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.
Try this :
var elem = document.getElementsByTagName('input')[0];
if(elem.hasAttribute('required')){
//do your stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With