Reputation: 4521
Objective: Fix the code below, and understand why focusing on radio buttons doesn't work like focusing on text input boxes.
Question: Why does this not work:
function isValidRadio(elem, helperMsg) {
var valid = false;
for (var i = 0; i < elem.length; i++) {
if (elem[i].checked) {
return true;
}
}
alert(notice);
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
}
...when this does:
function isValidText(elem, notice) {
var str = elem.value;
var re = /.+/;
if(!str.match(re)) {
alert(notice);
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
} else {
return true;
}
}
Example Code:
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
elem.focus();
elem.select();
}
function validateForm(form) {
if (isValidText(form.phone, "Fail.")) {
if (isValidRadio(form.yesNo, "Fail.")) {
return true;
}
return false;
}
}
<form id='myForm' action='/formPage/collectinfo/' method='post' accept-charset='UTF-8' name="myForm">
<input name="phone" type="text" maxlength="14" size="14" />
<input type="radio" name="yesNo" value="Yes"> Yes <input type="radio" name="yesNo" value="No" > No
<input type="submit" value=" Submit " name="Submit" onclick="return validateForm(myForm)" />
Details: I'm using php/javascript/html and so far I've only been testing this piece in Chrome. The form works just fine and the validation works up until it hits isValidRadio. The alert runs, but then the javascript breaks. A code fix would be great, but I wouldn't mind 'fishing for a life time...'
Upvotes: 0
Views: 11858
Reputation: 4521
Alright, I found the solution, AlienWebguy put me on the right track thinking about arrays. I just needed to specify which radio button to focus on as opposed to which set. Here is the working code:
// Validate that the user has checked one of the radio buttons
function isValidRadio(radio, helperMsg) {
var valid = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
return true;
}
}
alert(helperMsg);
radio[0].focus();
return false;
}
Called via: isValidRadio(form.yesNo, "Error.")
Thanks for the assist.
Upvotes: 2