选择选择时,在文本输入中放置默认值

时间:2015-07-16 10:00:44

标签: jquery forms jsp

我的JSP中有一个表单,在select选项中我显示了数组的元素,在此旁边我有一个输入text

<% ArrayList<Machine>  machinesList = (ArrayList<Machine>) (session.getAttribute("machinesList")); %>

<-- and later in the form -->

<select class="form-control" id="select" name="position1-1"> 
     <option value="0"></option>
     <%for(Machine m : machinesList){%>
          <option value="<%=m.getIdMachine()%>"><%=m.getIdMachine()%></option>
     <%}%>
</select>

<select class="form-control" id="select" name="position2-1"> 
         <option value="0"></option>
         <%for(Machine m : machinesList){%>
              <option value="<%=m.getIdMachine()%>"><%=m.getIdMachine()%></option>
         <%}%>
    </select>

<input type="text" class="form-control" id="inputName" name="name3-1">


<select class="form-control" id="select" name="position3-1"> 
         <option value="0"></option>
         <%for(Machine m : machinesList){%>
              <option value="<%=m.getIdMachine()%>"><%=m.getIdMachine()%></option>
         <%}%>
    </select>

我还有一个数组nameList

<% ArrayList<String>  nameList= (ArrayList<String>) (session.getAttribute("machinesList")); %>

,其中包含ID的名称。如何在用户选择id时,文本输入自动从列表nameList中获取默认值?例如,我从select中选择第一个值,然后文本ipnut将具有nameList中的第一个元素。

1 个答案:

答案 0 :(得分:1)

<强> 编辑:

您在同一范围内key不能拥有同一session的多个属性。这在以后设置时无效,因为属性将覆盖旧属性。

<% ArrayList<Machine>  machinesList = (ArrayList<Machine>) (session.getAttribute("machinesList")); %>
<% ArrayList<String>  nameList = (ArrayList<String>) (session.getAttribute("machinesList")); %>

假设您在javascript变量中需要nameList字符串类型,您可以这样做:

var names = ${nameList}; // ${}, is jsp's EL

var names = <%=nameList%>; //jsp expression scriplet

change事件上使用jQuery:

&#13;
&#13;
var names = ['Apple', 'Microsoft']; //${nameList}

$(function() {
  $('select[id^=select]').on('change keyup', function(e) {
    //make text blank if selected option is at 0 index else get the selected option value
    var i = this.selectedIndex;
    var txt = i ? names[i - 1] : '';
    $('#inputName' + this.id.replace(/\D/g,'')).val(txt);
  });
});

//this.id.replace(/\D/g,'') will replace other than digits
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="select1">
  <option value="0">Select</option>
  <option value="Machine 1">Machine 1</option>
  <option value="Machine 2">Machine 2</option>
</select>

<input type="text" id="inputName1">
<br/>
<select id="select2">
  <option value="0">Select</option>
  <option value="Machine 1">Machine 1</option>
  <option value="Machine 2">Machine 2</option>
</select>

<input type="text" id="inputName2">
<br/>
<select id="select3">
  <option value="0">Select</option>
  <option value="Machine 1">Machine 1</option>
  <option value="Machine 2">Machine 2</option>
</select>

<input type="text" id="inputName3">
<br/>
&#13;
&#13;
&#13;