Same Javascript for multiple sets of html checkboxes

Asked
Active3 hr before
Viewed126 times

8 Answers

javascriptmultiple
90%

My question is regarding the javascript part. Is there any way to make it common for both sorting sets of checkboxes? Or should I create a new javascript for this second filter and so on for any new sorting filters I would like to add?,The jQuery .change() function can be passed an eventObject parameter that has a bunch of data about the event on it. More importantly, inside the .change function, the local variable this is set to the item that the event was fired on. So you should be able to do something like this:,It's unusual to include a connection file more than once per script, and even more unusual to include it from inside a function. I don't know what it's doing, so I didn't refactor it at all; it looks like it is responsible for creating and/or modifying a variable called $con, which is not my favorite way of connecting to a database.,So your change function is now only aggregating together checkbox inputs which share the same name as the one that changed. It looks like this is compatible with your markup. I assumed that your indexMain.php loader script works the same for prices as it does colors. You might need to strip of the square braces ([]) from the end of the name for it to do the right thing. If your behavior needs to be significantly different between colors and prices, you could always just run a switch on the name.

The jQuery .change() function can be passed an eventObject parameter that has a bunch of data about the event on it. More importantly, inside the .change function, the local variable this is set to the item that the event was fired on. So you should be able to do something like this:

$(function() {
   $("input[type='checkbox']").on('change', function() {
      var boxes = [];
      // You could save a little time and space by doing this:
      var name = this.name;
      // critical change on next line
      $("input[type='checkbox'][name='" + this.name + "']:checked").each(function() {
         boxes.push(this.value);
      });
      if (boxes.length) {
         $(".loadingItems").fadeIn(300);
         // Change the name here as well
         $(".indexMain").load('indexMain.php?' + this.name + '=' + boxes.join("+"),
            function() {
               $(".indexMain").fadeIn('slow');
               $(".loadingItems").fadeOut(300);
            });

      } else {
         $(".loadingItems").fadeIn(300);
         $(".indexMain").load('indexMain.php', function() {
            $(".indexMain").fadeIn('slow');
            $(".loadingItems").fadeOut(300);
         });
      }
   });
});
load more v
88%

In addition to the common attributes shared by all <input> elements, "checkbox" inputs support the following attributes.,Note: No browser currently supports indeterminate as an attribute. It must be set via JavaScript. See Indeterminate state checkboxes for details.,Note: Radio buttons are similar to checkboxes, but with an important distinction — radio buttons are grouped into a set in which only one radio button can be selected at a time, whereas checkboxes allow you to turn single values on and off. Where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected.,In addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the HTMLInputElement object's indeterminate property via JavaScript (it cannot be set using an HTML attribute):

<form>
   <div>
      <input type="checkbox" id="subscribeNews" name="subscribe" value="newsletter">
      <label for="subscribeNews">Subscribe to newsletter?</label>
   </div>
   <div>
      <button type="submit">Subscribe</button>
   </div>
</form>
load more v
72%

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:,Let the user select one or more options of a limited number of choices:,Checkboxes are used to let a user select one or more options of a limited number of choices.

Definition and Usage

The <input type="checkbox"> defines a checkbox.

<input type="checkbox">
load more v
65%

Checkboxes Checked or not checked? Multiple choices Labels for checkboxes Working dynamically with a checkbox Summary ,However, as with all input elements, you need to define a name for it to be usable - without a name, the element won't be identifiable when posting the form back to a server for processing. You also want to set a value - this will be the value sent to the server if the checkbox has been checked. Here's an example:,In the old days of XHTML, where each attribute should always have a value, even the boolean attributes, it would look like this:,With this example, if the checkbox has been checked and the form is submitted to a server, the server will be able to read the form element "nameOfChoice" and its value will be 1.

Using checkboxes is a good option when you want to give your visitors the option to choose several items from a group of choices. In that regard, the checkbox works opposite of a radio button, which only allows you to select one item from a group of choices. In its most simple form, a checkbox is simply an input element with the type property set to checkbox, like this:

<input type="checkbox">
load more v
75%

Managing checkboxes in HTML, specifically using JavaScript and jQuery can seem a bit unnatural. I hope to resolve common problems you may be having with this tutorial.,There are two general use cases for a checkbox:,When using form encoding checkboxes of the same name values are all serialized:,This is where the checkbox becomes even better, through grouping. Here you have two or more checkboxes with the same name, but different values. We have already seen how this can be used in the previous examples.

Programatically you can get the current value or check state from the value property, which is also an attribute. The value is not true or false, even though the nature of the checkbox is to indicate if a value is selected or not.

 var btnSubscribe = document.getElementById("btnSubmitSubscribe");
 btnSubscribe.addEventListener("click", function(evt) {
          evt.preventDefault();
          var subscribe = document.querySelector("[name=subscribe]");
          console.log(subscribe.value); //writes 'newsletter' return false; });
load more v
40%

Several checkboxes in a form may share the same control name. Thus, for example, checkboxes allow users to select several values for the same property. The INPUT element is used to create a checkbox control.,The control type defined by the INPUT element depends on the value of the type attribute:,Users interact with forms through named controls.,The label attribute of the OPTGROUP element specifies the label for a group of choices.

Here's a simple form that includes labels, radio buttons, and push buttons (reset the form or submit it):

 <FORM action="http://somesite.com/prog/adduser" method="post">
    <P>
       <LABEL for="firstname">First name: </LABEL>
       <INPUT type="text" id="firstname"><BR>
       <LABEL for="lastname">Last name: </LABEL>
       <INPUT type="text" id="lastname"><BR>
       <LABEL for="email">email: </LABEL>
       <INPUT type="text" id="email"><BR>
       <INPUT type="radio" name="sex" value="Male"> Male<BR>
       <INPUT type="radio" name="sex" value="Female"> Female<BR>
       <INPUT type="submit" value="Send"> <INPUT type="reset">
    </P>
 </FORM>
load more v
22%

<form method="post" action="/Tests/Post/">
   <fieldset>
      <legend>What is Your Favorite Pet?</legend>
      <input type="checkbox" name="favorite_pet" value="Cats">Cats<br>
      <input type="checkbox" name="favorite_pet" value="Dogs">Dogs<br>
      <input type="checkbox" name="favorite_pet" value="Birds">Birds<br>
      <br>
      <input type="submit" value="Submit now" />
   </fieldset>
</form>
load more v
60%

Checkbox: Checkboxes are also mostly used in HTML forms. A checkbox allows you to choose one or many options to be selected from a list of options.,Convert a string to an integer in JavaScript,Form validation using HTML and JavaScript,How to convert JSON string to array of JSON objects using JavaScript ?

Other "javascript-multiple" queries related to "Same Javascript for multiple sets of html checkboxes"