最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop link action if onclick function returns false - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Oct 3, 2013 at 15:10 BalusC 1.1m376 gold badges3.6k silver badges3.6k bronze badges asked Oct 3, 2013 at 14:54 user2843198user2843198 951 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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/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');">
发布评论

评论列表(0)

  1. 暂无评论