select option, checkbox, radio tags, if they be empty

Viewed 87

For textboxes and numbers, If they are empty, We send the following error command very easily:

AJAX

    parent_fieldset.find('input[type="text"], input[type="number"]').each(function() {
        if( $(this).val() == "" ) {
            $(this).addClass('input-error');
            next_step = false;
        }
        else {
            $(this).removeClass('input-error');
        }
    });

CSS

.input-error {
    border-color: red;
}

But for select option, checkbox, radio tags, if they were empty, How should I do?

2 Answers

You may use something like this:

$(document).ready(function(){
$('#mySelectBox').each(function() {
 if($(this).val() == -1)     
        $(this).addClass('input-error');     
 else
        $(this).removeClass('input-error');
});

});

A fiddle example here. To clarify a bit, I assumed here that you'd have a "please select option" with the value -1 (so nothing was actually selected):

To verify if a combo box item has been selected, you can check the selectedIndex value. With the checkbox, you can check its checked property.

Working example is at https://jsbin.com/hezemohali/edit?html,js,output

function verify() {
  let selectCar = this.document.getElementById("car-brand");
  if(selectCar.selectedIndex === 0)
    selectCar.className = 'input-error';
  else 
    selectCar.classList.remove('input-error');

  let tc = this.document.getElementById("tc");  
  if (!tc.checked)    
    tc.parentNode.className = 'input-error';
  else
    tc.parentNode.classList.remove('input-error');
}
Related