1

I have a list of states in an option menu. I'd like to run a bit of jquery only when either CA or NV are selected. Here is what I have:

$('#state').change(function(){  var text=$('#state :selected').val();  
$('.st').val(text);      
});

Which I tried (unsuccessfully) to adapt to another bit of jquery like this:

<script type="text/javascript">
      $(document).ready(function() {
        $("#state").change(function() {
          if ($("#state option[value='CA']").attr('selected')) {



$('#state').change(function(){  var text=$('#state :selected').val();  
$('.st').val(text);      
});



          }
        });
      });
    </script>

Any idea what needs to be changed for this to work?

4 Answers 4

1

Use

if ($("#state").val() == "CA")

jQuery val() will return the selected value from a select element.

Here's a working example: jsfiddle

EDIT: And here's one that clears the value too: jsfiddle

$(function() {
    $("#state").change(function() {
        var state = $(this).val();
        $(".st").val((state  == "CA") ? state : "");
    })
});
Sign up to request clarification or add additional context in comments.

4 Comments

There is one issue now in that if a user selects CA and then goes back and selects another state, the value remains CA. What would I need to add in order to make anything else reset the value?
@Paul: the value of what remains CA? The textbox?
@Paul: See the edit in my answer, I think that's what you're after.
Aww, Town, so close - What I am actually looking to do is not so much clear the value as to reset the value to what it was initially. Really appreciate your help.
1

You could try:

      if ($("#state option[value='CA']:checked").length > 0) { ... }

Comments

1

Try this -

 <script type="text/javascript">
  $(document).ready(function() {
    $("#state").change(function() {
      if ($("#state").val()=='CA') {
          //do something
         }    
      });
  });
</script>

Comments

1

I ended up doing this, slight edit of Town's code (to account for t states and have a non blank default value:

<script type="text/javascript"> $(function() { $("#state").change(function() { var state = $(this).val(); $(".st").val((state == "CA" || state == "NV") ? state : "auto"); }) }); </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.