Reputation:
I have three different select boxes that users can choose from. I need to access the values of all three selections at once and can't figure out how to do it. Let me explain what I mean with an example:
<select id="hue">
// Options
</select>
<select id="sat">
// Options
</select>
<select id="lig">
// Options
</select>
Now, to access the choice of each select box I use the following code:
$('#hue').filter(':selected').val().change(function(){
hueVal = $(this).val();
return hueVal;
})
$('#sat').filter(':selected').val().change(function(){
satVal = $(this).val();
return satVal;
})
$('#lig').filter(':selected').val().change(function(){
ligVal = $(this).val();
return ligVal;
})
Now, what I want to do is get access to the three returned values (hueVal, satVal and ligVal) at the same time in a new jquery call - like follows:
$('#header').css('background-color', hsl(hueVal+','+satVal+','+ligVal));
The problem is, since each value is within a function I don't know how to get access to all three of them at once outside of their respective functions.
Any idea how I can do this?
Upvotes: 1
Views: 181
Reputation: 7297
Try this:
$('select').change(function() {
var hue = $('#hue').val(),
sat = $('#sat').val(),
lig = $('#lig').val();
$('#header').css('background-color', 'hsl('+ hue +','+ sat +','+ lig +')');
}).trigger('change');
edit: the value for background-color needs to be a full string
Upvotes: 1
Reputation: 160833
You could use an object to manage these values.
var color = {
hue: $('#hue').val(),
sat: $('#sat').val(),
lig: $('#lig').val()
};
$('#hue,#sat,#lig').change(function() {
color[this.id] = $(this).val();
$('#header').css('background-color', 'hsl('+color.hue+','+color.sat+','+color.lig+')');
});
Note:
.val()
could get the selected value of the select.hsl
is css expression, it also need to be a string.Upvotes: 0
Reputation: 9691
Consider declaring global variables, outside the functions:
var hueVal;
var satVal;
var ligVal;
$('#hue').filter(':selected').val().change(function(){
hueVal = $(this).val();
return hueVal;
})
$('#sat').filter(':selected').val().change(function(){
satVal = $(this).val();
return satVal;
})
$('#lig').filter(':selected').val().change(function(){
ligVal = $(this).val();
return ligVal;
})
$('#header').css('background-color', hsl(hueVal+','+satVal+','+ligVal);
Upvotes: 3
Reputation: 5374
Declare the variables outside of the functions, then modify the variables inside the functions (returning the values is useless in this context):
var hueVal,
satVal,
ligVal;
$('#hue').filter(':selected').val().change(function(){
hueVal = $(this).val();
});
$('#sat').filter(':selected').val().change(function(){
satVal = $(this).val();
});
$('#lig').filter(':selected').val().change(function(){
ligVal = $(this).val();
});
You can then do what you'd like with them, i.e.:
$('#header').css('background-color', hsl(hueVal+','+satVal+','+ligVal);
You might also want to read up on scope.
Upvotes: 0