Sanfly Sanfly - 5 months ago 10
Ajax Question

jQuery Modification of Ajax Populated Form Fields

I have a form, and when a certain select box changes, it uses Ajax to populate some checkboxes. Works great.

However, when I check these checkboxes, I'd like to use jQuery to modify another part of the form - this does not seem to be working... the jQuery does not fire at all.

Is this something to do with when the jQuery loads vs the ajax request and its just impossible? Or is there likely an error somewhere in my code?

The Ajax.php page (which works just as expected)

... some other code ...
$fields = "";
$i = 0;
foreach($cols as $c){
$fields .= '<tr><td width="50%"><input class="fieldCheckBox" data-num="' . $i . '" type="checkbox" name="data[' . $_GET['t'] . '][fields][' . $i . '][field]" value="' . $c . '"> ' . $c . '</td><td width="50%"><input type="text" name="data[' . $_GET['t'] . '][fields][' . $i . '][fieldAs]" class="form-control" style="width: 150px;"></td></tr>';
$i++;
}

echo $fields;


And then my jQuery request (which isn't firing)

... document.ready function...
$(".fieldCheckBox").change(function(){
alert("were in!");
});

Answer

This is your problem:

$(".fieldCheckBox").change(function(){

The value of the checkbox is not actually changing so this will never execute.

Instead you can check for the click event for example:

$(".fieldCheckBox").click(function(){

Edit: If the checkboxes don't exist on page-load, when your javascript is executed, you need event delegation to make sure the events get registered.

A simple example:

$('body').on('click', '.fieldCheckBox', function(){