Philipp M
Philipp M

Reputation: 3488

Combine input and select input/change

I have two input fields and two select fields.

I do some frontend validation on input of the input fields and when I change the select of the select fields ... for ALL fields.

The only way I get this to work is if I split it like this:

var is_currencyBilling;
var is_countryBilling;
var is_cityBilling;
var is_postalBilling;

$('#cityBilling,#postalBilling').on('input', function () {

    ...

}); 

$('#currencyBilling,#countryBilling').on('change', function () {

    ...

});

Is there any way to combine this? Or do I have to split it like above?

Edit:

If I combine it in a change like this:

$('#cityBilling,#postalBilling,#currencyBilling,#countryBilling').on('change', function () {

    console.log('Test');

    ...

}); 

... it works after I tab to another input field or a input field looses focus. But is there any chance to keep the former validation behaviour right when I 'change' the value of an input field?

Upvotes: 1

Views: 715

Answers (1)

charlietfl
charlietfl

Reputation: 171679

You can use same change event for all or use multiple events like $(selectors).on('change input', validate)

But you can also listen for different events that use the same event handler.

Within that handler your business logic can adapt to the event type or element type or whatever other special conditions you need

Basic example

$('input:text').on('input', validate);
$('input:checkbox').on('click', validate)
$('select').on('change', validate);

function validate(evt) {
  console.clear()
  var $el = $(this),
    val = $el.val();

  console.log(evt.type + ' event on: ' + this.name + ', new value is: ', val);

  if ($el.is('input:text')) {
    console.log('This is an input:text');
    
  } else if ($el.is('select')) {
    console.log('This is a select');
    
  }else if ($el.is('input:checkbox')) {
    console.log('Checkbox is checked = ', this.checked)
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Inp1: <input name="input_one" type="text" /> Inp2: <input name="input_two" type="text" /> <br><br> 
Check<input name="check_one" value="one" type="checkbox">
<br><br> 

Sel 1
<select name="sel_one">
  <option></option>
  <option value="1">one</option>
  <option value="2">two</option>
</select>

Sel 2
<select name="sel_two">
  <option></option>
  <option value="1">one</option>
  <option value="2">two</option>
</select>

Upvotes: 3

Related Questions