如何制作动态选项标签html

时间:2018-11-20 23:21:33

标签: jquery html

是的,先生,我想选择“ 916812-Kurt Cobain”,当我单击它时,只显示“ 916812”,我已经完成了。
但是当我想重新选择其他选项“ 916812”时,它并没有更改回“ 916812-Kurt Cobain”。如何解决呢?这是我的代码:

HTML:

<body>
<select name="anggota_nis" id="anggota_nis">
<option hidden selected value=""></option>
<option value="916812">916812 - Kurt Cobain</option>
<option value="918291">918291 - Freddi Mercury</option>
<option value="912728">912728 - Gerry Cherone</option>
<option value="991829">991829 - Axl Rose</option>
<option value="927182">927182 - Steven Tyler</option>
<option value="912728">912739 - Russel Hitchcock</option>
</select>
</body>

jQuery:

  $("#anggota_nis").on('change', function(){
      var nis = $("#anggota_nis").val();
      $("#anggota_nis option[value="+nis+"]").text(nis);      
  })

jsfiddle: http://jsfiddle.net/he7Laytg

here's the form i created

因此,基本上,我想让用户有帮助,因为在搜索“学生姓名”时基于“ NIS”,而“ NIS”只是选项中的数字值。

我认为仅用“ ID”搜索“学生姓名”有点困难,因此我将“学生姓名”放在其中。

1 个答案:

答案 0 :(得分:1)

//take note of the data-name attributes added to the options
//bind a change event listener to the select
var $anggotaNis = $('#anggota_nis').on('change', function(){
  $anggotaNis.find('.changed') //find the previously changed option
    .removeClass('changed') //remove the class, as we are reverting them
    .text(function(){ //set the text back, based on the value and name
      return this.value +' - '+ this.getAttribute('data-name');
    });
  
  $anggotaNis.find(':selected') //find the option just selected
    .addClass('changed') //add the class to mark that we are changing it
    .text(function(){ //set the text to just the value
      return this.value;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="anggota_nis" id="anggota_nis">
<option hidden selected value=""></option>
<option value="916812" data-name="Kurt Cobain">916812 - Kurt Cobain</option>
<option value="918291" data-name="Freddi Mercury">918291 - Freddi Mercury</option>
<option value="912728" data-name="Gerry Cherone">912728 - Gerry Cherone</option>
<option value="991829" data-name="Axl Rose">991829 - Axl Rose</option>
<option value="927182" data-name="Steven Tyler">927182 - Steven Tyler</option>
<option value="912728" data-name="Russel Hitchcock">912739 - Russel Hitchcock</option>
</select>