icor103
icor103

Reputation: 203

Form Value with jQuery and POST - Single Checkbox

This successfully returns a result, but the result is useless to me. In the php file, I have this simple code: var_dump($_POST['rememberMe']);

Whether the checkbox is marked or not, the result is string(2) "on". How do I get a result that changes based on whether the checkbox is marked?

Thanks.

Remember Me: <input type="checkbox"
                    id="remember">

<div id="result" style="margin-top:20px;">


<script>

$("#submit").click(function(){
    submitLogin();
});

$("#password").keyup(function (f){
    if (f.keyCode == 13) {
        submitLogin();
    }
});


function submitLogin(){
    $.post("php/test.php", { 
        loginUsername:$('#username').val(), 
        loginPassword:$('#password').val(),
        rememberMe:$('#remember').val()
    }, function(data){
        $("#result").text(data);
    });
}

</script>

Upvotes: 0

Views: 106

Answers (3)

icor103
icor103

Reputation: 203

This:

rememberMe:$('#remember').val()

Needed to become:

rememberMe:$('#remember').is(':checked')

Upvotes: 0

Paul
Paul

Reputation: 9022

The value attribute is mandatory for checkboxes and defaults to on. This applies whether the checkbox is checked or not, the value is always the same. What you want is to check the state of the checkbox (not its value).

$('#remember').prop("checked")

Btw, this is way faster than .is(:checked), see http://jsperf.com/prop-vs-ischecked/5 for a comparison.

Upvotes: 1

user2755150
user2755150

Reputation:

It's better if you serialized the form that you are sending via post $("form").serialize(); Then, in the target page, just check if $_POST['rememberMe'] exists. (If the checkbox isn't checked, isset for $_POST['rememberMe'] will be equal to false)

Upvotes: 0

Related Questions