Reputation: 95
Here is a function that simply checks if a radio button has been selected on a form element.
function validate_selected(element) {
var radios = document.getElementsByName(element);
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must select one before moving on!");
return formValid;
}
Here is my link that I want disabled if the function returns false. Right now the link shows the alert but after the alert the link sends the user forward.
<a href="#m2" data-role="button" onclick="validate_selected('owner');"><p style="font-size:<?php echo $size1.'px'; ?>;">Next</p></a>
I want the link to be disabled if the function returns false.
Upvotes: 5
Views: 2499
Reputation: 16103
You almost got it, you needed to add the 'return' in the function aswell:
onclick="return validate_selected('owner');"
Also a small tip, add a break:
while (!formValid && i < radios.length) {
if (radios[i].checked){
formValid = true;
break; // No need to continue any more, we've found a selected option
}
i++;
}
I've changed your onclick
from inline to the proper way to handle events, and made a working demo. Just remove the onclick from the button and add this:
document.getElementById('button').onclick =function(){ validate_selected('owner'); };
http://jsfiddle.net/WX6v7/1/ (added some radiobuttons in the example)
Upvotes: 7
Reputation: 56429
You need to actually return
the value in the onclick
that your function returned:
onclick="return validate_selected('owner');">
Upvotes: 3