Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the required attribute is set on a field

I have a simple form that has some required fields in it.

<form name="form" method="post">
<pre>
<label>     Name: </label><input type="text" name="name" required>
<label>  Address: </label><input type="text" name="add" required>
<label>Telephone: </label><input type="text" name="tel">
<input type="submit" value="Submit Form"> 
</pre>
</form>

I know you can set the required attribute using document.forms['form']['name'].required = false. But is there a way where you can just check if the required attribute is set or not? I tried using getattribute() but it just returns blank. I also tried using the code below, but it always executes the statement, even if the required attribute isn't set (e.g. on the telephone field).

 if( document.forms['form']['name'].required = true)
     label.innerHTML += " (required)"

Does anyone know of a way I can do this?

Update: Both setting the if statement to == instead of = and using hasAttribute work, thanks.

like image 711
Harry12345 Avatar asked Oct 19 '13 16:10

Harry12345


1 Answers

Try this :

var elem = document.getElementsByTagName('input')[0];

if(elem.hasAttribute('required')){
//do your stuff
}
like image 152
super Avatar answered Oct 05 '22 00:10

super