2017-10-06 80 views
3

我有一個具有超過當前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/month(12個月)被選中時,它在下拉菜單中顯示爲$ 2.00 /月。

+5

[HTML選擇 - 在HTML中顯示值屬性但保留選項文本]的可能副本(https://stackoverflow.com/questions/26822596/html-select-display-value-attribute-in-html-but-retain -option-text) –

回答

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>

+0

假設這些選項沒有「月」呢? –

0

集寬度:

<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寬度文本。

相關問題