Reputation: 644
I'm trying to use jQuery to fire off a javascript function whenever the selected option changes in a dropdown list.
The options of this dropdown list (insurance carriers) change each time the form is filled out. Options are populated by an event from a previous form field (onblur when user enters a case number), php is used to query a database and populate the dropdown list with each potential insurance carrier. Different case numbers result in different insurance providers showing up as options in the dropdown list, so the options are never the same each time a user fills this form.
Like stated previously, after the options are populated I'm trying to call another js function when the user selects a different insurance carrier from the dropdown.
On page load, the html for the form dropdown looks like this, simple:
<tr>
<tr><td><span class="qText" name="insurer">2. Insurer:</span></td></tr>
<td><select class="qAns" name="insurer_a1">
<option>Please enter a case number</option>
</select></td>
</tr>
Once a case number is entered in a previous field, the dropdown populates with however many potential insurance carriers are available for that case.
I tried to use something like this:
<script>
$("#insurer_a1").change(function(){
getAdjuster1();
});
</script>
I also tried this:
$(function() {
$("#insurer_a1").change(function() {
getAdjuster1();
});
});
Is what I'm trying to do much more difficult than I anticipated, because the dropdown options are not static?
Upvotes: 0
Views: 63
Reputation: 58
From what you are saying the values in the select list constantly change and you need to grab that value and pass it off to a javascript function. The easiest way that I have found to do this is by using the onchange event. I have rewritten your code below as an example.
<tr>
<tr><td><span class="qText" name="insurer">2. Insurer:</span></td></tr>
<td><select class="qAns" id="insurers" name="insurers" onchange="getAdjuster(this.value)">
<option value="1">case number 1</option>
<option value="2">case number 2</option>
</select></td>
Sript Code
<script>
function getAdjuster(case_number){
//your code that executes
}
</script>
Upvotes: 0
Reputation: 417
There are some problems:
insurer_a1
is not an id, it's a nameselect
tag, right now, you only have one option, so you cannot change it.In the following code, you print "dropdown changed!" when it is changed.
function getAdjuster1() {
console.log("dropdown changed!")
}
$("[name=insurer_a1]").change(getAdjuster1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<tr>
<td><span class="qText" name="insurer">2. Insurer:</span></td>
</tr>
<td>
<select class="qAns" name="insurer_a1">
<option>Please enter a case number</option>
<option>Number1</option>
</select>
</td>
</tr>
Upvotes: 1