简体   繁体   中英

jquery ajax call on button click validation not working

I'm submitting a form on a btn click using jquery ajax call. I'm doing form validation and if input is not valid then need to stop the ajax call. I've tried the following code but form submits every time even when the conditions fail

<script type="text/javascript">
    $(document).ready(function () {

        $('#btnSubmit').click(function (evt) {
            if (ValidateUserInput()) {
                $.ajax({
                    type: 'GET',
                    url: '@Url.Action("SearchResults", "Request")',
                    data: { searchTerm: $("#searchTerm").val(), searchFilter: $("#searchFilter").val() },
                    success: function (data) {
                        $('#Results').html(data);
                    }
                });
            }

        });

    });

    function ValidateUserInput() {

        if ($('#searchFilter').val() == 'RequestId' && $('#searchTerm').val() != parseInt($('#searchTerm').val())) {
            $('#HiddenInvalidInputContainer').show(); 
            return false;

        }
        else {
            alert('testing');
            $('#HiddenInvalidInputContainer').hide(); 
            return true;
        }

    }

</script>

Any ideas?

You always get the else clause, as this is always false for a number

$('#searchTerm').val() != parseInt($('#searchTerm').val()

"1" != parseInt("1") is false, "1" !== parseInt("1") is true

if you are trying to test for not-a-number, then you could use isNaN()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM