Reputation:
Let's say I have this HTML:
<select id='list'>
<option value='1'>First</option>
<option value='2'>Second</option>
<option value='3'>Third </option>
</select>
<input type ="text" id="text"/>
and then this JavaScript
//other variables are also declared here
var x1 = 5;
var x2 = 10;
var value = x1 * x2;
var list_value =$("#list").change(function() {
$(this).val();
// just an example of how i want the function in the variable
});
var nwval = value * list_value;
$('#text').val(nwval);
// some long piece of code
// i'm also using the list_value value somewhere in the long piece of code..
I want the val in the textbox to change as the user selects an option, I know it'll work if I wrap the change event around it, but is there any way to go about this while keeping it as that variable list_value
?
Upvotes: 11
Views: 65851
Reputation: 3798
$('#text').val($('option:selected').text());
$('#list').change(function(){
$('#text').val($('option:selected').text());
})
check from here http://jsfiddle.net/QrHUN/
Upvotes: 3
Reputation: 207501
this returns a jQuery object, not a value.
var list_value =$("#list").change(function() {
If you want the value outside of the code, you would need to do something like this
var list_value = 0;
var sel = $("#list").change(function() {
list_value = $(this).val();
}).change();
var nwval = value * list_value;
$('#text').val(nwval);
BUT the onchange event will never update the page, just that variable!
Upvotes: 0
Reputation: 92581
Wrapping the change event is the better way as it creates a closure, you could use global variables as below, but you would be better (imho) to simply grab the value again futher down.
You could technically do (although a bad idea as it is global variables):
var x1 = 5;
var x2 = 10;
var value = x1 * x2;
var list_value = 1;
$("#list").change(function() {
list_value = $(this).val();
var nwval = value * list_value;
$('#text').val(nwval);
});
Upvotes: 1
Reputation: 10305
var x1 = 5;
var x2 = 10;
var value = x1 * x2;
var nwval;
$("#list").change(function() {
nwval = value * $(this).val();
$('#text').val(nwval);
});
Upvotes: 16