[英]Checkbox is checked, but :checked doesn't work
I have a few checkboxes. 我有几个复选框。 I'm setting and resetting the default values of the checkboxes with the .prop() function, based on a JSON response (loading the data via ajax-requests).
我正在基于JSON响应(通过ajax-requests加载数据)使用.prop()函数设置和重置复选框的默认值。 The problem is, that they apparently don't change this behaviour, if I change them manually.
问题是,如果我手动更改它们,则它们显然不会更改此行为。 I can't pass the value of the checkboxes via $('#checkbox :checked').val(), a console log says 'undefined'.
我无法通过$('#checkbox:checked')。val()传递复选框的值,控制台日志显示“未定义”。 Is this because of the .prop() function?
这是因为.prop()函数吗? How can I get the value of the checked checkboxes?
如何获取已选中复选框的值?
If you need more information, i'll gladly provide them. 如果您需要更多信息,我会很乐意为您提供。 Here some code:
这里有一些代码:
if (json.event.public_visible == 1) {
$('#event_public_visible').prop('checked', true);
} else {
$('#event_public_visible').prop('checked', false);
}
if (json.event.package_event == 1) {
$('#event_package_only').prop('checked', true);
} else {
$('#event_package_only').prop('checked', false);
}
Update: more code 更新:更多代码
var editEvent = function () {
if ($('#event_public_visible').is(':checked')) {
console.log('test');
}
formData = {
// ... other fields
event_package_only: $('#event_package_only :checked').val(),
event_public_visible: $('#event_public_visible :checked').val(),
// ... more fields
};
$.ajax({
url: base_url + "admin/events/editAsync",
type: "POST",
data: formData,
dataType: "json",
success: function (json) {
// success handling
}
});
};
Try this: $('#event_public_visible:checked').val()
and $('#event_public_visible:checked').val()
试试这个:
$('#event_public_visible:checked').val()
和$('#event_public_visible:checked').val()
You can try: ('#event_public_visible:checked').length ? $('#event_public_visible:checked').val() : '';
您可以尝试:
('#event_public_visible:checked').length ? $('#event_public_visible:checked').val() : '';
('#event_public_visible:checked').length ? $('#event_public_visible:checked').val() : '';
Example: http://jsfiddle.net/infernalbadger/SfcjG/ 示例: http : //jsfiddle.net/infernalbadger/SfcjG/
You're setting a property on elements with an IDs of 'event_public_visible' and 'event_package_only' and then trying to read from an element of ID 'checkbox'. 您正在为ID为'event_public_visible'和'event_package_only'的元素设置属性,然后尝试从ID为'checkbox'的元素读取。
Did you mean to use this? 你是说要用这个吗?
$('[type=checkbox]:checked').val()
Can see it working here: 可以看到它在这里工作:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.