Reputation: 605
I want to read a value of a input in a form.
sometimes the the form contains the input
<form id="myform">
<input type="text" name="username">
<input type="hidden" name="userid" value="123">
</form>
sometimes the above input will not be in the form
<form id="myform">
<input type="text" name="username">
</form>
My problem is
I am reading the userid value which throws the error if the input is not there.
var form = document.getElementById("myform");
userid = form.userid.value;
Because of this error most of the script functionality is not working.
if(pack_id !=undefined && pack_id ==''){
pack_id=0;
}
please help me rectify the error
Upvotes: 1
Views: 809
Reputation: 318
var userIdCheck=$('#userId').val();
if(userIdCheck!=='undefined'){
alert("Ther is a input"+userIdCheck);
}
else{
alert("User Id does not contain the value");
}
Try this may helps you
Upvotes: 1
Reputation: 8496
you can check it by typeof method for userid property is exist or not in form JavaScript dom element object.
var form = document.getElementById("myform");
userid="";
if(typeof form.userid !=="undefined" )
{
userid = form.userid.value;
}
Upvotes: 1
Reputation: 831
You can apply undefined check before getting value
if(form.userid!=undefined){
userid = form.userid.value;
}
Upvotes: 1
Reputation: 15565
var ext = $('input[name=userid]').length;
if (ext) {
alert('input is here')
} else {
alert('not input is here')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input type="text" name="username">
</form>
Check the length like $('input[name=userid]').length
of the input it present or not
Upvotes: 1