1

I have a checkbox item like this:

 $("#userRoleDiv-"+note_id).append(" \n\ <div><input name='userInput-"+note_id+"' type='checkbox' value='' id= '1' />Instructor</div>\n\ <div><input name='userInput-"+note_id+"' type='checkbox' value='' id= '2' />Students</div>\n\ "); 

Now, I want to check checkboxes having id 1 and/or 2 but has the same name, as given in the code. How can it be done?

3 Answers 3

2

You may try this too (It's clean). also don't need to use \n and notice checked:checked (only one)

var instructor = $('<input/>', { 'name':'userInput-'+note_id, 'id':1, 'type':'checkbox', 'checked':'checked' }); var students = $('<input/>', { 'name':'userInputs-'+note_id, 'id':2, 'type':'checkbox' }); $("#userRoleDiv-"+note_id).append( $('<div/>', {'text':'Instructor'}).prepend(instructor), $('<div/>', {'text':'Students'}).prepend(students) ); 

DEMO.

Sign up to request clarification or add additional context in comments.

Comments

0

Apply the checked attribute to the <input> element.

Also, you should wrap your inputs in <label> tags, so the label (Instructor and Student) will be clickable.

$("#userRoleDiv-"+note_id).append(" <label><input name='userInput-"+note_id+"' type='checkbox' id='1' checked />Instructor</label> <label><input name='userInput-"+note_id+"' type='checkbox' id='2' />Students</label> "); 

Comments

0

Given a name:

var name = 'userInput-1'; 

Select the checkboxes like this:

var checkboxes = $('input[name=' + name + ']').filter('#1, #2'); 

Then check them:

checkboxes.each(function () { this.checked = true; }); 

Note that I haven't tested this; it may require modifications in order to work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.