views:

40

answers:

1

Hi,

I am trying to create dynamic selection boxes with Jquery.

Due to requirements, I have 5 selection boxes with similar Class contents e.g. Class A, Class B, Class C, etc. I have another 5 Student selection boxes besides each of the Class selection boxes.

So the idea is that when I select a class selection box, javascript will check on the selection and proceed to send the selection value using GET action, and return the contents for my Student selection box.

I already have a working script. But it is only working for one Class selection box, and if I need to have it running for the rest of the 4 Class selection boxes, I will have to create 4.js script with the different values.

May I know is there any way that I could just use 1 js and works for all the 5 Class selection boxes? Maybe a loop, or etc?

Working js for 1 selection box:

function class_change() {
    $('#class1').change(update_students);  
        // the rest of the class sel boxes are named as #class2 #class3, etc.
}

function update_students() {
    var class = $('#class1').val();
    var seat = $('#seat1').val();   
    $.get('getStuds.php?seatno='+seat+'&class='+class, showStudents);
}

function showStudents(result) {
    $('#show_student1').html(result);
}

$(document).ready(class_change);

Thank you very much.

A: 

ok let's try this...

let's say you have your markup like this for each set of classes:

<select id="c-1" class="classes">
<option>Class A</option>
<option>Class B</option>
</select>
<select id="s-1" class="students">
<option>1</option>
<option>2</option>
</select>
<div id="show-1"></div>

then modify your code a bit

function class_change() {
    $('.classes').change(update_students);  
    // set classname for all your class selectboxes to "classes"
}

function update_students() {
    var classSelBox = $(this);
    var className = classSelBox.val();
    var classID = classSelBox[0].id.split('-')[1]; // so we only need the number 1 in for example "c-1"
    var seat = $('#s-' + classID).val();   
    $.get('getStuds.php?seatno='+seat+'&class='+className, function(result) {
        // lets use the power of closures here
        showStudents(result, classID); 
    });
}

function showStudents(result, id) {
    $('#show-' + id).html(result);
}

$(document).ready(class_change);

Hope this helps.

ricecake5