我正在尝试将选定的选项值或文本移动到下一个输入字段。然而,它从来没有显示我甚至努力编码它。
脚本
function haz(elem){
console.log($(elem).find('option:selected').val());
$(elem).closest("input#hazard").text($(elem).find('option:selected').val());
}<li class="hazard_header"><h3>Hazard</h3>
<select id='haz_op' onchange="haz(this)">
<option>--Select--</option>
<option value="Airborne Particulates (Silica Dust)">Airborne Particulates (Silica Dust)</option>
<option value="Asbestos">Asbestos</option>
</select>
</li>
<li>
<h3>or</h3>
</li>
<li class="hazard_input">
<input type="text" name="hazard[]" id="hazard" autocomplete="off" placeholder="enter text here"/>
</li>在脚本部分,console.log执行得很好,但是,当我尝试将它添加到#hazard输入时,它从未显示,我只尝试硬编码一个字符串,但仍然什么也没有显示。(“我选错了吗?”)
谢谢
发布于 2015-05-28 17:43:10
在您的示例中,不需要导航到$(elem)。只需使用$('#hazard')。另外,#hazard是一个input类型元素,所以您应该使用val()而不是text()
更新
如果有多个输入元素,请导航如下
$(elem).closest('li').nextAll('.hazard_input:first').find('[name="hazard[]"]').val($(elem).find('option:selected').val());或者假设您有一个父ul,就越容易
$(elem).closest('ul').find('[name="hazard[]"]').val($(elem).find('option:selected').val());
function haz(elem){
$(elem).closest('ul').find('[name="hazard[]"]').val($(elem).find('option:selected').val());
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul>
<li class="hazard_header"><h3>Hazard</h3>
<select id='haz_op' onchange="haz(this)">
<option>--Select--</option>
<option value="Airborne Particulates (Silica Dust)">Airborne Particulates (Silica Dust)</option>
<option value="Asbestos">Asbestos</option>
</select>
</li>
<li><h3>or</h3></li>
<li class="hazard_input">
<input type="text" name="hazard[]" id="hazard" autocomplete="off" placeholder="enter text here"/></li>
</ul>
https://stackoverflow.com/questions/30513513
复制相似问题