1

Can you please take a look at This Demo and let me know what I am doing wrong in this Custom Function to validate the Text input?

$(function () {
    var fname = $('#fname').val();
    var lname = $('#lname').val();
    var proceed = true;

    function nameInput(inputData) {
        var textBox = $.trim($(inputData).val())
        if (textBox == "") {
         alert('Field Can Not be Empty');
        }
    }

    $("#pro").on("click", function (e) {
        nameInput(fname);
        e.preventDefault();
    });
});

apparently the nameInput() is returning Field Can Not be Empty in both empty and filled format of the fname input. Thanks

1 Answer 1

2

You need to remove the two calls to val() when you declare your field variables:

var fname = $('#fname');
var lname = $('#lname');

As it is, you're passing the value to your method, and then in your method calling val() again.

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

2 Comments

Thanks Robby it is working now but I am really confused here! I tried to keep the variables as they are and updating the function as var textBox = $.trim(inputData); but it didn't work!
Indeed, because they are initialized only once when your outer function is first loaded/executed. If you update the values afterwards, it will not be reflected in the variables.

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.