Reputation: 33
I am creating a user form. In this I have textbox and a lot of number of select dropdown. After submitting I send all the value to database by $_POST. My form is like This:
<tr>
<td>Review Employee Id</td>
<td><input type="text" name="rcode" id="rcode" class="genInputBox" /></td>
</tr>
<tr>
<td>Quality of Delivery</td>
<td>
<select name="qd" id="qd">
<option value="">Plz Select Ratting </option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select>
</td>
</tr>
And more select boxes.........
and for select box validtion I am using like this
var qd = document.product.qd.options[document.product.qd.selectedIndex].value;
if (qd == "") {
error_message = error_message + "Please select Rating In domain Knowledge\n";
error = 1;
}
I mentioned lot of select boxes in the form. So my question is can I use a single select box validation script for all select boxes?
I use this answer In this manner
var sels = document.product.getElementsByTagName("select");
for (var i=0,n=sels.length;i<n;i++) {
if (sels[i].selectedIndex<1) {
alert(sels[i].options[0]); // alerts Plz Select whatever
sels[i].focus();
error_message = error_message + "Please select drop down\n";
error = 1; }
}
if (error == 1) {
alert(error_message);
return false;
} else {
return true;
}
}
but now if a left only 1 single select drop down without check,then its show 10 error message for selectbox.
Upvotes: 3
Views: 1525
Reputation: 177950
Like this - plain JS -
window.onload=function() {
var form = document.getElementsByTagName("form")[0]; // assuming first form on page
form.onsubmit=function() {
var sels = form.getElementsByTagName("select");
for (var i=0,n=sels.length;i<n;i++) {
if (sels[i].selectedIndex<1) {
alert(sels[i].options[0]); // alerts Plz Select whatever
sels[i].focus();
return false; // disallow submit
}
}
return true; // allow submission
}
}
Upvotes: 2
Reputation: 100175
Yes you can, like:
var firstSelectLen = document.product.qd.length; var secondSelectLen = document.product.qd1.length; // and so on for all selects you have //then loop with lengths to check if any selected //and show error msg accordingly
Hope it helps
Upvotes: 0