Get Value of Checkbox using jQuery

0 min read 187 words

This one is quite an easy one, but a good one to mention non-the-less as it does definitely come in really handy.

If you would like to get a checkbox’s value to send to the backend using jQuery you can always do the following:

Firstly let’s draw some HTML to illustrate our example.

<input id="chkOurCheckbox" type="checkbox" />

Now we need some jQuery to do the real work.

var ourCheckboxValue = ($("#chkOurCheckbox:checked").val()=="undefined") ? 0 : 1

In our above example we draw an HTML checkbox to the screen and then use jQuery to return the value of it.

Bare in mind that the $("#chkOurCheckbox:checked") is an object so we need to get the value of it using .val().

Also bare in mind that it can have two values, either “on” or “undefined”, “undefined” means “not checked” and “on” means checked.

We perform a short if condition on the value and if it isn’t checked(/undefined) then we set our variable to be 0, alternatively if it is set then we set our variable to 1.

We now have a variable called “ourCheckboxValue” with a boolean value of our checkbox.

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags