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.
To disable href if onclick is executed with JavaScript, we call preventDefault to stop the default navigation action. document. getElementsById("ignore-click"). addEventListener("click", (event) => { event.
using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute. In other words, adding return false stops the href from working. In your example, this is exactly what you want.
This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.
Selecting a radio button will trigger an onclick event. If your event handler returns false, Internet Explorer will not change the state of any radio buttons.
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)
You need to actually return
the value in the onclick
that your function returned:
onclick="return validate_selected('owner');">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With