views:

230

answers:

2

Hi. I am trying to do the next thing in Jquery. I have 2 comboboxes and i want to make sure that their selected values is identical. If user chooses a value in one of the combo like the other one, i want to alert "invalid op" and set the combo selected value to its previous value. so i wrote:

$("#SelectGroupMargin").live("onchange", function() {
   // save the value before the change in case the change is invalid
   var valBeforeChange = $("#SelectGroupMargin").val();
   var currentLimitedRuleVal =  $("#SelectGroup").val();
   var newFillerRule= $(this).val();

   // check that the new value does not colide with the value of the limited rule
   // if it does colide alert the user and return to the former value
   if (currentLimitedRuleVal == newFillerRule) {
     alert("invalid op");
     $("#SelectGroupMargin").text(valBeforeChange);
   } 
});

but i have few problems: 1)onchange doesn't respond - just click and focusout 2) newFillerRule always identical to valBeforeChange

Do you have better idea/shorter any advice thank u

+1  A: 

Try using change as opposed to onchange in the live() method. Also, if my memory serves me correctly, you'll need jQuery 1.4+ to use live with the change event, as code was only implemented in 1.4+ to handle delegation for the change event.

In terms of comparing the newly selected value to the last selected value, you might consider storing the selected value for the using $.data() - then you can compare the value after the change event with the value stored in $.cache (where $.data() stores values) and do the necessary. You could also implement it using a closure too.

Russ Cam
does not work with "change"
ron
it does with 1.4+ - http://jsbin.com/axope/edit
Russ Cam
Tested it, it works as expected concerning your question. I'd look over your syntax carefully, perhaps you have other code affecting the sample you've given us.
Joseph Silvashy
It does work with 1.4+. How do i get the value that was selected before the change?
ron
You'd need to observe the `click` event on it, get it's value, then compare it to the value after it's been changed. In fact you don't need the `live()` function at all in your case.
Joseph Silvashy
A: 

$("#SelectGroupMargin") is the same as $(this) in the context of that function. And use "change" for the live call

zincorp