0
<form name="FNAME">  
    <div id="div1">  
        <ul id="ul1"><li id="li1"><a href="" onclick="getValue(this);">Click</a>  </li></ul>
    </div>  
</form>  

<script type="text/javascript">
    function getValue(elem) {
        formName = $(elem.form.name).val();
        alert(formName);
    }
</script>

I am trying to get the form name of the above code:
formName is undefined using above code
How could i get the value of form name inside the javascript function?

Nikunj Chotaliya
  • 792
  • 7
  • 19
kumar91
  • 43
  • 1
  • 1
  • 8

3 Answers3

4

Since you are using jQuery for cross browser support

function getValue(elem) {
  var formName = $(elem).closest('form').attr('name')
  alert(formName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="FNAME">
  <div id="div1">
    <ul id="ul1">
      <li id="li1">
        <a href="" onclick="getValue(this); return">Click</a> 
      </li>
    </ul>
  </div>
</form>
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
  • for elem.form.name showing error as cannot read property 'name' and $(elem).closest('form').attr('name') value is still showing undefined – kumar91 Aug 04 '15 at 05:34
  • its working here but in my code it showing error let me check again – kumar91 Aug 04 '15 at 05:36
2

Try to use closest() like,

function getValue(elem)    
{    
    formName=$(elem).closest('form').attr('name');  
    alert(formName);  
} 

function getValue(elem) {
  formName = $(elem).closest('form').attr('name');
  alert(formName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="FNAME">
  <div id="div1">
    <ul id="ul1">
      <li id="li1"><a href="" onclick="getValue(this);">Click</a> 
      </li>
    </ul>
  </div>
</form>

Alternatively, bind on click event using jquery like,

$(function(){
   $('#li1').on('click','a',function(e){
      e.preventDefault();
      alert($(this).closest('form').attr('name'));
   });
});

$(function(){
   $('#li1').on('click','a',function(e){
      e.preventDefault();
      alert($(this).closest('form').attr('name'));
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="FNAME">
  <div id="div1">
    <ul id="ul1">
      <li id="li1"><a href="" onclick="getValue(this);">Click</a> 
      </li>
    </ul>
  </div>
</form>
Rohan Kumar
  • 39,838
  • 11
  • 73
  • 103
0

Simply from form tag.

var formName = $('form')[0].name; alert(formName);

Rehan Khan
  • 11
  • 3