Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  179] [ 4]  / answers: 1 / hits: 23698  / 11 Years ago, thu, january 30, 2014, 12:00:00

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..



       <!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;

if (countryValue == )
{
alert(field value missing);
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == )
{
alert(state field value missing);
return false;
}
}

</script>
</head>
<body>
<form method = post action = 33.html>
Country: <input type=text id=count ID>
state: <select id=state ID>
<option></option>
<option value=ap>ap</option>
<option value=bp>bp</option>
</select>
<br>
<input type = submit>
</form>
<script>window.onload=f1</script>

</body>
</html>


Please help.


More From » html

 Answers
3

Have a look at this since you have messed up the IDs



Live Demo



window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == ) {
alert(Please enter a country);
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert(Please select a state);
return false;
}
return true; // allow submission
}
}


PS: It is likely that POSTing to an html page will give you an error



To get the last button to do the submission



window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}

[#72852] Wednesday, January 29, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;