将表单值附加到文本框

时间:2016-07-06 13:52:45

标签: jquery

我正在尝试在下拉框中选择值,然后使用JQuery将其附加到我页面上的另一个文本框中。

从此表单中获取值

<form id="val">
<select>
<option value="Counseling General CBI Determinations">CBI Determinations</option>
<option value="Counseling General Correspondence">Correspondence</option>
<option value="Counseling General Memorandum">Memorandum</option>
</select>
<button type="button" id="append">apply filter</button>
</form>

附加到此文本框

<input name="txtBox" type="text"/>

2 个答案:

答案 0 :(得分:1)

首先需要修复html,选项需要在select内 然后你可以在按钮的click事件处理程序中完成它。

&#13;
&#13;
$('#append').click(function() {
  var selectedVal = $('#mySelect').val();
  $('input[name="txtBox"]').val(selectedVal);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="val">
    <select name="mySelect" id="mySelect">
      <option value="Counseling General CBI Determinations">CBI Determinations</option>
      <option value="Counseling General Correspondence">Correspondence</option>
      <option value="Counseling General Memorandum">Memorandum</option>
    </select>
<button type="button" id="append">apply filter</button>
</form>
Append to this textbox

<input name="txtBox" type="text"/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要确保并在完成后将选项元素放入选择中,以便您的html应该读取:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="val">
    <select id="selectBox">
      <option value="Counseling General CBI Determinations">CBI Determinations</option>
      <option value="Counseling General Correspondence">Correspondence</option>
      <option value="Counseling General Memorandum">Memorandum</option>
    </select>
<button type="button" id="append">apply filter</button>
</form>
Append to this textbox

<input name="txtBox" type="text"/>

完成此操作后,您可以使用jquery:

$('input[name="txtBox"]').val($("#selectBox").val());