简体   繁体   中英

jQuery validation with submit button disabled

I made some sort of form validation. User can input name of group and group description. With jQuery I'm validating if group name is empty or not, if empty submit button should be disabled. Now I have problems with disabling submit button. If I click on input tag where group name is, then validation is ok, and submit button is disabled, but if I just click on submit button, without touching anything else, then jQuery skip validation and fires submit button although name of group is empty. I tried setting input tag in focus with jQuery but it only works if I actually click on that input tag.

Submit button is 'saveGroup' button.

Can someone tell me how to invoke click event on this input tag, or maybe I can use some other validation tehnique.

    <div class="newGroupDiv">
            <label>Title: </label><input type="text" id="groupTitle" onblur="checkTitle();"><br>
            <label>Description:</label><br>
            <textarea id="groupDescription"></textarea><br><br>    
            <button id="saveGroup">Save</button>
            <button id="cancelGroup">Cancel</button>
            <label id="groupError"></label>
        </div>

---------------------------------------------------------------------------------    

    $("#saveGroup").click(function(){
                var variable = checkTitle();
                if(variable == true){
                    if($("#groupError").html() == ""){
                        $(".columns").append('<ul class="'+ $("#groupTitle").val() +'"><li class="naslov">'+ $("#groupTitle").val() +'</li></ul>');
                        $("ul").sortable({containment : 'document', 
                            tolerance: 'pointer', 
                            cursor: 'pointer', 
                            revert: 'true', 
                            opacity : 0.6, 
                            connectWith : "ul", 
                            placeholder: 'border', 
                            items : 'li:not(.naslov)', 
                            start : function(){
                                check = false;
                                $(".readContent").fadeOut(300);
                            }, stop : function(){
                                check = true;
                            }}).disableSelection();

                        $.post("addGroup.php", {'title' : $("#groupTitle").val(), 'description' : $("#groupDescription").val(),
                        'color' : $("#colorHex").html(), 'color2' : $("#colorHex2").html()}, function(){
                            window.location.reload();
                        });
                    }
                }
            });


--------------------------------------------------------------------------------    


    var checkTitle = function(){
        $.post("checkTitle.php", {'title' : $("#groupTitle").val()}, function(data){
            if(data == 'exist') $("#groupError").html("Group already exists");
            if(data == 'no title') $("#groupError").html("Group title can't be empty");
            else if(data == 'ok') $("#groupError").html("");
        });
        return true;
    }

With this 'variable' I tried to accomplish some sort of callback wait, so when this variable gets result from function it should continue with rest of code, but I'm not sure if it works.

You would be better of switching the way you do things here. First of, as I said, make sure you do the "isEmpty" check without performing any ajax calls. Javascript is perfectly capable of doing so itself.

Secondly, instead of checking the HTML inside your element, you'd be better of checking the result of your checkTitle() function. Because there might be a slight possibility the if($("#groupError").html() == ""){ fails because there is still some HTML detected.

The above comments result in this javascript:

function checkTitle() {
    $groupTitle = $('#groupTitle').val();

    if($groupTitle == "") {
        $("#groupError").html("Group title can't be empty");
        return false;
    } else {
        $.post("checkTitle.php", {'title' : $groupTitle }, function(data){
            if(data == 'exist') {
                $("#groupError").html("Group already exists");
                return false;
            } else if(data == 'ok') {
                $("#groupError").html("");
                return true;
            }
        });
    }
}

Now the result of the checkTitle() function can be used in your final check that you perform onBlur and onClick. Let's continue with your HTML:

<div class="newGroupDiv">
    <label>Title: </label>
    <input type="text" id="groupTitle" onblur="checkTitle();"><br>

    <label>Description:</label><br>
    <textarea id="groupDescription"></textarea><br><br>    

    <button id="saveGroup">Save</button>
    <button id="cancelGroup">Cancel</button>

    <label id="groupError"></label>
</div>

Just a little suggestion is to use a div instead of a label to show your groupError in, I understand right now this is for demo purposes only so it's just a little sidenote.

I'm not 100% possitive this solution will work, however, what I think is causing the issue is the default behaviour of the button you're using. Since the script is completely relying on the ajax call, my guess is that you have to prevent the default from happening as such:

$('#saveGroup').click(function(e) {
   e.preventDefault();
});

You could give the script below a shot, hopefully it works. I can't test it because of the ajax calls. But I'll make a jsFiddle with some test data in a minute:

$("#saveGroup").click(function(e){
    e.preventDefault();
    var formValidation = checkTitle();

    // formValidation is only true in case no errors occured
    // Therefor making your #groupError check useless
    if(formValidation == true) {
        // Reset the #groupError html content
        $('#groupError').html('');

        // insert your other jQuery code here
    }
});

a jsFiddle: http://jsfiddle.net/8bJAc/

As you can see onBlur the data is checked (please not there's a random factor that simulates true/false for your ajax call) and after submitting you can see either a success or error message.

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