Create event occur when checkbox is selected

Hi

I have something I am working on, I have created a fiddle here:

What I want to happen, if any checked box other than the first is selected, I want ifCheckDiv text box to appear (I am only trying to get existingGuided for now).

I can get this working with a group of radio buttons, but I think the problems could be

  1. the ID is “buried” for the checkbox in the field set
  2. checkValDiv is not being called
  3. I assume checkboxes work slightly differently to radio buttons.

I can post code for what I can get working later.

I’d do it by adding a class to the elements you want to use it on, then using querySelectorAll to grab them.

So on the elements you want the listener add a class, it can be any class name you want:

<input type="checkbox" name="Left-hand side menu item" id="leftHand" class="someclass"/>

Then in your JavaScript, grab the elements by using querySelectorAll, which will give you back a list of elements which you can then loop through.

var someClasses = document.querySelectorAll('.someclass');

someClasses.forEach(function(entry){
    entry.addEventListener('change', function(){
        if(this.value === 'existingGuided') {
    	    Show('ifCheckDiv');
        } else {
    	    Hide('ifCheckDiv');
        }
    });
});

However, I just noticed you have multiple names on your elements. You can’t do that. An element must only have a single name. It looks like you’re using names as if they were classes. It’s ok to have multiple classes on an element.

Hi, ty for taking the time to reply.

I am currently studying the SitePoint “Simply Javascript” book, so please allow me to pick your brain a little over this.

Working backwards.

Are you certain that the elements must have the same name? For example ( I know this source can be wrong) - w3c schools on checkboxes:

Mind you they have a radio button example with the same name on each element.

I am only able to post two links with this account (believe it or not I have been a member since 2006). I will try make something work and post a JS fiddle.

Hi, I have created a fiddle. I have some more questions.

  1. I tried to get this method to work in JS fiddle only, but could not get the form to appear on selection. Is this a JS fiddle thing, or is there an issue with my code?

  2. Why can’t we use the ID, why do we have to make a class?

  3. If for some reason we have to use a class, can we put it with the other one in the div above (where the in line class is used).

TY

Hi

(edit - I tried your method and it did not work. I think we need to be able to first check if the box is in a state of checked === true). I will now attempt to create something. Wish me luck!

I was thinking about this, and if we can say “if checked = true, do this”, it might work.

This is what gave me the idea.

I might try write something see what I can come up with.

I’ll also try the above example now I have all the code in front of me.

Update

I have found this method, which seems good, however I need to figure out how to make it work in the context of my problem.

Are you certain that the elements must have the same name?

No, names should be unique to the element and each element should only have one name. You’re getting names confused with classes. My solution is based on classes.

Radio buttons are different, because they are a multiple choices items that you must choose 1 of. Checkboxes (and other elements) are individual and you can select any combination of them.

Why can’t we use the ID, why do we have to make a class?

ID’s are unique. There must only be one element per id on the page. There can be multiple elements with the same class on a page. document.querySelectorAll('.someclass'); will return an array of those elements, where as document.getElementById('#someid') will only return a single reference to an element.

If for some reason we have to use a class, can we put it with the other one in the div above (where the in line class is used).

If you want. But I don’t see any reason to. You can get the element by finding it with a CSS selector, which you can use inside the querySelectorAll function.

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors

So that means you can use something like:

var elms = document.querySelectorAll('.someclass input[type=checkbox]'); 

But, I don’t see any reason to do that instead of just setting the class directly to the input.

We don’t have to use a class, it’s just the best/easiest solution I can think of off the top of my head. You can design this any way you want as long as you abide by the rules of HTML/CSS/JS. But even those rules can be hazy because browsers support things that don’t necessarily follow proper standards.

I have found this method, which seems good, however I need to figure out how to make it work in the context of my problem.

You could use that.

Here is some more reading on them:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Event_attributes

I avoid them, because it mixes your JavaScript with your HTML. If you notice on that page, they suggest the same thing. But if you’re just trying to get it to work, then there’s no inherent reason to not use them as a beginner. Just keep in mind that it’s bad practice.

Warning: These attributes should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the Window object, polluting the global namespace.

If you ever start getting into HTML rendered in your JavaScript via React or Vue, you’ll notice that HTML Events will come back. But, that’s a different paradigm you shouldn’t worry about right now.

Hi

Thanks for the detailed reply. Before I go too deep in, I’d like to clarify one thing (I’m a little confused by your reply)"

Please define element in the context of my example, is an element each checkbox option (which can have a unique name), or, the entire checkbox itself?

Looking at this, I am guessing you are going to say that an element is the checkbox, and that checkbox can contain a number of inputs / options.

Reason I am confused

  1. you started off answering my question saying no, does that mean you are not certain:)

  2. I have located multiple examples where the name is unique to a checkbox item.

What am I doing to educate myself?

I have run through the W3 schools function and events tutorials several times, and I am currently up to the DOM chapt in the sitepoint book I have.

Thanks,
Backspace / Unconformed

BTW - this is me. I have my real account back woot!

1 Like

Please define element in the context of my example, is an element each checkbox option (which can have a unique name), or, the entire checkbox itself?

An element is an DOM element, which is pretty much anything you define in HTML. In the context of your code, I’m referring to the <input type="checkbox" ... /> element.

I have located multiple examples where the name is unique to a checkbox item.

