user2722885
user2722885

Reputation: 43

How to perform certain code if value of textbox equals specific string (jquery)

Script here

    $(document).ready(function(){

        $("#txt").click(function(){

            var text = $("#test").val()
            var comparingText = "hi"

            if (text == comparingText){

                alert( $("#test").val());

            });

        });
    });

Html here

<input type="text" id="test"/><br>
<input type="button" id="txt" value="Submit" />

So basically what I want is that if someone types in "hi" in the textbox and presses the submit button an alert message with "hi" should pop up. I feel like this should be rather simple but I've literally looked everywhere and can not understand how to make this work.

Upvotes: 2

Views: 9363

Answers (4)

kayz1
kayz1

Reputation: 7434

<section id="input-section">
    <legend>Input section</legend>
    <input type="text" id="test-input"/><br>
    <input type="button" id="submit-button" value="Submit" />
</section>

var SimpleModule = (function($){

    var _$inputSection = $('#input-section');
    var _$testInput = $('#test-input');

    var HI_CONST = 'HI';

    var _sayHiEvent = function(){
        var text = $.trim(_$testInput.val());

        if(text && text.toUpperCase() === HI_CONST){
            alert(text);
        }
    };

    var _bindEvents = function(){
        _$inputSection.on('click', '#submit-button', _sayHiEvent);
    };

    var init = function(){
        _bindEvents();
    };

    return {
        init : init
    };

})(jQuery);

/* Or include before </body> tag */
$(function(){
    SimpleModule.init();
});

Upvotes: 0

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

$(document).ready(function(){
    $("#txt").click(function(){
        var text = $("#test").val();
        var comparingText = "hi";

        if (text === comparingText){
            alert( $("#test").val());
        }
    });
});

Look at this: http://jsfiddle.net/tS2m3/.

Just fix your JavaScript code and it will be ok.

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15923

code should be:

 $(document).ready(function(){

        $("#txt").click(function(){

            var text = $("#test").val();
            var comparingText = "hi";

            if (text == comparingText){

                alert( $("#test").val());

            }

        });
    });

Upvotes: 2

htxryan
htxryan

Reputation: 2961

You just have some syntax errors. Here is the corrected code:

$(document).ready(function () {
    $("#txt").click(function () {
        var text = $("#test").val();
        var comparingText = "hi";
        if (text == comparingText) {
            alert($("#test").val());
        }
    });
});

Fiddle: http://jsfiddle.net/UY3A6/

You were missing the semicolons after "hi" and .val(). You also had an extra ); after the if statement's closing "}".

Upvotes: 1

Related Questions