0

I'm trying to change the state of a button (using Bootstrap) from active to inactive based on input from the user. In the bigger picture, I am trying to come up with an intuitive way to test input for a form, so that once every field is valid, the submit button can then be pressed for PHP processing on the server side. Here is what I currently have for code:

<br>
<label>
    Input: <input type="text" name="sample" class="form-control" id="input" onkeyup="activateButton()" required>
</label>

<br>
<label>
    <button type="submit" name="submit" class="btn btn-success disabled" id="button">Submit</button>
</label>

<script type="text/javascript">
    function activateButton() {
        "use strict";

        var input = document.getElementById("input").val();
        if (input == "activate") {
            document.getElementById("button").className = "btn btn-success active";
        }

    }
</script>

This is, of course within html markup, and so I wanted to get some pointers on how to approach this, since my current setup doesn't seem to work. Thank you!

2
  • 2
    btw document.getElementById("input").val(); should be document.getElementById("input").value; Commented Jun 24, 2015 at 15:57
  • Thats all it is. That should probably be an answer. Commented Jun 24, 2015 at 15:59

1 Answer 1

1

In your code document.getElementById("input").val(); should be document.getElementById("input").value;

And Since you have tagged question in jquery too..

 function activateButton() {
        "use strict";

        var input =$("#input").val();
        if (input == "activate") {
            $("#button").toggleClass("btn btn-success active");
        }

    }

ADDITION(extra info asked by the user):

$("input").keyup(function(){
        var d=$(this).val();
        var res = d.test(/your-regex-here/);
        if(res)
        {
              //enable button here
        }
        else
        {
              //disable button here
        }
    });
Sign up to request clarification or add additional context in comments.

3 Comments

With this jQuery code, is it possible to format it such that it checks (in real time) the value of the field, and changes the button accordingly?
Let's say I wanted to test it against a regex pattern, and so if the user entered a valid input, it would allow them to click the button, but if they used backspace, or entered an invalid character it would disable it again. Thanks for your help @Varun !
@UsmanTahir Check the answer,i have made an addition,which hoepfully is what you want

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.