Question

I append some input textfields and checkboxes onclick. But when a checkbox is checked i want to toggleClass to the input textfield. This is my create code:

jQuery(function() {
var counter = 0;

$('#appendbtn').click(function() {
    var elems = '<div>' + '<input type="checkbox" id="checkbox"' + (counter) + '" class="item"/>' + '<input type="text" id="inputfield"' + (counter) + '"/>' + '</div>';
    $('#box').append(elems);
    counter++;
    return false;
});

This is what should happen;

if ($("#checkbox").is(":checked"))
 {
$("inputfield" + counter).toggleClass("complete")
 });

Ofcourse this isn't correct, but i hope you get what i mean ;) is this by the way possible without an if statement?

here is the jsfiddle http://www.jsfiddle.net/gkdKY/

oh and this is exactly what i want http://www.jsfiddle.net/xzmcL/ but with appended checkboxes!

Was it helpful?

Solution

This line:

var elems = '<div>' + '<input type="checkbox" id="checkbox"' + (counter) + '" class="item"/>' + '<input type="text" id="inputfield"' + (counter) + '"/>' + '</div>';

...has two extra quotes. It should be:

var elems = '<div>' + '<input type="checkbox" id="checkbox' + (counter) + '" class="item"/>' + '<input type="text" id="inputfield' + (counter) + '"/>' + '</div>';

That breaks your selector for the click event. But note, that won't work anyway, since you are trying to hook an element that does not exist until the 'click me' link is pressed - so you need to use .live() or .delegate() for that anyway.

Something like this might work:

$("#drag").delegate("input[type=checkbox]", "change", function(){
   var index = this.id.substring(8);
   $("#inputfield" + index).toggleClass("complete");
});

OTHER TIPS

You want:

$('input:checkbox').click(function(){
   $('#inputfield').toggleClass('bold');
});

I'm assuming you aren't setting your checkboxes' checked state to true dynamically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top