首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jquery在激活按钮之前检查文本是否已输入且未清除。

jquery在激活按钮之前检查文本是否已输入且未清除。
EN

Stack Overflow用户
提问于 2013-12-06 07:39:25
回答 2查看 70关注 0票数 0

我有一个表单,我采取了一个选择选项下拉和另一个输入文本类型。现在,我希望,当有人将填充这两个字段后,然后添加字段按钮将激活,否则它将仍然是禁用的。我的标记和jQuery的代码如下

代码语言:javascript
复制
  <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>

这里,它的工作良好,当我第一次添加值,但当我删除任何值(清除文本或下拉选项重置),然后按钮仍然显示在活动状态?

现场演示可以看到这里

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-06 07:48:10

检查一下变更事件。够了:

代码语言:javascript
复制
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);
}
});

http://jsfiddle.net/u96zT/1/

票数 0
EN

Stack Overflow用户

发布于 2013-12-06 07:42:14

使用keyup事件检查输入框中值的大小。

代码语言:javascript
复制
$(#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()捕获密钥。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20418598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档