I have a simple form where a user can choose a colour and then a thing from that colour category. The second select input updates based on the first input.
I have a jQuery script which allows me to target the first element based on id and change the next one accordingly when it’s id is specified. Now I want to make this into a reusable script so that I can choose ANY select and update the NEXT select accordingly. I can take care of the internal logic (url,GET parameter).
In my jQuery script: get parameter), but I can’t figure out how to target the next select element after the one selected (I tried with next() but it didn’t work).
$(document).ready(function () {
var nextSelect = $('#id_colour');
nextSelect.change(function () {
function updateChoices() {
var selected = nextSelect.val();
if (selected) {
// this line shown for completeness - will be refactored
$.getJSON(url, {
colour_id: selected
}, function (data, jqXHR) {
var options = [];
for (var i = 0; i < data.length; i++) {
output = '<option value="' + data[i].id + '"';
if (nextSelect.val() == data[i].id) {
output += ' selected="selected"';
}
output += '>' + data[i].name + '</option>';
options.push(output);
}
$('#id_thing').html(options.join(''));
});
}
}
updateChoices();
$('#id_thing').change(updateChoices);
});
});
Any help much appreciated.
EDIT
Here is the html. So I want that when one is changed the NEXT will be targeted. I cannot rely on ids or classes.
<form action="" method="post">
<!-- colour -->
<div class="form_div">
<p><label for="colour">Colour:</label></p>
<p>
<select name="colour" id="id_colour">
<option value="" selected="selected">---------</option>
<option value="1">Green</option>
<option value="2">Brown</option>
<option value="3">Blue</option>
</select>
</p>
</div>
<!-- thing -->
<div class="form_div">
<p><label for="thing">Thing:</label></p>
<p>
<select name="thing" id="id_thing">
<option value="" selected="selected">---------</option>
<option value="1">Branch</option>
<option value="2">Leaf</option>
<option value="3">Sky</option>
</select>
</p>
</div>
<p><input type="submit" value="Submit Choice" /></p>
</form>
If you want to make reusable code (which may be used within other scripts), you can create a utility function:
Just call nextSelect with three parameters; (1) the first select, (2) the second select which will change according to select1, (3) the url where you do the request.
JQuery (v1.8.2):
The HTML (I just shortened it):
Here is a fiddle
If this was not what you were looking for, come with feedback and I will adjust the code.
Cheers!
EDIT:
Ok, so if I understood correctly you want to be able to select the first ‘select’ –> meaning you in some form need to hardcore the referencing of an id/class. This doesn’t need to be the select itself, it can be a wrapper class. The second select would be automatically selected.
Modified the code and the fiddle to adjust for it.