Reputation: 95
So I have two basic select dropdowns with some options:
<div id="form">
<select name="firstselect">
<option>English</option>
<option>French</option>
</select>
<select name="secondselect">
<option>Girls</option>
<option>Boys</option>
</select>
</div>
<div id="print_html_here"></div>
I would like to be able to use .val() to grab BOTH of the user's choices and then print some html (depending on what combination of choices was made) into the last div.
This is what I have tried so far:
$("#form").on('change', function(e) {
var selectedValue = $('select[name=firstselect]', 'select[name=secondselect]').val();
if (selectedValues === "English" "Girls") {
$("#print_html_here").html("You have selected English Girls.");
}
elseif (selectedValues === "French" "Girls") {
$("#print_html_here").html("You have selected French Girls.");
}
});
But no joy. I think the syntax is wrong for when I am trying to val the two select elements. Any help would be appreciated!
Upvotes: 0
Views: 37
Reputation: 135
You have a few mistakes, some of they are:
1) First I suggest to add ids
to your html elements, so they are more easy to target from Jquery
.
2) The change
event listener should be over the selects
, not over the form
.
3) You need to add values
attributes to your options...
So, taking into consideration previous comments, I have reorganized your code like this:
$("#sel1, #sel2").on('change', function(e)
{
var firstSel = $('#sel1').val();
var secondSel = $('#sel2').val();
if (firstSel == 1 && secondSel == 1)
$("#print_html_here").html("You have selected English Girls.");
else if (firstSel == 2 && secondSel == 1)
$("#print_html_here").html("You have selected French Girls.");
else if (firstSel == 1 && secondSel == 2)
$("#print_html_here").html("You have selected English Boys.");
else if (firstSel == 2 && secondSel == 2)
$("#print_html_here").html("You have selected French Boys.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form">
<select id="sel1" name="firstselect">
<option value="1">English</option>
<option value="2">French</option>
</select>
<select id="sel2" name="secondselect">
<option value="1">Girls</option>
<option value="2">Boys</option>
</select>
</div>
<div id="print_html_here"></div>
Upvotes: 2