1

With the code shown below, I would like to disable the text input when the user clicks on the button.

When I click on my button, the text input only disables for one second, before it enables again.

I would like to know why does this happens.

<html>

<head>
    <script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#enable').click(function() {
                $('#textBox').removeAttr("disabled")
            });
            $('#disable').click(function() {
                $('#textBox').attr("disabled", "disabled");
            });
        });
    </script>
</head>

<body>
    <form>
        <input type="text" id="textBox" />
        <button id="enable">Enable</button>
        <button id="disable">Disable</button>
    </form>
</body>

</html>
4
  • 1
    It works fine in a fiddle: jsfiddle.net/v6oxd4zp. Can you set up a working example of the problem. There's nothing in your code which would cause a change in DOM state after a timed interval. Commented Apr 21, 2015 at 16:24
  • @RoryMcCrossan - you forgot the form element -> jsfiddle.net/adeneo/v6oxd4zp/1 Commented Apr 21, 2015 at 16:27
  • @adeneo yep, you're right. Let this be a lesson to everyone - indent your code! Commented Apr 21, 2015 at 16:28
  • @RoryMcCrossan@adeneo- thanks for giving the answer. Commented Apr 21, 2015 at 17:04

1 Answer 1

3

A button inside a form submits the form, reloading the page, as it's default type is submit.

You have to either change the type

<input type="button" id="enable" value="Enable">

or prevent the default

$('#enable').click(function (e) {
    e.preventDefault();
    $('#textBox').prop("disabled", false);
});
$('#disable').click(function (e) {
    e.preventDefault();
    $('#textBox').prop("disabled", true);
});

And use prop() for the disabled property.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.