javascript / jquery获取新选中复选框的值

时间:2017-04-06 10:53:24

标签: javascript php jquery

以下是我的代码

<script>
$(document).ready(function() {
    var ckbox = $('#checkbox');
    var url = '';
    console.log(url);

    $('input').on('click', function() {

        if(ckbox.is(':checked')) {
            var url = $(':checked').val();
            console.log(url);
            window.location = url;
        }
    });
});

我的javascript / jquery脚本是

alert"('hello world')"

我希望页面转到新选中的复选框。如何实现?

3 个答案:

答案 0 :(得分:2)

 $(document).ready(function() {
        var ckbox = $('.clscheckboxes');
        var url = '';

        $('input[type=checkbox]').change(function() {
  if ($(this).is(':checked')) {
     var url = $(this).val();
                console.log(url);
                alert(url);
  } 
});
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" id="checkbox1" class="clscheckboxes" value="brand.php?brand=bmw" name="bmw" <?php echo $checked; ?> > BMW</li>
    <input type="checkbox" id="checkbox2" class="clscheckboxes" value="brand.php?brand=toyota" name="toyota"> Toyota</li>
    <input type="checkbox" id="checkbox3" class="clscheckboxes" value="brand.php?brand=farari" name="farari" checked > Farari</li>
    <input type="checkbox" id="checkbox4" class="clscheckboxes" value="brand.php?brand=nissan" name="nissan" checked > Nissan</li>

答案 1 :(得分:2)

id应该是整个文档中的唯一值。更改HTML以使每个复选框具有唯一ID,并根据类或输入类型修改jQuery选择器。

检查以下示例。

&#13;
&#13;
$(document).ready(function() {
  $('.chkbox').on('change', function() {
    if ($(this).is(':checked')) {
      var url = $(this).val();
      console.log(url);

      window.location = url;
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" id="checkbox1" class="chkbox" value="brand.php?brand=bmw" name="bmw"> BMW</li>
<input type="checkbox" id="checkbox2" class="chkbox" value="brand.php?brand=toyota" name="toyota"> Toyota</li>
<input type="checkbox" id="checkbox3" class="chkbox" value="brand.php?brand=farari" name="farari" checked> Farari</li>
<input type="checkbox" id="checkbox4" class="chkbox" value="brand.php?brand=nissan" name="nissan" checked> Nissan</li>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

还有一个示例代码。希望它能运作。

JQuery代码

$( ".checkbox" ).click(function() {
    if ($(this).is(":checked"))
    {
        var page_url = $(this).val();
        window.location = page_url;
    }
});

<强> HTML

<input type="checkbox" class="checkbox" value="brand.php?brand=bmw" name="bmw"> BMW</li>
<input type="checkbox" class="checkbox" value="brand.php?brand=toyota" name="toyota"> Toyota</li>
<input type="checkbox" class="checkbox" value="brand.php?brand=farari" name="farari"> Farari</li>
<input type="checkbox" class="checkbox" value="brand.php?brand=nissan" name="nissan"> Nissan</li>