簡體   English   中英

從選項中選擇時更改選項值

[英]Change a options value when selected from options

我有一個下拉值,其值超過當前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 /月。

該解決方案隨附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> 

將選擇組件的寬度設置為任何固定寬度,如下所示:

 <div class="calci-input">
          <select id="g-suite-pac-id" name="g-suite-package" style="width:96px">       
                    <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)dffsdfsdfdsfsdfdsfdsfsd</option>
                    <option value="3.33">$3.33/month (12 months)</option>
          </select>
</div> 

嘗試上面的代碼,它顯示可以適合96px寬度的文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM