简体   繁体   中英

My Jquery button- disable/enable function is not working. Can anyone tell me what's wrong?

I'm trying to disable submit button until first two fields have input. I've written a function to do that but for some reason it's not working. Here is my HTML:

<html>
<Head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script  type="text/javascript" src="Stuff.js"></script>
</Head>
<body>
    <div class="container">
        <form role="form">
            <div class="form-group has-error">
                <label for="FirstName">First Name</label>
                 <input type="text" class="form-control" id="First" placeholder="First Name">
            </div>
    <div class="form-group">
                <label for="LastName">Last Name</label>
                <input type="text" class="form-control" id="Last" placeholder="Last Name">
    </div>
    <div class="form-group">
                <label for="Age">Age</label>
                <input type="text" class="form-control" id="Age" placeholder="Age">
     </div>
    <button type="submit" class="btn btn-default" id="submit"  >Submit</button>
        </form>
    </div>
</body>

This is my function:

$('#submit').keyup(function () {
if ($('#First').val() != "" && $('#Last').val() != "") {
    $('#submit').removeattr('disabled');
} else {
    $('#submit').attr('disabled', true);
}

});

You could use something like this:

$('#First, #Last').keyup(function () {
  if ($('#First').val() !== "" && $('#Last').val() !== "") {
    $('#submit').prop('disabled', false);
  } else {
    $('#submit').prop('disabled', true);
  }
});

Note that you need to check the fields themselves upon keyup.

Also, use prop() to set the underlying boolean property of the disabled attribute to true/false, instead of removing it completely - see here for why .

jsFiddle here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM