Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".)

like image 290
Koerr Avatar asked Dec 14 '25 20:12

Koerr


2 Answers

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 />
like image 90
David Tang Avatar answered Dec 17 '25 10:12

David Tang


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

like image 41
ssk Avatar answered Dec 17 '25 11:12

ssk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!