Home > Net >  jQuery: Depending on the Selected Option of the <Select> Output a Different Text
jQuery: Depending on the Selected Option of the <Select> Output a Different Text

Time:05-29

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:

$(document).ready(function() {
  $('#title').html("Date 1 or 2");

  $('#select-date').change(function() {
    if ($('#select-date') > $('#select-date').is(':nth-child(2)')) {
      $('#title').html("Date 3 to 6");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
  <p id="title"></p>
  <select id="select-date">
    <option>Date 1</option>
    <option>Date 2</option>
    <option>Date 3</option>
    <option>Date 4</option>
    <option>Date 5</option>
    <option>Date 6</option>
  </select>
</div>

CodePudding user response:

You likely want to look at the selected option

$("#select-date option:selected")

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

$(function() {
  $('#select-date')
  .on("change", function() {
    $('#title').html(this.selectedIndex < 2 ? "Date 1 or 2" : "Date 3 to 6");
  })
  .change(); // initialise
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
  <p id="title"></p>
  <select id="select-date">
    <option>Date 1</option>
    <option>Date 2</option>
    <option>Date 3</option>
    <option>Date 4</option>
    <option>Date 5</option>
    <option>Date 6</option>
  </select>
</div>

  • Related