![](/img/trans.png)
[英]How can I set the value of an hidden input tag with the value of the selected option of a select tag using JavaScript\JQuery?
[英]How can I select the value of a selected option with jQuery?
我正在努力從文檔中找到答案。
.form-group
label.col-md-3.control-label(for='industry') Industry
.col-md-9
select#industries.form-control
option(value='Please Select') Please Select
option(value='A') A
option(value='C') C
option(value='D') D
option(value='S') S
option(value='E') E
如果JavaScript有更簡單的解決方案,我也歡迎。
假設您使用“ my-select”作為選擇的ID,則可以
$('#my-select').val();
否則使用JavaScript:
document.querySelector('#my-select').value;
考慮到您在上面編寫的選擇器,這應該是您的選擇器(但我需要確定HTML才能確定):
$('.form-group label.col-md-3.control-label[for="industry"] .col-md-9 select#industries.form-control')
盡管這也應該很好:
$('select#industries')
您無需擔心獲得所選option
。 只需獲取select
的值:
$( "select" ).change(function () { // Just use the val() method on the select to get its current value $( "#output" ).text( $(this).val() ); }).change();
<script src="https://code.jquery.com/jquery-1.10.2.js"></script> <p>Click your selection: </p> <select multiple="multiple"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <div>You selected: <span id="output"></span></div>
如果有人正在尋找javascript解決方案,則可以通過以下方式完成:
1.選擇下拉元素
2,從期權集合中提取價值
function test() { var elem = document.getElementById('industries'); var val = elem.options[elem.selectedIndex].value; console.log('Value=' + val); }
<select id="industries"> <option value='Please Select'>Please Select</option> <option value='A'>A</option> <option value='B'>B</option> </select> <button class="btn btn-success" id="buttonCode" type="button" onclick="test()">test</button>
只需使用$('#industries').val();
在JQuery中
$( "select" ).change(function () { // Previous answer: technically incorrect logic // var str = $( "select option:selected" ).text(); // $( "div" ).text( str ); $( "div" ).text( $(this).val() ); });
<script src="https://code.jquery.com/jquery-1.10.2.js"></script> <select multiple="multiple"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <div></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.