[英]Take input field data to save in select option value
我有这个具有不同值的下拉列表。 我想要做的是每当我选择其他选项时,显示 id=othertype 的隐藏 div,我将在输入字段中输入并想要保存该数据,但它不起作用。 我不能两次使用相同的 name 属性,但我不想要一个单独的列只用于其他输入。 是否可以将输入值与选项保存在同一列中? 我想要输入字段的值,而不是我在其他选项中传递的值,这本身就是其他选项。
<div class="form-group">
<div class="col-sm-12">
<label for="p_type">Type*:</label>
<select class="form-control" name="qp_type" id="p_type" required>
<option value="Css">CSS</option>
<option value="HTML">HTML</option>
<option value="PhP">PhP</option>
<option value="Other">Other</option>
</select>
</div>
</div>
<div class="form-group" id="otherType" style="display:none;">
<div class="col-sm-12">
<label for="pType">If you chose ‘Other’, please describe below:</label>
<input id="pType" type="text">
</div>
</div>
脚本
$('#p_type').on('change',function(){
if( $(this).val()==="Other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});
看起来您正在尝试使用文本字段的输入或下拉列表中的值。 您可以只启用或禁用一个字段。 名称可以相同,这不是问题。
<div class="form-group">
<div class="col-sm-12">
<label for="p_type">Type*:</label>
<select class="form-control" name="qp_type" id="p_type" required>
<option value="Css" selected>CSS</option>
<option value="HTML">HTML</option>
<option value="PhP">PhP</option>
<option value="Other">Other</option>
</select>
</div>
</div>
<div class="form-group" id="otherType" style="display:none;">
<div class="col-sm-12">
<label for="pType">If you chose 'Other', please describe below:</label>
<!-- START OFF WITH THIS ONE DISABLED, NAME IT THE SAME AS ABOVE --->
<input id="pType" type="text" name="qp_type" disabled>
</div>
</div>
<script>
$(document).ready(function(){
$('select[name=qp_type]').change(function(){
if($(this).val() == 'Other') {
$('#otherType').show();
$('#pType').prop('disabled',false);
}
else {
$('#otherType').hide();
$('#pType').prop('disabled',true);
}
});
});
</script>
这会将所选选项的值更改为输入字段中的值。
function init() { $('#p_type').on('change',function(){ if( $("option:selected", this).text()==="Other"){ $("#otherType").show() } else{ $("#otherType").hide() } }); $('#pType').on('change',function(){ // selector should be '#p_type option[text="Other"]', but it's returning an empty array $('#p_type option:selected').val( $(this).val() ) console.log( $('#p_type').val() ); } ); } $(init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <body> <div class="form-group"> <div class="col-sm-12"> <label for="p_type">Type*:</label> <select class="form-control" name="qp_type" id="p_type" required> <option value="Css">CSS</option> <option value="HTML">HTML</option> <option value="PhP">PhP</option> <option value="Other">Other</option> </select> </div> </div> <div class="form-group" id="otherType" style="display:none;"> <div class="col-sm-12"> <label for="pType">If you chose 'Other', please describe below:</label> <input id="pType" type="text"> </div> </div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.