Function to dynamically update checkboxes using Ajax

I'm attempting to utilize AJAX to send a checkbox value to an external function.

Although I have the function working with the current JavaScript code, it's quite messy because I'm duplicating the script for each instance that exists.

<form>
<input type="checkbox" name="event_status" id="event_status1455" value="1" <?php echo ($event_status == '1' ? 'checked="checked"' : '') ?>>
</form>

<form>
<input type="checkbox" name="event_status" id="event_status1456" value="1" <?php echo ($event_status == '1' ? 'checked="checked"' : '') ?>>
</form>

<form>
<input type="checkbox" name="event_status" id="event_status1457" value="1" <?php echo ($event_status == '1' ? 'checked="checked"' : '') ?>>
</form>

<script>
 $('input:checkbox').change(function(e) {
e.preventDefault();
var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
$.ajax({
          type: 'POST',
          url: '<?php echo $this->url('/profile/list', 'event_status', $cobj->getCollectionID())?>',
        data: { event_status:$("input:checkbox").attr("id"), event_status:isChecked }
});        
});
</script>

The issue lies in the fact that the current JavaScript only applies to a specific checkbox. I am searching for a way to create a single JavaScript function on my page that can handle multiple checkboxes.

I've made some modifications to the original code. While my AJAX is functioning as desired, it only works for the last checkbox. Is there a way to adjust the JavaScript to make it work for all checkboxes?

Answer №1

Resolved my issue by figuring out how to get the ID of the checkbox so that I can determine which checkbox value my function was acting on.

<script>
$('input:checkbox').change(function(e) {
e.preventDefault();

// Identify ID
 var value = $(this).attr('id');
 var EsID = value;

var isChecked = $("input:checkbox").is(":checked") ? 1 : 0; 
$.ajax({
          type: 'POST',
          url: "<?php echo $this->url('/profile/list', 'event_status')?>" + EsID + "",
        data: { event_status:$("input:checkbox").attr("id"), event_status:isChecked }
});        
});
</script>

Answer №2

Consider assigning a class to your checkbox input and triggering the change event on that class rather than the checkbox name.

For example:

Replace

$('#event_status<? echo $cobj->getCollectionID()?>').change(function() {

with

$('.CheckboxClassName<? echo $cobj->getCollectionID()?>').change(function() {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

``How can we successfully transfer an array containing transferable objects, such as buffers, alongside non-transferable objects, like JSON objects, using the postMessage() method in JavaScript when working with web

My goal is to call a specific function onMessage() in the main thread from a web worker. I also need to pass an array of transferable objects such as Uint16Array buffer, Float32Array buffer, along with a boolean object, integer, or string value while posti ...

What method does jQuery 2.x use to distinguish one element from another in the .data() function?

Back in the days of jQuery 1.x, elements would be assigned a unique identifier known as a cache key, stored in the ele[jQuery.expando] property of a node set by a specific line of code. This caching mechanism has similarities with how Mootools handles its ...

Chrome Developer Tools - Array Length Discrepancies

While exploring Chrome DevTools, I came across an inconsistency that caught my attention. The screenshot above shows the issue I encountered. Initially, it indicated that the object contained a Body and a Head, with the head being an array of length 1. Ho ...

Selecting a "non-operational" collection location on an e-commerce platform

Recently I discovered a bug on an online shopping website. It seems that by using inspect element, it was possible to alter the HTML code and change an unavailable pickup point to available. This allowed me to place an order, make a payment, and even recei ...

Creating an array of options for a jQuery plugin by parsing and populating

I am currently in the process of developing my very first jQuery plugin. The main function of this plugin involves taking JSON data and loading it into a table. Although most of the logic has been implemented successfully, I am facing challenges when it co ...

Is there a way to remove the image preview once it has been submitted?

When I preview an image and submit it, the preview of the image remains even after adding a comment. I would like the image preview to be automatically removed once it has been submitted. This is the HTML code I am using: function displayImagePreview( ...

Event triggered when a tab is changed in an Ajax Tab control

I have incorporated an Ajax Tab Control into a page, which features a master User Control containing three tabs. Each of these tabs is filled with content from three distinct user controls that contain various controls and a save button for data input. My ...

The enigmatic disappearance of data in PHP fopen()

My current process involves using the fopen() function with the binary-read parameter ("rb") on an image file. Here's how it looks: $imageURL = "assets/" . $gameObject . "Assets" . "/" . $gameObject . $description . "Base8SmallPNG.png"; $imag ...

Two steps to execute an Ajax script

I have a function to call a PHP script using Ajax, and I would like to add another event to call the same PHP page without repeating the same Ajax call. How can I achieve this? $('.episodeNum').change(function(){ var formItems = $('form ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

Trigger alerts when the button is clicked

Why are my alerts not working when I click the button? Could it be because I forgot to include some JavaScript files in the header section? Take a look at my login form view: <?php echo CHtml::beginForm(); ?> <div class="row"> <?php echo ...

Exploring the fundamentals of fragment shaders in three.js: utilizing position data to color individual fragments

I am experimenting with coloring the fragments in my shader based on their position between the highest and lowest vertex. Take a look at the shaders below: <script type="x-shader/x-vertex" id="vertexshader"> uniform float span; attr ...

Session management in Laravel is seamlessly handled even during an ajax login process

Is it possible to maintain or establish a session via Ajax login in my Laravel setup, which is similar to the basic make:auth installation? I had to modify some parts of the authcontroller to return JSON instead of redirects. Below is the code snippet for ...

Toggle the checkbox to either allow or prevent scrolling within the div element's content

I have successfully used jQuery to append content to a div on my website. In addition, I have applied CSS to the div with the following styling: #data { height: 700px; position: absolute; left: 0; right: 0; overflow-y: auto; vertical-align: b ...

Javascript code to verify whether the page is currently positioned at the top

How can I use JavaScript to determine if the page is at scroll(0,0)? I have a full-page slider that needs to pause when the page is no longer at the top. The page may not be scrolled manually, as there are internal HTML # links that could load the page d ...

Using Javascript, dynamically animate the text in the hero unit with fading in and out effects

I currently have a "Hero" unit with the following code: <div class="hero-unit"> <div class="container"> <h1>Dapibus Euismod Mollis</h1> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis ...

I'm facing an issue with retrieving data from the req.user object in passport js

Implementing passport.js in my node/express project has been quite a journey. I utilized the authenticationMiddleware() Integrating it within one of the routers was a crucial step. To ensure everything is functioning smoothly, I set up logs to track the ...