从选项中选择时更改选项值

时间:2017-10-06 12:13:44

标签: javascript jquery html css html5

我的下拉列表的值超出了当前div的宽度。我想在选择该选项时只显示文本的一部分。我尝试扩展宽度,但表单结构搞砸了。

  <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>

我如何使用jQuery实现这一目标?

预期输出是当选择$ 2.00 /月(12个月)选项时,它在下拉列表中显示为$ 2.00 /月。

2 个答案:

答案 0 :(得分:1)

该解决方案附带onchange和onmousedown事件。使用jQuery的选择器,我们可以获得所选的选项并更改其显示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>

答案 1 :(得分:0)

将选择组件的宽度设置为任何固定宽度,如下所示:

JpaRepository

尝试上面的代码,它显示的文本可以适合96px宽度。

相关问题