0

$('form input').change(function(){
  if ($(this).val() != '') {
    alert('The Form Not Empty');
  } else {
    alert('The Form Empty')
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='get' action=''>
  <input type='text'>
  <input type='number'>
  <input type='checkbox'>
</form>

I want to track the form inputs, If the entire form inputs are empty, i alert empty once, If a single input is not empty, I alert not empty

I keep getting Not Empty on the checkbox, But it works ok on the text inputs.

Can I just track the form itself if it is not totally empty or not instead of the inputs?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
Toleo
  • 764
  • 1
  • 5
  • 19
  • 1
    Click on the first box, type something, blur, you get Not empty, go back to the input, delete the content and blur, you get empty. Main problem is the checkbox, the value is "on" checked or unchecked – Huangism Feb 08 '18 at 21:05
  • @Huangism Oh, Blur actually helps here, But the problem form contains every type of inputs except the one with defined values like range or radio – Toleo Feb 08 '18 at 21:08
  • 1
    To check the checkbox, see https://stackoverflow.com/questions/11440128/jquery-check-if-checkbox-is-not-checked for the input text, the change only triggers when you blur – Huangism Feb 08 '18 at 21:08

3 Answers3

2

$(this).val() is not a good test for a checkbox, the value is always "on", which is not empty.

For checkboxes you need to use .prop()

$('form input').change(function(event) {
  console.log($(this).val())
  if (event.target.type === 'checkbox') {
    if ($(this).prop('checked') === true) {
      console.log('checked');
    } else {
      console.log('not checked');
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='get' action=''>
  <input type='text'>
  <input type='number'>
  <input type='checkbox'>
</form>
Sébastien
  • 11,860
  • 11
  • 58
  • 78
  • Can't i use the `form` itself to check If it contains any value in it? I actually don't know how `form`s works, But I assumed That it collects all the data in something temporarliy. – Toleo Feb 08 '18 at 21:12
  • 1
    No, you must look at each individual form control. – Sébastien Feb 08 '18 at 21:14
0

HTML has a build in feature called required to alert the user that the form should not be empty. For your form it should look like this:

<form method='get' action=''>
  <input type='text' required>
  <input type='number' required>
  <input type='checkbox' required>
</form>
garritfra
  • 546
  • 4
  • 21
0

You can use the required attribute for your form or inputs to make them mandatory, more informations here.

Saturnin
  • 36
  • 2