Reputation: 133
I have a list of check-box items with number values like "30%", "20%", and I want to allow the user to check only two boxes and compare them and show the positive or negative difference value. I have started with the following code:
HTML:
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">10%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">20%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">40%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">60%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">80%</label>
<div id="resultsection"></div>
JS:
$('input[type="checkbox"]').live('click', function() {
var selected = '';
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
selected += ($('label[for="'+this.name+'"]').html() + ', ');
}
});
if (selected.length > 0) {
selected = "You have selected the following: <br /> " + selected.substring(0,selected.length-2) + '.<br />';
} else {
selected = 'No metrics selected.';
}
$('#resultsection').html(selected);
});
what this does is show the values of the selected items inside the #resultsection. What I need is get only two values and store them as two cookie variables to make use of them after page reload. Then we can add a button to compare between the two values like (first-value - second-value = %result).
I appreciate you help.
Upvotes: 0
Views: 1613
Reputation: 21233
I have done the logic for you (fiddle). It does:
Now you just need to store the values in cookies and do whatever you want to do with 2 values.
$('input[type="checkbox"]').live('click', function() {
var selected = '';
var values = [];
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
selected += "<span>" + $(this).next().html() + " </span> ";
values.push($(this).next().html());
}
if($('input[type="checkbox"]:checked').length > 1 ) {
$('input[type="checkbox"]').each(function(index, value) {
if (!this.checked) {
$(this).attr("disabled", true);
}
});
}
});
if(values[0] == values[1]) {
console.log('true');
} else {
console.log('false');
}
if (selected.length > 0) {
selected = "You have selected the following: <br /> " + selected + '.<br />';
} else {
selected = 'No metrics selected.';
}
$('#resultsection').html(selected);
});
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">10%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">20%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">40%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">60%</label>
<input type="checkbox" class="box" name="metrics1" value="" />
<label for="metrics1">10%</label>
<div id="resultsection"></div>
Upvotes: 1