jQuery jquery复选框按id在函数中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16862884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:55:34  来源:igfitidea点击:

jquery check checkbox by id in function

javascriptjquery

提问by user1977434

I have a function which the name of a user is passed in and the ID of the checkbox will be that name, I'm trying to get jquery to check it by the ID, but no luck. the ID field of the checkbox is called by each user name so it needs to find the correct checkbox called by the 'name' passed in and check it.

我有一个函数,其中传入了用户名,复选框的 ID 将是该名称,我试图让 jquery 通过 ID 检查它,但没有运气。复选框的 ID 字段由每个用户名调用,因此它需要找到传入的“名称”调用的正确复选框并检查它。

function send_new_message(name)
{
var html = new_message_form();
var div = $(html);

//Set user clicked to checked
//$("#dave").prop("checked", true);
$("#" + name).prop('checked', true);   

div.find('.send').click(function()
{
//Remove any error message
$("p.error").html('');

//Error check
var name = $("input.name").val();
var message = $("#message").val();

if(message==""){
$(".error").html('This filed is required!');
$("#message").focus();  
return false;  
}

//Send message to be processed
var post_data = name + "##@##" + message;
$.post(
'frames/process_messages.php',
{name: name, message: message},
function(result){
alert(result);
}
);      
//Close
//div.dialog('close');
});

div.dialog(
{
title:"Send New Message",
width: 450,
show: {
effect: "fold",
duration: 500
},
hide: {
effect: "explode",
duration: 500
},
close: function(){
$(this).dialog("destroy");
$(this).remove();       
}
});
}

HTML (PHP echo's)

HTML (PHP 回声)

<tr><td><input class=\'names\' id=\''.$users[$i]['name'].'\' type=\'checkbox\' name=\'names[]\' value=\''.$users[$i]['id'].'\' /></td><td>'.$users[$i]['name'].'</td></tr>

rendered

渲染

<tr><td><input class='names' id='dave' type='checkbox' name='names[]' value='3' /></td><td>dave</td></tr>

does not seem to work :(

似乎不起作用:(

Thanks for any help.

谢谢你的帮助。

回答by tymeJV

If it's the ID, you can do:

如果是身,你可以这样做:

$("#" + name).prop('checked', true);

and use prop()when changing attributes that take boolean values.

prop()在更改采用布尔值的属性时使用。

回答by Arun P Johny

Use .prop()instead of .attr()to change runtime properties like checked and disabled

使用.prop()而不是.attr()来更改运行时属性,例如已选中和已禁用

$('#'+name).prop('checked', true);

You can read more about the difference in the documentation for .prop()

您可以在.prop()的文档中阅读有关差异的更多信息

回答by keith

I was able to get a handle on a specific checkbox with the following code:

我能够使用以下代码处理特定复选框:

var myCheckbox=$("input[name='checkbox_name']");
myCheckbox.change(function(){
     if(this.checked){
          alert('checked');
     } else {
          alert('unchecked');
     }
});