I guess with a checkbox, you could have multiple elements with a single name. But they will not be unique when they are sent back to the server and they will be sent in an array or as separate elements all with the same name, but with different values (which is then usually turned into an array on the server). This is usually better handled by unique names, but I can think of some use cases where it could be argued that you need the list.

Are you seeing this one W3Schools? I’d be interested in seeing where. W3Schools is notorious for having bad information and being misleading. Supposedly they have cleaned it up, but if you’re seeing this, then they haven’t.

Hi - thanks again for continuing on this conversation.

Ok cool, so just so we are clear, are you saying that each checkbox element should be unique? OR are you saying they should be the same for everything in the fieldset?
Because currently, each checkbox element does have a unique name:

      <fieldset>
              <legend><strong>Please select what this enhancement relates to (tick box, multiple can be selected)</strong></legend>
              <div id="checkValDiv">
                <div class="inline">
                  <input type="checkbox" name="New functionality" id="newFunctionality"/>
                  <label for="newFunctionality">New functionality</label>
                </div>
                <div class="inline">
                  <input type="checkbox" name="Existing Guided Procedure" id="existingGuided" onclick="handleClick;"/>
                  <label for="existingGuided">Existing Guided Procedure</label>
                </div>
                <div class="inline">
                  <input type="checkbox" name="Existing Workspace menu item" id="existingWorkspace"/>
                  <label for="existingWorkspace">Existing Workspace menu item</label>
                </div>
                  <div class="inline">
                  <input type="checkbox" name="Left-hand side menu item" id="leftHand"/>
                  <label for="leftHand">Left-hand side menu item</label>
                </div>
                <div class="inline">
                  <input type="checkbox" name="access" id="access-1"/>
                  <label for="access-1">Access</label>
                </div>
              </div>
            </fieldset>

----

You originally said "However, I just noticed you have multiple names on your elements. You can't do that. An element must only have a single name. It looks like you're using names as if they were classes. It's ok to have multiple classes on an element."

In regards to W3 schools, [this example uses the same name for each element](http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_checkbox_order). 

Where this [examples uses different names](http://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_checkbox) 


Secondly, I am keen to explore your suggested method, however I am unable to get it to work. Would you mind showing me an example of the method working?

This is my attempt is JS fiddle.

In case there is an issue with JS fiddle, here is the same example in JS bin.

Thanks again for the time, I really appreciate it (I think I am a very slow learner!)

are you saying that each checkbox element should be unique?

Yes.

Because currently, each checkbox element does have a unique name:

Ah, I see your problem. You shouldn’t put spaces in your names. I actually didn’t even know you could do that before I tested it just now. I thought you were trying to assign multiple names to A name is like a variable name, it should be 1 word, short, and descriptive.

Hi

Thanks for clearing that up. sorry for the confusion.

Now onto the original post, I tried your method, however I was unable to get it to work, would you mind checking my work?

Currently you are checking the checkbox value.

if(this.value === 'existingGuided') {

Here is one of the checkboxes:

<input type="checkbox" name="features" id="existingGuided" class="newFunctionality-2"/>

What is the value of that checkbox?

1 Like

It is a Boolean, so it should be true or false.

So instead of

if(this.value === ‘existingGuided’) {

if(this.value === ‘true’) // do something

else
// do something else

I will have a fiddle with my fiddle.

hi

with respect, I don’t believe this is accurate.

At least this and this stack exchange site would suggest not. However, they do say it could get you into trouble. I ask because all the forms at work have space in the names attribute.

From the HTML 4.01 specs, we are told:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by
any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
colons (":"), and periods (".").

https://www.w3.org/TR/html401/types.html#type-cdata

I did see this. I will drop it now haha
We are using
XHTML 1.0 Transitional

So I ahev been working on this. I still lack some fundamental understandings, so I went back over some form tutorials. Specially, I was interested in what the “value” attribute is used for.

The example form I was using has a value for checkbox, however I crafted mine off the radio buttons to get them to stack (rather than sit inline, wrong method I used, I now realise).

so to answer your question, I don’t have a value set, according to this article it is a mandatory value, and the Mozilla developer site has one set (note, that last URL is using HTML 5, and the name attribute has now been deprecated, I think. Thus, it is not in this example).

I’m still missing some very basic pieces I need to fully understand and solve this problem. I have done some more study over the weekend (SitePoint JavaScript book, still on DOM, chapter 4).

During my research, I have located another possible solution. Determine if the checkbox is checked, and if yes, do this.

<form name="test">
 <input type="checkbox" name="checkgroup" checked />
 <input type="checkbox" name="checkgroup" />
 <input type="checkbox" name="checkgroup" checked />
 </form>

 <script type="text/javascript">
 for (i=0; i<document.test.checkgroup.length; i++){
 if (document.test.checkgroup[i].checked==true)
 alert("Checkbox at index "+i+" is checked!")
 }
 </script>

I’ll add a vaule to example supplied by mawburn and see if I can get that approach working, and I’ll have a crack at the method I have posted just now.

I have made an update.

I can see that I am asking If the value is “something”, do something else. And I had no value set.

I have done some research and I know that the value attribute is sent along with the form name so the server. But I think I need to be checking if the state of the checkbox is “checked”. Because I am following Mawburns example an using the ‘querySelectorAll’ (method?), I’m a little confused. I’ll keep working on something.