Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - How to properly use JQuery Option Selection

I'm learning JQuery and need some assistance with the change function. This example works fine by appending the value to the word example.

var val = $('#exampleFruit').val();
$('#example'+val).show();

Working - https://jsfiddle.net/wj_fiddle_playground/mt69f5w4/19/

However, now I'm trying to use the optionValue variabile with value attribute like this.

$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");

Not Working - https://jsfiddle.net/wj_fiddle_playground/tavg9ec7/11/

If <option value="1">Apple</option> is chosen the apple dropdown should show..etc.

UPDATE

If the apple list is <select id="option2Apple"> and the option value is
<option value="1">Apple</option>

How do I choose table row 3 from apple?

Fiddle: https://jsfiddle.net/wj_fiddle_playground/tavg9ec7/18/

<table>
  <tr id="table 1">
   <select id="exampleFruit">
  <option value="">-- Please Select --</option>
  <option value="1">Apple</option>
  <option value="2">Banana</option>
</select>
</tr>

  <tr id="table 2">
  <select id="option1Banana" class="exampleSubselect" style="display: none;">
  <option value="1">Plantain</option>
  <option value="2">Burro</option>
  <option value="3">Cavendish</option>
  </select>
</tr>

  <tr id="table 3">
   <select id="option2Apple" class="exampleSubselect" style="display: none;">
 <option value="1">Red Delicious</option>
  <option value="2">Granny Smith</option>
  <option value="3">Cox's Orange Pippin</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You forget "#" this is for get the id's in jQuery. Try modifying this:

<select id="exampleFruit">
    <option value="">-- Please Select --</option>
    <option value="exampleApple">Apple</option>
    <option value="exampleBanana">Banana</option>
    <option value="exampleOrange">Orange</option>
</select>

and

$(document).ready(function(){
    $("#exampleFruit").change(function(){
      var optionValue = $(this).val();
      $('.exampleSubselect').hide();
      if(optionValue){
        $(`#${optionValue}`).show();
      }
    }).change();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...