10

Fill in some entries in a drop-down list

 2 years ago
source link: https://www.codesd.com/item/fill-in-some-entries-in-a-drop-down-list.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Fill in some entries in a drop-down list

advertisements

I have a jsp like this:

$("select[name='numbers']").change(function() {
  var str = $('#numbers option:selected').text();
  var ret = str.split(" ");
  var str1 = ret[0];
  var str2 = ret[1];
  var str3 = ret[3];
  $("first").val(str1);
  $("second").val(str2);
  $("last").val(str3);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="numbers" name="numbers">
  <option value="1 2 3">1 2 3</option>
  <option value="4 5 6">4 5 6</option>
  <option value="7 8 9">7 8 9</option>
</select>
<br/>
<br/>
First: <input id="first" name="first" type="text"/><br/>
Second: <input id="second" name="second" type="text"/><br/>
Last: <input id="last" name="last" type="text"/>

What I would like to do is fill the inputs like this:

  • if 1 2 3 option is selected, write 1 inside first input, 2 inside second input, 3 inside last input;
  • if 4 5 6 option is selected, write 4 inside first input, 5 inside second input, 6 inside last input;
  • if 7 8 9 option is selected, write 7 inside first input, 8 inside second input, 9 inside last input;

I tried in this way but it's not working: https://jsfiddle.net/L1xj7uge/ I think I'm selecting the dropdown list value in a wrong way but I don't know how to solve.


Updated fiddle.

You should add the id sign # in the selector of those lines to refer to id attribute :

$("#first").val(str1);
$("#second").val(str2);
$("#last").val(str3);

And also the index of str3 should be 2 not 3, so :

var str3 = ret[3];

Should be :

var str3 = ret[2];

Hope this helps.

$("select[name='numbers']").change(function() {
  var str = $('#numbers option:selected').text();
  var ret = str.split(" ");
  var str1 = ret[0];
  var str2 = ret[1];
  var str3 = ret[2];

  $("#first").val(str1);
  $("#second").val(str2);
  $("#last").val(str3);

}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="numbers" name="numbers">
  <option value="1 2 3">1 2 3</option>
  <option value="4 5 6">4 5 6</option>
  <option value="7 8 9">7 8 9</option>
</select>
<br/>
<br/>
First: <input id="first" name="first" type="text"/><br/>
Second: <input id="second" name="second" type="text"/><br/>
Last: <input id="last" name="last" type="text"/>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK