<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?
<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?
- This might help. stackoverflow./questions/1621714/jquery-find-parent-form and stackoverflow./questions/991367/… – Shrinivas Shukla Commented Aug 4, 2015 at 5:22
- Thanx @ShrinivasShukla .This also works – kumar91 Commented Aug 4, 2015 at 6:22
3 Answers
Reset to default 4Since 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./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>
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./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./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>
Simply from form tag.
var formName = $('form')[0].name;
alert(formName);