简体   繁体   English

使用Jquery AJAX复选框

[英]Using checkboxes with Jquery AJAX

I am using JQuery for some AJAX functionality. 我正在使用JQuery来实现一些AJAX功能。 But when is pass the value of a checkbox, the value is show regardless of whether the checkbox is ticked or not. 但是当传递复选框的值时,无论是否勾选复选框,都会显示该值。 Here is my code: 这是我的代码:

$(document).ready(function(){ 
  $('#submitform').click(function(){
    $.ajax({
      type: "POST",
      url: "abs_newabs_check.asp",
      data: { allday: $("#allday").val() },
      success: callback
    });
  });
});

function callback(data, status)
{
    $("#ajaxdiv").html(data);
}

What am I doing wrong? 我究竟做错了什么? Any help appreciated. 任何帮助赞赏。 Thanks. 谢谢。

The value of your checkbox, as accessed by val() will always be corresponding to the value property of the input. val()访问的复选框的value将始终对应于输入的value属性。 Which is always set, regardless of the checkbox's checked-state. 无论复选框的检查状态如何,始终设置哪个。 What you want to check for is checked property: 您要检查的是已checked属性:

{ allday: $('#allday').is(':checked') }

or if you really do want to pass the value, when it's checked: 或者,如果您确实想要传递该值,则在检查时:

{ allday: $('#allday').is(':checked') ? $('#allday').val() : '' }

Checkboxes are annoying little buggers. 复选框是烦人的小虫子。 You have to actually check if the "checked" attribute is checked on the checkbox and if it is, only then do you want to apply the value. 您必须实际检查复选框上是否选中了“已检查”属性,如果是,则只需要应用该值。

So if you have a checkbox 所以如果你有一个复选框

<input type="checkbox" name="sports" value="soccer"  />

you want to check that the checked attribute has been set on it 您想要检查是否已在其上设置了checked属性

<input type="checkbox" checked="yes" name="sports" value="soccer"  />

The value will always be the same, it's the state that changes 值总是相同的,它是改变的状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM