Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  166] [ 4]  / answers: 1 / hits: 65781  / 11 Years ago, fri, february 7, 2014, 12:00:00

I am trying to make it so that if the checkbox on our page is checked it will display an alert message notifying the user they have opted in to showing their checkout history. If the user deselects the check box then it should show another alert box letting them know they are opting out of showing their checkout history. I am having trouble just displaying alert boxes if the check box is even checked/unchecked. Here is my code.



HTML



<div class=myAccountCheckboxHolder id=showCheckoutHistoryCheckbox>
<input tabindex=40 checked=checked id=showCheckoutHistory name=showCheckoutHistory type=checkbox>
<label for=showCheckoutHistory class=checkLabel>Show my checkout history</label>
</div>


Javascript



function validate() {
var checkoutHistory = document.getElementById('showCheckoutHistory');
if (checkoutHistory.checked) {
alert(You have elected to show your checkout history.);
} else {
alert(You have elected to turn off checkout history.);
}


Thank you.


More From » jquery

 Answers
2

jQuery (original answer)



jQuery(document).ready(function() {
jQuery('#showCheckoutHistory').change(function() {
if ($(this).prop('checked')) {
alert(You have elected to show your checkout history.); //checked
}
else {
alert(You have elected to turn off checkout history.); //not checked
}
});
});


Documentation here: http://api.jquery.com/prop/






JavaScript (2018 update)



It is worth to notice, that you don't need any javascript libraries to acomplish that.



// Check current state and save it to checked variable
var checked = document.getElementById(showCheckoutHistory).checked;

// Set state manually (change actual state)
document.getElementById(showCheckoutHistory).checked = true; // or
document.getElementById(showCheckoutHistory).checked = false;


For more pure javascript solutions I recommend vanilla.js: http://vanilla-js.com/ framework ;)


[#72662] Thursday, February 6, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiyam

Total Points: 448
Total Questions: 96
Total Answers: 92

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;