Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a checkbox without a form

Tags:

I have been trying to make a simple app with 3 fields like this:

    <div id = "nameInput" >Name:</div><input id = "nameInputField" type = "text" name = "userName" />
    <div id = "emailInput" >Email:</div><input id = "emailInputField" type = "text" name = "email" />
    <input id = "termsCheck" type = "checkbox" name = "terms" />

The problem I am having is that I keep needing to try to wrap it in a form to get the checkbox to register as checked when it is. I DO NOT want to use a form because I don't ever want to submit anything.

Here is the JS for the checkbox as well. It is always marked as unchecked:

if ($('#terms').checked == true) {
    //Rest of code

Is there a way to make this without using a form or is there a reason that my checkbox is never registered as checked?

like image 434
Soatl Avatar asked May 18 '11 18:05

Soatl


People also ask

Does a checkbox need to be in a form?

Contrary to popular belief, having a checkbox on every form that collects is not required under the GDPR. A checkbox isn't required if the user, by submitting a form for its stated use, gives explicit consent.

How do you make a checkable box in HTML?

The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!

How do I make text a checkbox?

var text = $('input[type="checkbox"]'). text(); alert(text);


2 Answers

<input id = "termsCheck" type="checkbox" name="terms" />

JS:

pre jQuery 1.6:

if($('#termsCheck').is(':checked')){}

after jQuery 1.6:

if($('#termsCheck').prop('checked')){}
like image 162
Naftali Avatar answered Oct 04 '22 15:10

Naftali


Two issues.

First, you're referencing the name of the input instead of its ID.

Second, in order to use the checked property, it must be done on the DOM element, not the jQuery object.

if( $('#termsCheck')[0].checked ) {
    // ...
}

This is accessing the DOM element at index 0 of the jQuery object, then accessing its checked property.

You could also use the get()[docs] method to retrieve the DOM element.

if( $('#termsCheck').get(0).checked ) {
    // ...
}
like image 31
user113716 Avatar answered Oct 04 '22 14:10

user113716