Reputation: 1
Aye sir, i want to make option like "916812 - Kurt Cobain", and when i click it shown only "916812" and i have done with that..
but when i want to reselect the option "916812" to others it didnt change back to "916812 - Kurt Cobain". How to solve this? here is my code :
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
So, basically i want to make user feel helpfully because when searching "student name" is based on "NIS" which is only number value from option.
I think its kinda hard searching the "student name" only with the "ID" so i put "student name" with it.
Upvotes: 0
Views: 82
Reputation: 24965
//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>
Upvotes: 1