/    Sign up×
Community /Pin to ProfileBookmark

Convert a jQuery boolean to a HTML FORM boolean when submitting

I have a checkbox which I use to change form settings before submitting.

“`
$(‘#hidden_form_field’).val( $(‘#checkbox’).is(‘:checked’) );
“`

However, when I submit the form, the value comes through as a string ‘true’ or ‘false’ which evaluates to true every time.

So I’ve changed it to the following but it just seems odd writing if true then true (1) or if false then false (0). Is there a cleaner way or is this just the way it is because jQuery and HTML forms don’t play together nicely?

“`
$(‘#hidden_form_field’).val( $(‘#checkbox’).is(‘:checked’)?1:0 );
“`

to post a comment
HTMLJavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogSep 30.2022 — If I were doing it, I would not use the hidden field at all. Since the checkbox element/value only gets submitted if it is checked, you can just check for its existence in the server-side code that handles the form. E.g., in PHP:
[code=php]
$it_was_checked = isset($_POST['the_checkbox_name']);
// result will be a Boolean
[/code]
×

Success!

Help @php-bgrader spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...