How to handle multiple Jquery + Ajax dependent select boxes in the same form

admin

Administrator
Staff member
I can't figure out how to handle having more than one row of chained select boxes in a form using jquery and ajax.

There are plenty of tutorials available explaining how to create a single instance of chained selects, but unfortunately (for me, at least) they never discuss how to handle more than one instance/row of chained selects in the form.

I can get it working by explicitly writing different blocks of jquery code, as shown below, but my problem is that there can be any number of rows of chained selects that will be generated automatically.

To handle this, I need a single block of jquery code that can work on all of the rows of chained selects. Everything I've tried so far results in the typical newbie problem of not being able to get any of the rows of chained select boxes working other than the first one.

Here is the html:

Code:
<form>
    Connection Type :
    <select name="contype_01" id="contype_01">
      <option value="ssh">SSH</option>
      <option value="telnet">Telnet</option>
    </select>

    Credentials :
    <select name="creds_01" id="creds_01">
      <option> --Please Select-- </option>
    </select>

    <br /> <!-- 2nd row of chained selects -->

    Connection Type :
    <select name="contype_02" id="contype_02">
      <option value="ssh">SSH</option>
      <option value="telnet">Telnet</option>
    </select>

    Credentials :
    <select name="creds_02" id="creds_02">
      <option> --Please Select-- </option>
    </select>
  </form>

And the jquery:

Code:
 $(document).ready(function(){

    $("#contype_01").change(function(){
        var contype=$("#contype_01").val();
        $.ajax({
            type:"post",
            url:"ncmexport-helper.php",
            data:"contype="+contype,
            success:function(data){
                $("#creds_01").html(data);
            }
        });
    });

    $("#contype_02").change(function(){
        var contype=$("#contype_02").val();
        $.ajax({
            type:"post",
            url:"ncmexport-helper.php",
            data:"contype="+contype,
            success:function(data){
                $("#creds_02").html(data);
            }
        });
    });


});

If you've made it this far I thank you, and here is my question: What do I need to do to turn the two blocks of jquery code shown above into a single block that can work with multiple chained selects in a form? My very limited javascript and jquery skills are not yet sufficient enough for me to know how to iterate over the different select box id's.

Note: the original jquery / ajax code I'm using came from this tutorial:
<a href="http://phpseason.wordpress.com/2013/02/19/dynamic-dependent-select-box-using-jquery-and-ajax/" rel="nofollow">http://phpseason.wordpress.com/2013/02/19/dynamic-dependent-select-box-using-jquery-and-ajax/</a>