Validating select box with jquery validate and chosen plugins

旧时模样 提交于 2019-11-26 21:59:13

问题


I am trying to use validate and chosen plugin together. I am having the problem while validating select boxes. I found similar questions How can I use jQuery validation with the "chosen" plugin? and Chosen.js and validate jquery but I couldn't find a way to import the solutions to my code :

<form  class='myform' id='producteditform'>
                    <input type='hidden' value='<? echo $row['id']; ?>' name='pkedit' id='pkedit'>                   
                    <input type='hidden' value='save' name='operation' id='operation'>
                    <p><label for='nameedit'>Product Name</label><em>*</em><input id='nameedit' name='nameedit' value='<? echo $row['pname']?>'/></p>
                    <p><label for='unitedit'>Unit</label><em>*</em><?
                        $query="select * from units";
                        $result=$mysqli->query($query);
                        if($result->num_rows==0)
                        echo "<a href='units.php?operation=insert'>No unit found. Please define a unit first</a>";
                        else{               
                        echo    "<select class='chosen' id='unitedit' name='unitedit'>";        
                            while($row=$result->fetch_assoc())
                              echo  "<option value='".$row['id']."'>".$row['name']."</option>";
                            echo    "</select>";
                        }
                        $mysqli->close();               

                    ?></p>                    
                    <p><a class='button' class='button' id='saveedit'>Save</a>
                    <a class='button' id='canceledit' onclick='f()' >Cancel</a></p>
                    </form>

jquery code

$("#save").click(function () {
        if($("#producteditform").validate({ 
         ignore: [], 
                rules: {
                  nameedit: {
                    required: true,
                    maxlength:100

                  },
                  unitedit:{
                    required: true,
                  }

                }
              }).form()
            )
        {
            // do sth

                })
        }
}

html rendered output

<form class="myform" id="productform" novalidate="novalidate">
                    <input type="hidden" value="insert" name="operation" id="operation">

                    <p><label for="name">Product Name</label><em>*</em><input type="text" name="name" id="name"></p>
                    <p><label for="unit">Unit</label><em>*</em><select class="chosen chzn-done" id="unit" name="unit" style="display: none;"><option value="">please choose..</option><option value="1">kgg</option></select><div id="unit_chzn" class="chzn-container chzn-container-single" style="width: 200px;" title=""><a href="javascript:void(0)" class="chzn-single" tabindex="-1"><span>please choose..</span><div><b></b></div></a><div class="chzn-drop" style="left: -9000px; width: 198px; top: 24px;"><div class="chzn-search"><input type="text" autocomplete="off" style="width: 163px;"></div><ul class="chzn-results"><li id="unit_chzn_o_0" class="active-result result-selected" style="">please choose..</li><li id="unit_chzn_o_1" class="active-result" style="">kgg</li></ul></div></div></p>
                    <p><a class="button" id="save">Save</a>
                    <a class="button" id="cancel" onclick="f()">Cancel</a></p>                  
                    </form>

when I remove class='chosen' everything works fine when save button clicked, otherwise im getting error Uncaught Error: Failed to validate, found an element with no name assigned. See console for element reference.


回答1:


Try something like this instead.

$(document).ready(function() {

    // initialize the plugin on DOM ready
    $("#producteditform").validate({ 
        // all rules and options,
        rules: {
            nameedit: {
                required: true,
                maxlength:100
            },
            unitedit:{
                required: true,
            }
        }
    });

    // test for valid form
    $('#save').on('click' function() {
        if($("#producteditform").valid()) {
            // do this on valid form
        } else {
            // do this on invalid form
        }
    });

});

$('#producteditform').validate() initializes the validate plugin on the form.

$('#producteditform').valid() programmatically triggers an actual validation test and returns a true/false boolean value.


Alternatively, since your event is the form click on submit event, then you simply use the built-in submitHandler callback function instead. (There is no need to create another click handler.)

$(document).ready(function() {

    // initialize the plugin on DOM ready
    $("#producteditform").validate({ 
        // all rules and options,
        rules: {
            nameedit: {
                required: true,
                maxlength:100
            },
            unitedit:{
                required: true,
            }
        },
        submitHandler: function(form) {
            // do this on valid form
        }
    });

});

Full documentation:

http://docs.jquery.com/Plugins/Validation


Until you show your HTML output instead of the PHP, here is a generic example of how to validate a select element:

http://jsfiddle.net/6Dt7F/

Important, the very first, or the default option in the select element must contain value="" or the required rule will fail.

<select name="field1">
    <option value="">please choose...</option>
    <option>option 1</option>
    <option>option 2</option>
    <option>option 3</option>
</select>

EDIT:

I still don't have enough code to make a working demo. However, since the chosen plugin is hiding the actual form elements, you'll have to do the following...

1) Target the actual form element that is going to get validated and pass the data, not the visual element created by chosen.

2) Enable jQuery Validate to work on hidden elements by setting ignore: [] option.

Try this...

$(document).ready(function () {

    // initialize the plugin on DOM ready
    $("#producteditform").validate({ 
        // all rules and options,
        ignore: [], // <-- option so that hidden elements are validated
        rules: {
            name: {  // <-- name of actual text input
                required: true,
                maxlength: 100
            },
            unit:{  // <-- name of actual select input
                required: true
            }
        },
        submitHandler: function(form) {
            // do this on valid form
        }
    });

});



回答2:


This occurs because Chosen inserts an input field which the user can search through the dropdown list with.

For some reason, this search field does not have a name tag (hence the error):

<input type="text" autocomplete="off" tabindex="7">

The input doesn't have a class or ID either, which is probably why the console error is so vague. A quick fix is to give it a name:

$(".chzn-search input").attr('name', 'chzn-search');


来源:https://stackoverflow.com/questions/14861160/validating-select-box-with-jquery-validate-and-chosen-plugins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!