How to display warning windows based on if checked or not using Javascript

I am trying to make sure that if the checkbox on our page is checked, it will display a warning message notifying the user they selected to show their discharge history. If the user deselects the checkbox, he should show another window with a warning that they refuse to show their statement history. I am having trouble displaying warning boxes, even if the checkbox is checked / not checked. 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.");
    }

Thanks.

+4
source share
3 answers

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
        }
    });
});

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


JavaScript ( 2018)

, javascript, .

// 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;

javascript- vanilla.js: http://vanilla-js.com/ framework;)

+16

, change, jQuery. javascript :

$("#showCheckoutHistory").change(function(event){
    if (this.checked){
        alert("You have elected to show your checkout history.");
    } else {
        alert("You have elected to turn off checkout history.");
    }
});

.

+7

jQuery. , . checkoutHistory var .

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

JSFiddle. http://jsfiddle.net/aaFe5/

+4

Source: https://habr.com/ru/post/1525834/


All Articles