javascript - Add and remove values inside array in change event of checkbox

Javascript - Add and remove values inside array in change event of checkbox

You can use the change event of a checkbox to add or remove values from an array in JavaScript. Below is an example using plain JavaScript:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Checkbox Array Example</title> </head> <body> <label> <input type="checkbox" value="apple" id="checkboxApple"> Apple </label> <label> <input type="checkbox" value="banana" id="checkboxBanana"> Banana </label> <label> <input type="checkbox" value="orange" id="checkboxOrange"> Orange </label> <script> // Array to store selected fruits const selectedFruits = []; // Function to handle checkbox change event function handleCheckboxChange(event) { const checkbox = event.target; const value = checkbox.value; if (checkbox.checked) { // Add value to the array if checkbox is checked selectedFruits.push(value); } else { // Remove value from the array if checkbox is unchecked const index = selectedFruits.indexOf(value); if (index !== -1) { selectedFruits.splice(index, 1); } } // Log the selected fruits array console.log('Selected Fruits:', selectedFruits); } // Add change event listeners to the checkboxes document.getElementById('checkboxApple').addEventListener('change', handleCheckboxChange); document.getElementById('checkboxBanana').addEventListener('change', handleCheckboxChange); document.getElementById('checkboxOrange').addEventListener('change', handleCheckboxChange); </script> </body> </html> 

In this example:

  • Each checkbox has a unique ID (checkboxApple, checkboxBanana, checkboxOrange).
  • The handleCheckboxChange function is called when any checkbox is changed.
  • If a checkbox is checked, its value is added to the selectedFruits array. If it is unchecked, its value is removed from the array.
  • The selected fruits array is logged to the console for demonstration purposes.

You can customize and expand this example based on your specific use case or requirements.

Examples

  1. "JavaScript checkbox change event example"

    • Code:
      // JavaScript checkbox change event example const checkbox = document.getElementById('myCheckbox'); const selectedValues = []; checkbox.addEventListener('change', function() { if (this.checked) { // Add value to array selectedValues.push(this.value); } else { // Remove value from array const index = selectedValues.indexOf(this.value); if (index !== -1) { selectedValues.splice(index, 1); } } // Display updated array console.log('Selected Values:', selectedValues); }); 
    • Description: A basic example demonstrating how to add and remove values from an array based on the change event of a checkbox.
  2. "JavaScript checkbox array manipulation"

    • Code:
      // JavaScript checkbox array manipulation // ... (same as previous code) // Display updated array in a list const resultList = document.getElementById('resultList'); resultList.innerHTML = selectedValues.map(value => `<li>${value}</li>`).join(''); // ... (same as previous code) 
    • Description: Extends the previous example by displaying the updated array values in an HTML list for better visualization.
  3. "Toggle values in JavaScript array with checkbox"

    • Code:
      // Toggle values in JavaScript array with checkbox // ... (same as previous code) // Toggle value presence in array if (this.checked) { // Add value if not present if (!selectedValues.includes(this.value)) { selectedValues.push(this.value); } } else { // Remove value if present const index = selectedValues.indexOf(this.value); if (index !== -1) { selectedValues.splice(index, 1); } } // ... (same as previous code) 
    • Description: Enhances the code to toggle the presence of values in the array based on checkbox state.
  4. "JavaScript checkbox array and form submission"

    • Code:
      // JavaScript checkbox array and form submission const form = document.getElementById('myForm'); form.addEventListener('submit', function(event) { event.preventDefault(); // Use selectedValues array in form submission console.log('Form submitted with values:', selectedValues); // Additional form submission logic here }); // ... (same as previous code) 
    • Description: Demonstrates incorporating the checkbox array into a form submission, preventing the default form behavior.
  5. "Dynamically create checkboxes in JavaScript"

    • Code:
      // Dynamically create checkboxes in JavaScript const checkboxContainer = document.getElementById('checkboxContainer'); const valuesToDisplay = ['Option 1', 'Option 2', 'Option 3']; valuesToDisplay.forEach(value => { const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.value = value; checkbox.id = value.toLowerCase().replace(/\s/g, ''); // Generate unique ID checkbox.addEventListener('change', checkboxChangeHandler); checkboxContainer.appendChild(checkbox); const label = document.createElement('label'); label.htmlFor = checkbox.id; label.textContent = value; checkboxContainer.appendChild(label); }); function checkboxChangeHandler() { // ... (same as previous code) } 
    • Description: Illustrates how to dynamically create checkboxes in JavaScript and associate them with a change event handler.
  6. "Using data attributes with JavaScript checkboxes"

    • Code:
      // Using data attributes with JavaScript checkboxes // ... (same as previous code) // Access custom data attribute for value const value = this.getAttribute('data-value'); // Toggle value presence in array if (this.checked) { // Add value if not present if (!selectedValues.includes(value)) { selectedValues.push(value); } } else { // Remove value if present const index = selectedValues.indexOf(value); if (index !== -1) { selectedValues.splice(index, 1); } } // ... (same as previous code) 
    • Description: Enhances the code to use custom data attributes for associating values with checkboxes.
  7. "JavaScript ES6 arrow functions and array manipulation"

    • Code:
      // JavaScript ES6 arrow functions and array manipulation // ... (same as previous code) // Toggle value presence in array using arrow function this.checked ? selectedValues.includes(value) || selectedValues.push(value) : selectedValues.includes(value) && selectedValues.splice(selectedValues.indexOf(value), 1); // ... (same as previous code) 
    • Description: Updates the code to use ES6 arrow functions for concise array manipulation.
  8. "JavaScript event delegation for checkboxes"

    • Code:
      // JavaScript event delegation for checkboxes const checkboxContainer = document.getElementById('checkboxContainer'); checkboxContainer.addEventListener('change', function(event) { if (event.target.type === 'checkbox') { checkboxChangeHandler.call(event.target); } }); // ... (same as previous code) 
    • Description: Introduces the concept of event delegation, optimizing the code for handling checkbox changes within a container.

More Tags

random tidyeval mongodb-.net-driver h.264 angular-material-datetimepicker uibutton serial-port npm-scripts audio-streaming jquery-mobile

More Programming Questions

More Everyday Utility Calculators

More Bio laboratory Calculators

More Date and Time Calculators

More Investment Calculators