Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  100] [ 1]  / answers: 1 / hits: 22741  / 11 Years ago, sat, october 19, 2013, 12:00:00

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.


More From » html

 Answers
32

Try this :



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

if(elem.hasAttribute('required')){
//do your stuff
}

[#74874] Friday, October 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
;