Dennis Dennis - 1 month ago 11
Javascript Question

How to change text names inside select box without changing selection?

For example, in code below when I select

Ship Date
, I want the "Sort Direction" to change to
{"Earliest Date First", "Latest Date First"}
without changing the selection itself.

And when I select "Value", I want the "Sort Direction" to change to
{"Smallest Value First", "Largest Date First"}
without changing the selection.

So I want the text of options to change in select box #2, when I select various specific options in select box #1.

How?

My code does something weird and does not change selection...



$('#sort_by').change(function() {
if ($('#sort_by').val("shipdate"))
$('#sort_order').val("asc").val("Earliest Date First");
else
$('#sort_order').val("desc").val("Latest Date First");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Sort By Field:
<select name="sort_by" id="sort_by">
<option value="shipdate">Ship Date</option>
<option value="value">Value</option>
</select>
<br/>Sort Direction:
<select name="sort_order" id="sort_order">
<option value="asc">Asc</option>
<option value="desc">Desc</option>
</select>
</form>




Answer

If you just only want to change the text of your options you need to simply change the text.

Example :https://jsfiddle.net/799cf2wr/

<form>
  Sort By Field:
  <select name="sort_by" id="sort_by">
    <option value="shipdate">Ship Date</option>
    <option value="value">Value</option>
  </select>
  <br/>Sort Direction:
  <select name="sort_order" id="sort_order">
    <option value="asc" id="asc">Asc</option>
    <option value="desc" id="desc">Desc</option>
  </select>
</form> 

JS:

$('#sort_by').change(function() {
  if ($('#sort_by').val() === "shipdate"){
        $('#asc').text("Earliest Date First");
        $('#desc').text("Latest Date First");
  }
  else{
      $('#asc').text("Smallest Value First");
      $('#desc').text("Largest Date First");
  }
});
Comments