Jquery validation error placement (radio buttons)

前端 未结 4 1268
有刺的猬
有刺的猬 2021-02-05 11:19

I\'m trying to use the Jquery validation plugin to validate my form. I have error messages appearing to the right of most of my input elements, but radio buttons are giving me n

相关标签:
4条回答
  • 2021-02-05 12:03

    Try this. It places the error before the object the error is raised on. If you set the first radiobutton as required, this wil work. For consistency I chose to perform this action on all inputtypes, but you can also tweak the script a little to perform this action only when a radiogroup fails validation.

    $('form').validate({
      errorPlacement:
      function(error, element){
        var id=element[0]['id'];
        $( element ).before( "<label for='"+id+"' class='error'>"+error.text()+"</label>" );
      }
    });
    
    0 讨论(0)
  • 2021-02-05 12:07

    Dont even need JS errorPlacement to do it... if just place a label for the radio buttons also works like so:

    <label class="label_radio" for="answer_A">
      <input id="answer_A" name="answers[question1].choiceArray" type="radio" value="A"/>Yes
    </label>
    <label class="label_radio" for="answer_B">
      <input id="answer_B" name="answers[question1].choiceArray" type="radio" value="B"/>No
    </label>
    
    <label for="answers[question1].choiceArray" class="error" style="display:none;">* Please pick an option above</label>
    

    Jquery Validation plugin will automatically unhide it and display the "required" messsage.

    0 讨论(0)
  • 2021-02-05 12:09

    You can also use this method to place an error for a specific field wherever you want.

    errorPlacement: function(error, element) {
      if (element.attr("name") == "PhoneFirst" || element.attr("name") == "PhoneMiddle" || element.attr("name") == "PhoneLast") {
         error.insertAfter("#requestorPhoneLast");
      } else {
         error.insertAfter(element);
      }
    },
    
    0 讨论(0)
  • 2021-02-05 12:16

    Just use some CSS:

    #myform div.group label.error {float:right;padding-left:10px;}
    
    0 讨论(0)
提交回复
热议问题