user5005768 user5005768 - 1 month ago 8
jQuery Question

How to Modify selected option text & Restore Back text after next option

I want to Modify text contents of dynamically generated drop down list using jQuery. Here is my example:

Drop Down Text look like below:

<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>


jQuery:

var previous;
$('#s1').focus(function () {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
//Modify the SelectedOption Display only Number Value
$('#s1').find(':selected').text($('#s1').find(':selected').val());
//Restore the Previous Option : Format 'Number Value : data-name'
alert($("#s1 option[value='"+previous+"']").val());
alert($("#s1 option[value='"+previous+"']").attr('data-name'));
$("#s1 option[value='"+previous+"']").text($("#s1 option[value='"+previous+"']").val() +' '+ $("#s1 option[value='"+previous+"']").attr('data-name'));
});


I also used following attributes :


  • value
    : stores number value of that car

  • data-name
    : stores the Name of that Car



This is what I want:
Whenever any user select any option, then the selected option text will be modified and removes that Name part: For example: selecting 1:Volvo become 1 only.However if user select another option then the previous option text will be restore back to previous format e.g: 1 becomes 1:Volvo again. That is why i used given attributes to restore format.
I have written a code that works fine if i used
alert
.But i want to do it without using
alert
and then it does not work.

Here is my code:
jsfiddle
please help.

Answer

You have set data-name and value attributes, so you can easily loop over the options and use those attributes to update the text:

$('#s1').change(function() {    
  $(this).find('option').each(function(){
    $(this).text(
      $(this).attr('value')+( $(this).is(':selected') ? '' : ':'+$(this).attr('data-name'))
    );
  });
});

$('#s1').change(function() {    
  $(this).find('option').each(function(){
    $(this).text(
      $(this).attr('value')+( $(this).is(':selected') ? '' : ':'+$(this).attr('data-name'))
    );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
  <option data-name="volvo" value="1">1:Volvo</option>
  <option data-name="saab" value="2">2:Saab</option>
  <option data-name="mercedes"  value="3">3:Mercedes</option>
  <option data-name="audi"  value="4">4:Audi</option>
  <option data-name="BMW" value="11">11:BMW</option>
</select>

Comments