1

If a user types the correct word a function should be called. Currently i have this jQuery Snippet

..
<input type="text" id="code" name="code" placeholder="code">
...
<script>
$(function () {

    var discountCode = 'test4';
    var codeEntered = $("input[name='code']").val();


    $("#subbtn").on("click", function () {

        if (discountCode == codeEntered) {
            alert("RIGHT!");
        } else {
            alert("WRONG!");
        }

    });

});
</script>

But i get always "WRONG" even if i type "test4". What do i wrong ?

3 Answers 3

1

You need to get the value of codeEntered after you click.

Here is the corrected code:

$(function () {
  $("#subbtn").on("click", function () {
    var codeEntered = $("input[name='code']").val();

    if (discountCode == codeEntered) {
        alert("RIGHT!");
    } else {
        alert("WRONG!");
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

The code var codeEntered = $("input[name='code']").val(); should be inside the event handler.

$("#subbtn").on("click", function () {

    var codeEntered = $("input[name='code']").val();

    if (discountCode == codeEntered) {
        alert("RIGHT!");
    } else {
        alert("WRONG!");
    }

});

Comments

0

Try using localecompare

discountCode.localeCompare(codeEntered)

1 Comment

Then i get always right no matter what i type .. It should only be right if i type "test4".

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.