首页 > 解决方案 > 在jQuery中使用多个具有相同名称的单选框

问题描述

我第一次使用 jquery,我想从我的一个同名复选框中获取一个值。

我的代码是:

$(document).ready(function() {
  $('a#process_input').bind('click', function() {
    $(":checked").each(function() {
      $.getJSON('/management/avaliable_numbers', {
        num_of_numbers: $('input[name="num_of_numbers"]').val(),
      }, function(data) {
        $("#result").html(data.result);
      })
    });
    return false;
  });
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<div class='container'>
  <form>
    <div>
      <input type="radio" name="num_of_numbers" value="10"> 10
      <input type="radio" name="num_of_numbers" value="100"> 100
      <input type="radio" name="num_of_numbers" value="1000"> 1000
      <a href='#' id=process_input>
        <button type="button" class="btn">Choose</button>
      </a>
    </div>
    <p id=result></p>
</div>

这是 jquery+flask 教程中的现成代码,其中包含我在 Internet 上找到的资源的一些混搭。正如您所料,它并没有像我预期的那样工作。无论我选择哪个选项(即使我没有选择任何选项),该脚本都会将 10 发送到avaliable_numbers函数。

我正在寻找如何正确实现该功能的解释,因此当我不检查框上的任何内容时,它不会以任何方式传递给函数,而是传递相应的值。

提前感谢您的任何建议。

标签: javascriptjquery

解决方案


好的,我将对您的脚本进行一些更改(代码中的注释解释什么和原因)

    $(document).ready(function() {
      $('a#process_input').on('click', function(e) { // change bind to on as bind is deprectaed in jquery v3
                                                     // also pass the event back into the function

        e.preventDefault(); // stops the form submitting - you don't want it to reload the page - removes the need for returning false at the end

        if ($('input[name="num_of_numbers"]:checked').length) { // only do the following if there is something checked

          // remove each loop - not needed as you only want to pass the checked value to the json
          $.getJSON('/management/avaliable_numbers', {
            num_of_numbers: $('input[name="num_of_numbers"]:checked').val(), // just pass through the checked value
          }, function(data) {
            $("#result").html(data.result);
          });

        } else {
            $("#result").html('error message - please check a radio'); // nothing checked - might want an error message 
        }


      });
    });
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<div class='container'>
  <form>
    <div>
      <input type="radio" name="num_of_numbers" value="10"> 10
      <input type="radio" name="num_of_numbers" value="100"> 100
      <input type="radio" name="num_of_numbers" value="1000"> 1000
      <a href='#' id=process_input>
        <button type="button" class="btn">Choose</button>
      </a>
    </div>
  </form>             <!-- add missing form closing tag -->
  <p id=result></p>
</div>


推荐阅读