1

I have a div and into this I have 2 checkboxes and 2 inputs text but I want validate or check if all inputs are empty to display an alert or error and that fill at least one input (checkbox or text) because I don't do two validations: 1 for checkboxes and 2 for inputs text... exists any way to do this?

HTML

<div id="t_disp">
    <p>
        <label for="7x24">7x24</label>
        <input id="7x24" name="7x24" type="checkbox"/>
    </p>
    <p>
        <label for="5x8">5x8</label>
        <input id="5x8" name="5x8" type="checkbox"/>
    </p>
    <p>
        <label for="especial">Especial</label>
        <input id="especial" name="especial" type="text"/>
    </p>
    <p>
        <label for="ticket">Ticket</label>
        <input id="ticket" name="ticket" type="text"/>
    </p>
</div>

Thanks in advance!!

3 Answers 3

1

To get how many inputs are filled/checked:

var filled = $('#t_disp input').filter(function() { 
  return $(this).is('[type=checkbox]') ? this.checked : this.value;
}).length;

if ( filled ) {
   // at least one input is filled
} else {
   // all inputs are empty
}
Sign up to request clarification or add additional context in comments.

Comments

0

For the text inputs you can check the value.

$('#especial').val();
$('#ticket').val();

For the check boxes you can check if they're checked.

$('#7x24').attr('checked'); // returns 'checked' if checked
$('#5x8').attr('checked');

Then you just need to stick them all in a condition. If they're all empty or not checked then you show your error.

P.S. In my experience id= beginning with numbers don't work all that well.

Comments

0

You can use below function

function validate()
{

    var isFormValid = false;

        $("#t_disp input:text").each(function()
        {
      if ($.trim($(this).val()).length > 0)
           {      isFormValid = true;    }
        });

     var len =  $("#t_disp input:checked").length;
     if( len > 0 ) { isFormValid = true; }

        if (!isFormValid) 
        alert("Please fill atleast on one field.");

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.