Reputation: 1167
I have a list of some radio buttons, I get the value of the checked input on click, store it in a variable, and later I want to access the variable when another element, e.g a div is clicked. Everything works fine except for the variable not being recognized inside the second click event. Maybe a possible variable scope mistake?
<ul><li><a href="#">Line</a><input class="checkTool" type="radio" name="drawTool" value="line"></input></li></ul>
<ul><li><a href="#">Rect</a><input class="checkTool" type="radio" name="drawTool" value="rectangle"></input></li></ul>
<ul><li><a href="#">Circ</a><input class="checkTool" type="radio" name="drawTool" value="circle"></input></li></ul>
$("input:radio[name=drawTool]").click(function() {
var currTool = $(this).val();
});
$('.space').click(function(){
$(this).html(currTool)
})
Upvotes: 0
Views: 217
Reputation: 218732
If you want to access in a different method, keep the value in a variable declared outside the method. So that it has a wider scope than the method. It can be accessible outside the method as well.
$(function(){
var currTool="";
$("input:radio[name=drawTool]").click(function() {
currTool= $(this).val();
});
$('.space').click(function(){
$(this).html(currTool)
})
});
Upvotes: 1
Reputation: 20159
Even better: you can retrieve the currently selected tool when you actually need it by looking for the checked radio button.
$('.space').click(function(){
var currTool = $("input:radio[name=drawTool]:checked").val();
$(this).html(currTool);
});
Upvotes: 2