I have a simple PHP script with a form that has two select fields, both of which are simply numerical values. The script also has a maximum for the sum of the two fields. I’m trying to dynamically filter the second drop down, so that a user cannot select more than the maximum. E.g., if my maximum is 10, the first select dropdown would have 1-10 in it. A user selecting 6 would then only be able to select 0-4 in the second select dropdown.
I know this should be reasonably straightforward, but I’m a total JavaScript/jQuery novice. I have searched SO and Google, but I don’t understand enough of the examples I’ve seen to know where to start, let alone figure out how to customise them to my needs. I’ve provided the code I have already, which clearly doesn’t have any of the filtering I need.
Some sample code (assume $maximum defined already):
<script type="text/javascript">
var max = <?php echo $maximum; ?>;
</script>
<select name="dropdown1" id="dropdown1">
<?php
for ($i = 1; $i <= $maximum; $i++)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
<select name="dropdown2" id="dropdown2">
<?php
for ($i = 0; $i <= $maximum; $i++)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
Thanks in advance.
I now have the following piece of jquery in it’s own .js file:
$(document).ready(function() {
// var max ??
$("#dropdown1").change(function() {
var selectedVal = $(this).find("option:selected").val();
$("#dropdown2 option").removeAttr("disabled").removeAttr("selected");
$("#dropdown2 option").each(function() {
if($(this).val() > max - selectedVal*1)
$(this).attr("disabled", "disabled");
});
});
});
However, I’m a bit stuck getting $maximum from my PHP script into the jQuery. I figure I have to create a JavaScript variable, but not quite sure how to pass it to the jQuery. I can figure out how to do it if I had the jQuery embedded in the same PHP script, just by echoing it out, but not quite so sure about passing it as a parameter.
I update code of legendofawesomeness for your case