Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a options value when selected from options

i have a drop-down that has values which are exceeding the current div's width. i want to show only a part of the text when that option is selected. i tried extending the width but the form structure is getting messed up.

  <div class="calci-input">
          <select id="g-suite-pac-id" name="g-suite-package">       
                    <option value="2.40">$2.40/month</option>
                    <option value="4.00">$4.00/month</option>
                    <option value="2.00">$2.00/month(12 months)</option>
                    <option value="3.33">$3.33/month (12 months)</option>
          </select>
</div>

how can i achieve this using jQuery ?

the expected output is that when the option $2.00/month(12 months) is selected it shows as $2.00/month in the drop-down.

like image 980
Ryan Pereira Avatar asked Nov 19 '25 11:11

Ryan Pereira


1 Answers

The solution comes with the onchange and onmousedown event. Using jQuery's selectors we can get the selected option and change its display HTML.

//you really don't need jQuery, but we can wrap it in there.

//wrap in ready function to make sure page is loaded
$(document).ready(function() {
  $("select#g-suite-pac-id").on("change", function() {
     var text = $(this).children("option").filter(":selected").text()
    var edited = text.match(/^.+?\/month/); //use regex | ^ start, .+? lazy search for everything until /month
    
    //save
    $(this).children("option").filter(":selected").data("save", text);
    
    //change
    $(this).children("option").filter(":selected").text(edited);
    
  });


  $("select#g-suite-pac-id").on("mousedown", function(e) {
      //restore a saved value
      var selected = $(this).children("option").filter(":selected");
      if (selected.length > 0)
      {
        if (selected.data("save"))
        {
          selected.text(selected.data("save"));
          selected.removeData("save");
        }
      }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="calci-input">
  <select id="g-suite-pac-id" name="g-suite-package">       
                    <option value="2.40">$2.40/month</option>
                    <option value="4.00">$4.00/month</option>
                    <option value="2.00">$2.00/month(12 months)</option>
                    <option value="3.33">$3.33/month (12 months)</option>
          </select>
</div>
like image 74
Mouser Avatar answered Nov 20 '25 23:11

Mouser