2017-10-06 18 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 months)を選択すると、ドロップダウンで$ 2.00/monthと表示されます。

+5

[HTMLでHTMLの値を表示しますが、オプションテキストを保持する]の可能な複製(https://stackoverflow.com/questions/26822596/html-select-display-value-attribute-in-html-but-retain -options-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幅に収まるテキストを示しています。

関連する問題