Mjukis Mjukis - 13 days ago 6
Javascript Question

How to use jQuery onChange with if / else statement's?

I have a problem with javascript running because it is cashed.


Example

//Init onClick event
$(document).on('click', '.select', function(){
//Check if select has value
if( $(this).val() ){
console.log( $(this).val() )
} else {
console.log('no value')

$(this).on('change', function(){
console.log('Changed!')
}
}
}


PROBLEM

Now consider i have a select. From start the value is empty and the option is disabled. First time i click the select, console will log "no value".
You click and you change option/value to something in the list.

Second time i click the select, an option is selected and it has a value. Console will now log "the value", but it will also log "changed".

I guess it's because i have run the else statement before and the onChange function is cashed in my browser or something like it...

How can i prevent this from happen.. or how should i write my code instead?
I need to check if a value is selected from start.. and i need to use the onChange function...

UPDATE

When you click the select, i'd like to know if the select has a selected value. (To know if you change/edit a value OR if you choose value for first time) This is why i have a onClick function. Here i check the value.

After you clicked and i have checked the value, i like to trigger a onChange function.. that will do this for the edit route.. or that for the new route..

Answer

You should only add "change" event on the select. Operations on a select element must be done in terms of it's state changed w.r.t it's options

 var pervious;
 //Init onClick event
$(document).on('focus','.select', function () {
    // Store the current value on focus and on change
    previous = this.value;
}).
on('change', '.select', function(){
    //Check if select has value
    if( $(this).val() ){
      console.log( $(this).val() );
      previous = this.value;
    }
    else{
      console.log('no value')
      // YOUR choice, reset it i.e. previous = null;
    }
});
Comments