1
<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?

2

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

for elem.form.name showing error as cannot read property 'name' and $(elem).closest('form').attr('name') value is still showing undefined
its working here but in my code it showing error let me check again
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>

1 Comment

See my working snippet. Also Try my Alternate solution, which will work for you.
0

Simply from form tag.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.