0

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

<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 实现了这一点,但这是一个漫长而费力的过程。jQuery中有没有一种有效的方法来实现这一点?

4

5 回答 5

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
    }
});
于 2013-07-24T13:16:32.770 回答
0
$('input[type=radio]').on('change', function(){
  if((this.val() > 0) && (this.val() <=2)) {
    //Todos
   }
  else if(this.val() > 2) {
   //Todos
   }    
});
于 2013-07-24T13:18:15.600 回答
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
    }
}
于 2013-07-24T13:19:53.720 回答
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
于 2013-07-24T13:21:27.153 回答
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
  • 这个乐趣在代码执行时被调用一次,然后每次收音机改变时
于 2013-07-24T13:26:10.557 回答