John
John

Reputation: 426

How to check when two check boxes both have nonempty values with jQuery

So I'm trying to make it so that when a user clicks one of the options, nothing happens, but the second they click select an option on the other selector (whose value isn't empty), the page will instantly submit. I know I could use a submit button, but I really dislike those.

Does anyone know how to fix this?

Here's a small hypothetical situation:

 <script     src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<select name="select" id="select">
    <option value=''>--- Select ---</option>";
    <option value=1>a</option>";
    <option value=2>b</option>";
    <option value=3>c</option>";
</select>

<select name="select2" id="select2">
    <option value=''>--- Select ---</option>";
    <option value=1>a</option>";
    <option value=2>b</option>";
    <option value=3>c</option>";
</select>

Here's my js for it:

$(document).ready(function () {
   if( $('#select').val() && $('#select2').val()) { 
    alert("aa");
    submit();
   }
});

Also, here's a jfiddle for convenience: https://jsfiddle.net/bcknhe36/1/

Upvotes: 0

Views: 35

Answers (2)

charlietfl
charlietfl

Reputation: 171690

You are only checking on page load

You need to check within a change event handler after user has selected

$(document).ready(function() {
  $('#select,#select2').on('change', function() {
    if ($('#select').val() && $('#select2').val()) {
      alert("aa");
      $('#formID').submit();
    }
  });
});

Upvotes: 1

thatOneGuy
thatOneGuy

Reputation: 10632

Rather than checking on document ready you need to check on change. So when the drop down is changed check if both have a value.

Updated fiddle : https://jsfiddle.net/bcknhe36/4/

$(document).ready(function() {
 $( "#select,#select2" ).change(function() {
  if ($('#select').val() && $('#select2').val()) {
    alert("aa");
    submit();
  }
});

});

Upvotes: 0

Related Questions