【问题标题】:When selecting radio button, how can I test if another is already selected?选择单选按钮时,如何测试是否已经选择了另一个?
【发布时间】:2019-05-25 01:58:08
【问题描述】:

我有一个表格,每行有 2 个单选按钮组 - 这是一系列问题的是/否选择。

选择“是”会增加一个变量以跟踪“是”答案的总数。除非已经选择了 YES,否则选择 NO 不会执行任何操作,在这种情况下,它会减少总数。

我可以增加 YES easy peasy。问题是在选择NO时检测YES的状态,因为通过选择NO,在我可以测试之前不再选择YES。薛定谔的按钮?

如何在更改之前单击“否”并测试“是”的状态?

<input type='radio'  id = 'q1Y' name='q1' value='1Y' onChange='countY(this.id);'>
<input type='radio'  id = 'q1N' name='q1' value='1N'  onChange='countN(this.id);'>

function countN(id){
q = id.slice(0, -1);
/////////////////
//
// The problem is here.  By the time the code reaches this point, Y is already unchecked
//
////////////////
if($('#'+q+'Y').prop('checked')===true){
    score--;
    $("#scoretotal").html(score);
}

}

【问题讨论】:

  • 请发布您的代码。
  • 你真的需要一个总和,还是用户回答完所有问题后才能计算总和?
  • 当然,但为什么代码甚至相关?问题很明确。
  • 使用change事件代替点击事件。如果单击已选择的按钮,则不会调用事件侦听器。
  • 这不太对,如果最初都没有检查。

标签: javascript jquery forms radio-button


【解决方案1】:

您可以使用onmousedown 代替onchange。这在更改按钮的值以反映单击结果之前运行。

但不是递增和递减运行计数,而是只计算所有 YES 按钮以获得总数。

function count() {
    var total = $(":radio[value$=Y]:checked").length;
    $("#scoretotal").html(total);
}

【讨论】:

  • 这是一个很好的解决方案,我仍然对是否可以检查另一个按钮的状态的答案感兴趣 - 现在出于好奇;o)
  • onmousedown 处理程序中执行此操作,这将在值更改之前运行。
  • 是否可能与此解决方案无关。该解决方案没有基于另一个单选按钮先前状态的条件逻辑,而是通过一条途径获得相同的最终结果。
【解决方案2】:

每次单击集合中的按钮时,只需增加或减少一个计数器。确保检查

// Get both buttons into an Array
let yesNo = Array.prototype.slice.call(document.querySelectorAll(".yesNo"));

let total = document.getElementById("total");

let yesses = 0;

// Loop the Array
yesNo.forEach(function(btn){
  // Set up event handler
  btn.addEventListener("click", function(){
    if(this.value === "Yes"){
      yesses++;
    } else {
      yesses = yesses - 1 <= 0 ? 0 : yesses - 1;
    }
    
    total.textContent = yesses;
  });
});
<input type="radio" name="yesNo" value="Yes" class="yesNo"> Yes
<input type="radio" name="yesNo" value="No" class="yesNo"> No
<div id="total"></div>

【讨论】:

    【解决方案3】:

    您可以使用对象来映射答案的值,以便跟踪哪些答案得到了回答。 如果两个函数(countY 和 countN)具有相似的功能,您还可以重用代码,如下所示:

    <input type='radio'  id = 'q1Y' name='q1' value='1Y' onChange='count(this.name, true);'/>
    <input type='radio'  id = 'q1N' name='q1' value='1N'  onChange='count(this.name, false);'/>
    
    
    var map = {};
    function count(id, bool){
        map[id] = bool;
        let scoreTotal = Object.keys(map).filter(keyName => map[keyName]).length;
        // if you want to know how many NOs
        let negative = Object.keys(map).filter(keyName => map[keyName] === false).length;
        $("#scoretotal").html(scoreTotal);
    }
    

    【讨论】:

      【解决方案4】:

      这是有效的,我很欣赏 cmets 和答案,他们为我指出了一个解决方案。

      var score=0;
      $('input[type=radio]').mousedown(function(){
      
         question = this.value.slice(0, -1) // which button group?
         YN = this.value.substr(this.value.length - 1); // Y or N?
      
        if(YN=="Y"){
           $('#q'+question+'Y').prop('checked', true);  // set the buttons
           $('#q'+question+'N').prop('checked', false);       
           score++;
           $("#scoretotal").html(score);
        }
        else{
            if($('#q'+question+'Y').prop('checked')){ 
            //This is the test that made the difference because the other button hadn't been unchecked yet
                score--;
                $("#scoretotal").html(score);
             }
             $('#q'+question+'Y').prop('checked', false); //set the buttons
             $('#q'+question+'N').prop('checked', true);
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2011-11-05
        • 2016-09-24
        • 2013-05-06
        • 2020-01-21
        • 1970-01-01
        • 2014-04-09
        • 2021-10-21
        • 1970-01-01
        • 2012-05-03
        相关资源
        最近更新 更多