0

I have all kinds of form elements in a form. I have set mandatory class for mandatory elements to validate if they are not empty. The class selector works on input(text), textarea and select but not working on checkboxs and radios.

I know how can I check for at least one selection in a radiogroup or checkbox group (this answer) but I`m looking for a more general method to work only with class.

My exact question: Is there a general way to check all fields (and radios or checkboxes at least one selection) or I have to check radios and checkboxes separately?

my current code for inputs,textarea and select:

$(".ajaxform").ajaxForm({
  beforeSubmit : function(arr, $form, options){
    var myresult=true;
    $(".mandatory").each(function(){
      if (!($(this).val())){myresult=false}
    });
    return myresult;
  },
  success:showResponse
});
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • may be i didnt get your exact requirement but are you looking to check if the radio or checkbox is selected and that too without using `:checked` selector ? – Muhammad Omer Aslam Nov 06 '17 at 14:28
  • Yes. actually I don't want to check radios and checkboxes separately. even a plugin or a more general method and even using :checked for textareas(!) to validate all elements by a single method. – Ali Sheikhpour Nov 06 '17 at 14:32
  • hmm, that seems tricky as you have to check the `checked` property even if you go for native javascript i mean we still have to check `document.getElementById("myCheck").checked` to see if it is selected or not – Muhammad Omer Aslam Nov 06 '17 at 14:39
  • The second problem is that checkbox or radios are multi choice and one of them is enough and I have not to loop through all of them! – Ali Sheikhpour Nov 06 '17 at 14:40
  • why not add a class to all those inputs, textareas, checkboxes and radio buttons which are clicked or typed in and then check for that class on those element ? – Muhammad Omer Aslam Nov 06 '17 at 14:42
  • you can use `onblur` or `focusout` to check if something was typed in and the value is not empty before adding a class on them. – Muhammad Omer Aslam Nov 06 '17 at 14:44
  • Good suggestion. But I have to remove that class for checkboxes and radios when unselected or inputs when cleared! there is another long process to manipulate these events. – Ali Sheikhpour Nov 06 '17 at 14:45

0 Answers0