Hashey100
Hashey100

Reputation: 984

how to pass variable in jquery .change function

I have a form with a simple drop-down menu when the user selects any of the options, i want to be able to pass that selected value to a JavaScript function

Once the user clicks on an option it will alert the value in the jQuery change function but I want to use the value that was passed through in other functions but it does not get the value for some reason

function getTweet(){
  $('#test').change(function() {
    var value = $('#test :selected').val();
  });
}

want to use the value outside of the change function but it does not grab it

<form>  
    <select id="test">
        <option value="one">1</option>
        <option value="two">2</option>
        <option value="three">3</option>
    </select>
</form>

Upvotes: 0

Views: 1567

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

You might use custom events to do something based on that event?

Example:

$('#test').change(function () {
    $('mysubscriberselectorshere').trigger('gettweet');
});

// do something based on the custom event
$('mysubscriberselectorshere').on('gettweet', function {
    // do good stuff here
    alert($('#test').val());
});

Upvotes: -1

Ja͢ck
Ja͢ck

Reputation: 173562

If you want to use the most current value of the drop-down anywhere in your code, you can just reference it like this:

$('#test').val()

I've removed the :selected, because that's not necessary; .val() will give the right value.

Upvotes: 4

Related Questions