如何使用javascript从组合框中获取所选项目

时间:2016-08-04 13:34:19

标签: javascript html

需要使用javascript从select元素中检索所选项目。



<select id="selected">
  <option value="Default Request" selected disabled>Default Request Service</option>
  <option value="1">Anti-Virus Support and Services</option>
  <option value="2">CSB - Request and Report Forms</option>
  <option value="3">Email Support and Services</option>
  <option value="4">Hardware Support and Services</option>
</select>
<input id="selected_display" type="text" value="" name="subject">
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您的解决方案是在下一个代码中。你有2个功能。首先是获取所选项目的值或文本。 second用于设置值输入

你必须在select标签上添加监听器并等待所选选项的更改

享受!

function getOption(selector) {
    return {
        val: $(selector + ' option:selected').attr('value'),
      text: $(selector + ' option:selected').text()
    }
  };

function setItem(toSelector, value) {
    jQuery(toSelector).val(value);
}

var output;

jQuery('#selected').on('change', function(){
    output = getOption('#selected');
  setItem('#selected_display', output.val); //change to output.text to show text of selected output
});

https://jsfiddle.net/v4fwxeeu/3/

答案 1 :(得分:0)

也许你想用PHP试试:

<form Name="xxxx" class="xxxx" method="post" Action="xxxx">
    <select id="selected" Name="selected>
        <option value="Default Request" selected disabled>Default Request Service</option>
        <option value="1">Anti-Virus Support and Services</option>
        <option value="2">CSB - Request and Report Forms</option>
        <option value="3">Email Support and Services</option>
        <option value="4">Hardware Support and Services</option>
    </select>
</form>

使用PHP,您可以获得&#34;选择&#34;的价值。用:

<?php
   $selected = $_POST['selected'];
   echo $selected;
?>