Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery check checkbox by id in function

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.

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>

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.

like image 377
Rob Avatar asked May 31 '13 17:05

Rob


2 Answers

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

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

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

like image 90
Arun P Johny Avatar answered Oct 18 '22 07:10

Arun P Johny


If it's the ID, you can do:

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

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

like image 25
tymeJV Avatar answered Oct 18 '22 08:10

tymeJV