iraklisg
iraklisg

Reputation: 5799

How to dynamically display a placeholder and deselect the other options, in a select form menu using Javascript/Jquery

I have the following drop-down menu:

<form action="...">
    <select name="fruits" id="my-fruits">
        <option value="" disabled selected>Select a fruit</option>
        <option value="apple">apple</option>
        <option value="orange">orange</option>
        <option value="peach">peach</option>
    </select>
    <select name="animals" id="my-animals">
        <option value="" disabled selected>Select an animal</option>
        <option value="dog">dog</option>
        <option value="cat">cat</option>
        <option value="iguana">iguana</option>
        ></select>
</form>

What I need is when the user changes the selected option in one filed (i.e. on change event), the placeholder to be displayed on the other and vice-versa.

For example, lets say that the user had already selected orange in #my-fruits. Now, when the user changes the selection from dog to cat in #my-animals:

  1. the placeholder "Select a fruit" to be displayed automatically on #my-fruits field, and
  2. then, the <option value="orange"> have its "selected" attribute removed

Upvotes: 1

Views: 124

Answers (3)

guradio
guradio

Reputation: 15555

$('select').change(function() {
  $(this).siblings('select').prop('selectedIndex', 0);
  console.log($('option:selected', this).val())
  console.log($(this).siblings('select').val())

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="...">
  <select name="fruits" id="my-fruits">
    <option value="" disabled selected>Select a fruit</option>
    <option value="apple">apple</option>
    <option value="orange">orange</option>
    <option value="peach">peach</option>
  </select>
  <select name="animals" id="my-animals">
    <option value="" disabled selected>Select an animal</option>
    <option value="dog">dog</option>
    <option value="cat">cat</option>
    <option value="iguana">iguana</option>
  </select>
</form>

  1. Just set the selected option of sibling select to first index

Upvotes: 1

Anton Honcharuk
Anton Honcharuk

Reputation: 309

Ira, try this:

$('#my-fruits')
  .add('#my-animals')
  .on('change', function () {
    $(this).siblings().prop('selectedIndex', 0);
  });

Also, remove unnecessary arrow in this line:

></select>

Good luck ;)

Upvotes: 1

Eytibi
Eytibi

Reputation: 545

Try

$('#animals').change(function() {
    $('#fruits').val("");
});

Upvotes: -1

Related Questions