Reputation: 31580
I have a set of variables that I use to tell if an question in a survey has been answered, and they are initially set to false: q0=false; q1=false; qX=false;
. Then in the body, I have several input type="radio"
s with .change(function(){ counter_radio(q#,INPUT'S_ID); });
binded to each. This is the code for function counter_radio():
function counter_radio(q,id){
if (q===false) {
q=true;
count++;
$("#counter").css("width", count);
$("#percent").text(count + "%");
}
$("span#"+id).append(", "+q);
$("span#"+id).fadeIn();
}
I expect that the counter to only increment once (the first time a radio from a set is selected). However, the counter is incrementing every time the input type=radio
changes. My problem is that, q
returns true, but q#
remains false. In php, I would make q
a reference to q#
so when q
is set to true, q#
is also set to true. Is there such a construct in javascript?
Upvotes: 2
Views: 127
Reputation: 707148
As others have said, simple variables like booleans are passed by value, not by reference in Javascript so there is no way to change that.
If you have multiple variables like this:
var q0=false, q1=false, qX=false;
then, it might be easier to put them in an array:
var qArray = [false, false, false];
Then, because arrays and objects are passed in a way that you can modify the original, you can pass the array and an index to your function like this and you are then able to modify the original data from your function:
function counter_radio(q, index, id){
if (q[index] === false) {
q[index] = true;
count++;
$("#counter").css("width", count);
$("#percent").text(count + "%");
}
$("span#"+id).append(", " + q[index]);
$("span#"+id).fadeIn();
}
counter_radio(qArray, 2, id);
Upvotes: 1
Reputation: 2736
I would collect the values when the user submits the form:
jQuery('radio[name=...]:checked').val()
If you want to warn the user that not all questions have been answered, use the jQuery validation plugin.
Upvotes: 0
Reputation: 18258
You could change your bound function to:
.change(function(){ q# = counter_radio(q#,INPUT'S_ID); });
and add a return q;
to the end of your counter_radio function.
Upvotes: 3
Reputation: 45568
There's no native syntax for that, but you can e.g. use objects for that:
function counter_radio(q_,id){
if (q_.ref===false) {
q_.ref=true;
count++;
$("#counter").css("width", count);
$("#percent").text(count + "%");
}
$("span#"+id).append(", "+q);
$("span#"+id).fadeIn();
}
Upvotes: 1