jQuery检查多个单选按钮的值

时间:2013-07-24 13:13:49

标签: jquery select radio-button

我有一系列单选按钮如下:

<input type="radio" name="r1" value="1" />
<input type="radio" name="r1" value="2" />
<input type="radio" name="r1" value="3" />
<input type="radio" name="r1" value="4" />
<input type="radio" name="r1" value="-1" />

<input type="radio" name="r2" value="1" />
<input type="radio" name="r2" value="2" />
<input type="radio" name="r2" value="3" />
<input type="radio" name="r2" value="4" />
<input type="radio" name="r2" value="-1" />

<input type="radio" name="r3" value="1" />
<input type="radio" name="r3" value="2" />
<input type="radio" name="r3" value="3" />
<input type="radio" name="r3" value="4" />
<input type="radio" name="r3" value="-1" />

我需要做的是检查所选的任何单选按钮是否具有值equal to or less than 2 but greater than zero,然后运行一些代码或greater than 2如果他们这样做,再运行一些代码。

我之前使用javascript实现了这一点,但这是一个漫长而费力的过程。有没有一种有效的方法来实现这个?

5 个答案:

答案 0 :(得分:3)

$('input[type="radio"]:checked').each(function() {
    if (this.value > 0 && this.value <= 2) {
       // do something if the value is less than zero and below or equal to two
    }else if (this.value > 2) {
       // do something else if the value is greater than two
    }
});

答案 1 :(得分:0)

$('input[type=radio]').on('change', function(){
  if((this.val() > 0) && (this.val() <=2)) {
    //Todos
   }
  else if(this.val() > 2) {
   //Todos
   }    
});

答案 2 :(得分:0)

var $lessOrEqual2AndGreatZero = $('input[type="radio"]:checked').filter(function(elem){
    return ($(elem).val() > 0 && $(elem).val() <= 2);
});


if ($lessOrEqual2AndGreatZero.length){
   // code
} else {
    var $greaterThanTwo = $('input[type="radio"]:checked').filter(function(elem){
        return ($(elem).val() > 2);
    });
    if ($greaterThanTwo.length){
        // more code
    }
}

答案 3 :(得分:0)

如果我理解你的问题:

var check = $(':radio:checked').is(function () {
    return this.value <= 2 && this.value > 0
});

if(check)
   //at least one radio button which is checked as value > 0 but less or equal to 2

答案 4 :(得分:0)

var radios = $('input[type="radio"]');

function areAnyInRange() {
    return radios.filter(':checked').filter(function() {
       return (+this.value > 0 && +this.value <= 2);
    }).length > 0;
}

function inRange() {
    if(areAnyInRange()) {
       console.log('radios in range!');    
    } else {
        console.log('no radios in range :(');   
    }
}

inRange();
radios.change(inRange);

jsfiddle:http://jsfiddle.net/JZfeT/1/

代码的工作原理:

  • areAnyInRange循环检查无线电,如果有则返回true 值在范围内
  • 这个乐趣在代码执行时调用一次,然后每次无线电更改