1

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!");
    });
Sanfly
  • 1,021
  • 1
  • 11
  • 19

1 Answers1

2

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(){
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • Ummmmm, I'd like to know what's wrong with this; the value really does not change... – jeroen Jul 04 '16 at 10:16
  • i'm not a downvoter to your answer , but if the fields are generated dynamically , for javascript they do not exist yet. – Arsh Singh Jul 04 '16 at 10:17
  • @ArshSingh True, I might have (mis?)read "populated" as being modified, not being added. If they are not there yet, event delegation is needed. Will update... – jeroen Jul 04 '16 at 10:19
  • @jeroen glad you got what i said , you can pick up my answer's code , it will work without problem. – Arsh Singh Jul 04 '16 at 10:20
  • @Diederik Funny, I didn't know that. Doesn't make sense at all though :-) – jeroen Jul 04 '16 at 10:23
  • 1
    The .change definitely works on fields that are not populated/added using jQuery, I tested that. However, the event delegation thing was spot on - wasn't even sure what to search for - thanks! – Sanfly Jul 04 '16 at 10:49