Koerr
Koerr

Reputation: 15723

How to get a default value from a checkbox element?

Below is my code:

<INPUT TYPE="checkbox" NAME="cb" value="1">

After form is submitted, I get cb==1, if cb element is checked,

I want to get cb==0, if cb element is not checked. How to implement it?

BTW: can't change receive page, like:

if(cb==null)cb=0;// no no no..

I want implement it at web front client.

I tried like this:

<INPUT TYPE="hidden" NAME="cb" value="0"> <!--add this line-->
<INPUT TYPE="checkbox" NAME="cb" value="1">

If cb is not checked, it can override <INPUT TYPE="hidden" NAME="cb" value="0"> else I can get cb==0.

but I feel this solution is not good.

any idea? thx~ :)


Thanks wowo_999 for comment:

"I'd just ignore the value of the checkbox period and use it to set the value of your hidden field based on if its checked or not. The way you suggest will send the value for cb 2x in your query string if the checkbox is checked." – wowo_999


In database,I set cb field default value as"0",but when I insert or update,if it is null,show: "java.sql.SQLException: Column 'cb' cannot be null",so,I need cb==0,not null.(I can't ignore cb field in sql query string,because I maybe need update cb to "0".)

Upvotes: 3

Views: 8034

Answers (3)

David Tang
David Tang

Reputation: 93674

If you're going to use the checkbox's value to set the value of the hidden input, you might as well use javascript to set the value of the checkbox. For example using jQuery:

$("input[type=checkbox]").change(function() {
    $(this).attr("value", $(this).attr("checked") ? 1 : 0);
});

Or, let the script set the value on page load as well:

$(function() {
    function updateCheckbox() {
        $(this).attr("value", $(this).attr("checked") ? 1 : 0);
    }
    // Run whenever checkbox is ticked or unticked
    $("input[type=checkbox]").change(updateCheckbox);
    // Run on page load
    updateCheckbox();
});

And now you can use regular HTML markup too, without any hidden inputs and without value attributes:

<input type="checkbox" name="cb" />

Or have it checked by default:

<input type="checkbox" name="cb" checked />

Upvotes: 1

ssk
ssk

Reputation: 11

you can use javascript to check whether its unchecked and change the value to 0 and set it checked, on submit.

Upvotes: 1

LightningWrist
LightningWrist

Reputation: 937

You can't default in the DB as "0"?

Upvotes: 0

Related Questions