Checkbox jquery check by id in function

I have a function in which the username is passed, and the checkbox identifier is the name, I'm trying to get jquery to check it by identifier, but no luck. the checkbox identifier field is called by each username, so he needs to find the correct checkbox called "name" and check it.

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)

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

it turns out

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

doesn't seem to work :(

Thanks for any help.

+4
source share
3 answers

If it is an identifier, you can do:

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

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

+11
source

Use . prop () instead . attr () change runtime properties such as checked and disabled

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

Read more about the differences in the documentation for . prop ()

+5
source

I was able to process a specific flag with the following code:

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

Source: https://habr.com/ru/post/1483843/


All Articles