Display input based on a select option

Asked

Viewed 1,285 times

2

I want to exhibit a input based on the option that I choose through a select.

If I select 1 he shows the input 1, if I select 2 he shows the 2 but gives a hide() in the 1. Currently the code is like this:

$('.select').on({change: listChildren}).trigger('change');

function listChildren(){
  
  if ( $(this).val() != '' ) {
    children = $('option').val();
    $("#" + $(this).val() ).show();
  }
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<select name='options' class="select">
  <option value=''>Select</option>
  <option value='option-1'>Option 1</option>
  <option value='option-2'>Option 2</option>
  <option value='option-3'>Option 3</option>
</select>

<input type="text" placeholder="exemplo 1" class="one" style="display: none" id="option-1"/>
<input type="text" placeholder="exemplo 2" class="two" style="display: none" id="option-2"/>

I’m showing it, but I can’t do the hide().

  • the input to be shown has to have some connection with the selected value, for example, the input has an ID where, the value is the same as the selected option?

  • that’s right! actually today he’s already managing to do the show. the problem is in Hide.

1 answer

2


Add a class to all input. Then just put a hide() in class and so in the group and a show() for id in the specific element:

      $('.select').on({change: listChildren}).trigger('change');

      function listChildren(){

        if ( $(this).val() != '' ) {
          children = $('option').val();
          $(".input").hide();
          $("#" + $(this).val() ).show();
        }

      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name='options' class="select">
      <option value=''>Select</option>
      <option value='option-1'>Option 1</option>
      <option value='option-2'>Option 2</option>
      <option value='option-3'>Option 3</option>
    </select>

    <input type="text" placeholder="exemplo 1" class="one input" style="display: none" id="option-1" />

    <input type="text" placeholder="exemplo 2" class="two input" style="display: none" id="option-2" />

  • Good Samir, that’s right ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.