我有一个表单,我有一个选择选项下拉列表和另一个输入文本类型。现在我希望当有人填写两个字段然后添加字段按钮将激活后,否则它将保持禁用状态。 我的标记代码和jQuery一样
<div id="form-wrap" style="width:500px; margin: 0 auto;">
<table>
<tr>
<th width="55%">Service Name</th>
<th width="35%">From Price</th>
<th width="10%"></th>
</tr>
<tr id="template">
<td id="example" width="55%">
<select name="service-name" id="service-name" style="width:230px;">
<option value="" selected>--select--</option>
<option value="service-1">service-1</option>
<option value="service-2">service-2</option>
<option value="service-3">service-3</option>
<option value="service-4">service-4</option>
</select>
</td>
<td width="45%"><input type="text" name="from-price" id="from-price" /></td>
</tr>
</table> <input type="button" value="+ Add Field" id="add-field" />
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#add-field').prop("disabled",true);
jQuery("select#service-name, #from-price").on("change, keyup, keydown",function() {
var selectLength = jQuery('select#service-name').val().length;
var textLength = jQuery('#from-price').val().length;
if(selectLength > 0 && textLength > 0) {
jQuery('#add-field').prop("disabled", false);
}
else {
jQuery('#add-field').prop("disabled",true);
}
});
})
</script>
这是我第一次添加值时工作正常但是当我删除任何值(清除文本或下拉选项重置)时,按钮仍处于活动状态?
可以看到现场演示here
答案 0 :(得分:0)
使用keyup事件检查输入框内的值的大小。
$(#from-price').keyup(function(){
if($(this).val().length === 0 )
$('#add-field').attr('disabled','disabled');
else{
$('#add-field').removeAttr('disabled');
console.log($(this).val().length);
}
});
如果输入是动态生成的,请使用.on()
来捕获keyup。
答案 1 :(得分:0)
只需检查更改事件。这就够了:
jQuery('#add-field').prop("disabled",true);
jQuery("select#service-name, #from-price").on("change",function() {
var selectLength = jQuery('select#service-name').val().length;
var textLength = jQuery('#from-price').val().length;
if(selectLength > 0 && textLength > 0) {
jQuery('#add-field').prop("disabled", false);
}
else {
jQuery('#add-field').prop("disabled",true);
}
});