输入文本中没有值时禁用按钮

时间:2017-08-01 01:54:43

标签: jquery

我需要在输入文本中没有插入任何值时禁用该按钮

<form>
    <div class="form-group">             
        <p class="description">Please Enter Your Tracking Number.</p>

        <input type="text" id="tracking-input" class="input-text full-width" placeholder="Enter your Tracking number(s)"onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
    </div> 
    <br>
    <button type="submit" id="register" class="full-width btn-medium">Track</button>
</form>

尝试了这个但不起作用

<script>

function buttonState(){
    $("input").each(function(){
        $('#register').attr('disabled', 'disabled');
            if($(this).val() == "" ) return false;
        $('#register').attr('disabled', '');
    })
}

$(function(){
    $('#register').attr('disabled', 'disabled');
    $('input').change(buttonState);
})

</script>

2 个答案:

答案 0 :(得分:1)

您可以使用keyup事件根据值

检查按钮的disabled属性

$(document).ready(function(){
  $('#register').prop('disabled',true);
    $('#tracking-input').keyup(function(){
        $('#register').prop('disabled', this.value === "");     
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="form-group">
      <p class="description">Please Enter Your Tracking Number.</p>
      <input type="text" id="tracking-input" class="input-text full-width" placeholder="Enter your Tracking number(s)"onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
  </div> <br>
  <button type="submit" id="register" class="full-width btn-medium">Track</button>
</form>

答案 1 :(得分:0)

$("#register").prop("disabled",true);

$("#tracking-input").keyup(function(){
var valuee=$("#tracking-input").val().trim();
if(valuee==""){
$("#register").prop("disabled",true);

}else{
$("#register").prop("disabled",false);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
                <div class="form-group">

                    <p class="description">Please Enter Your Tracking Number.</p>

                    <input type="text" id="tracking-input" class="input-text full-width" placeholder="Enter your Tracking number(s)">
                </div> <br>
                <button type="submit" id="register" class="full-width btn-medium">Track</button>
            </form>