Question

Am a novice with Jquery but I've put together code for a jquery search on select change alongside code for add/remove instance buttons, the idea being that the user selects an entry in a dropdown and the page returns a table containing info in a database. If required the user can then click a button to add a copy of the dropdown and select another entry etc etc.

I'm having a few issues with the code that performs the actual search, only the first dropdown actually sends and recieves any data, the others although they have the correct id's names etc do nothing.

What would be the best way of ensuring that each cloned group acts independently of the other?

        $(document).ready(function() {   
        // Am I correct in thinking that if this variable is read on load it will never update and always be 1 as there are no other cloned inputs.
        var num =  $('.clonedInput').length;

        $('#issue-drop' + num).change(function() {

            var qString = 'id=' +$(this).val();
            $.post('sub_db_handler.php', qString, processResponse);

        });

        function processResponse(data) {
            $('#results' + num).html(data);
        }

    });

Here is an example of my forms generated source

<div id="issues-wrap1" style="margin-bottom:4px;" class="clonedInput">
            <select name="Issues[]" id="issue-drop1">
                <option selected>Please Select...</option>
              </select>
            <div id="results1">

            </div>
        </div>

 <!-- Second div starts here -->

 <div id="issues-wrap2" style="margin-bottom:4px;" class="clonedInput">
            <select name="Issues[]" id="issue-drop2">
                <option selected>Please Select...</option>
              </select>
            <div id="results2">

            </div>
        </div>
Was it helpful?

Solution

You should use delegation: {see if its working for you}

 $(document).on('change','.clonedInput select',function() {

        var data = {id: $(this).val()};
        $.post('sub_db_handler.php', data, processResponse);

    });

OTHER TIPS

$('.clonedInput').length;  

This line will return the number of element with the class "clonedInput" in your page. In this case "2". You have to make a "for" so you can add event to every element.

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