views:

48

answers:

1

I'm trying to check if the '#text' (id for a textarea) is empty when I change '#my_selection' (id for a drop-down select) option. And if NOT EMPTY (ie, there's some text in the textarea), I would like the confirmation to pop up, else don't want to change the '#my_selection'.
Many thanks in advance.

var selected=$('#my_selection').val();
$('#my_selection').change(function(){
   if($("#text").val() != ""){
      var check=confirm("change?");
      if(check){
         selected=$(this).val();
         $('#my_selection').val(selected);
      }else{
         $(this).val(selected);
      }
   }
});
+1  A: 

As far as I can tell you code is ok. Perhaps you are just missing an else on the outter if:

var oldVal = $('#select').val();
$('#select').change(function(){
    if ($('#text').val() != ''){
        if(confirm('change ?')){
            oldVal=this.value;
        } else {
            this.value = oldVal;
        }
    } else {
        this.value = oldVal;
    }
});

You can test a running example here.

Dan Manastireanu
dan, btw i noticed that your options don't change if the #text is empty.
DGT
@DGT: That is what the last else does. Besides that the rest of the code is equivalent to yours...
Dan Manastireanu
yeah, but if i remover the last else, it lets you change even when #text is empty, but when the confirm pops up (ie, when #text is not empty), and you click 'cancel', it always goes back to the first option (ie, "One"). do you know why?
DGT
@DGT: I'm not sure I understand what you actually want to happen when the text is empty. When you click on cancel it goes back to the previous value (which is 'One' when you first load the page). Try this: enter some text, switch to option 3, press ok(result=> it goes to 3), than try to switch to 2, but press cancel(result=>remains 3)
Dan Manastireanu