I want a different output based on the selected option.
What I’m trying to do is if the selected option is beyond option 2, I want to enter the condition. If it’s not, don’t enter the condition.
This is my code:
JavaScript
x
9
1
$(document).ready(function() {
2
$('#title').html("Date 1 or 2");
3
4
$('#select-date').change(function() {
5
if ($('#select-date') > $('#select-date').is(':nth-child(2)')) {
6
$('#title').html("Date 3 to 6");
7
}
8
});
9
});
JavaScript
1
13
13
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
2
3
<div>
4
<p id="title"></p>
5
<select id="select-date">
6
<option>Date 1</option>
7
<option>Date 2</option>
8
<option>Date 3</option>
9
<option>Date 4</option>
10
<option>Date 5</option>
11
<option>Date 6</option>
12
</select>
13
</div>
Advertisement
Answer
You likely want to look at the selected option
JavaScript
1
2
1
$("#select-date option:selected")
2
but it is much simpler to use the DOM selectedIndex which is 0-based.
When you use this
instead of $(this)
you get the underlying DOM object
I am using a so-called ternary
to set the text of the title
JavaScript
1
7
1
$(function() {
2
$('#select-date')
3
.on("change", function() {
4
$('#title').html(this.selectedIndex < 2 ? "Date 1 or 2" : "Date 3 to 6");
5
})
6
.change(); // initialise
7
});
JavaScript
1
13
13
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
2
3
<div>
4
<p id="title"></p>
5
<select id="select-date">
6
<option>Date 1</option>
7
<option>Date 2</option>
8
<option>Date 3</option>
9
<option>Date 4</option>
10
<option>Date 5</option>
11
<option>Date 6</option>
12
</select>
13
</div>