Implementing a loop in jQuery is not functioning as expected

Can someone help me figure out how to use a for loop to create a jQuery function? I'm having trouble when adding the array parameter in the string, it just doesn't seem to work correctly. Any suggestions?

var ids=["width_uncheck","thickness_uncheck"];
var names=['width','thickness'];
for(i=0;i<2;i++){
    $("#"+ids[i] ).click(function() {
        $('input:radio[name='+names[i]+']').each(function(i) {
            this.checked = false;
        });
    });
}

Answer №1

This action is not possible because the value of i reaches its maximum when the click event is triggered.

To resolve this issue, utilize a JavaScript closure, which can be easily achieved with the $.each function.

$.each(ids, function(i, id){
   $("#"+id ).click(function() {
        // Instead of using `each`, utilize `prop()`
        $('input:radio[name='+names[i]+']').prop('checked',false);
    });
});

The key difference here is that i functions as an argument within the function and thus retains its value without changing within the function like it would in a traditional for loop.

Answer №2

You've encountered an error with the selector for radio names; make sure to include quotation marks.

Here is the corrected code snippet:

var ids=["width_uncheck","thickness_uncheck"];
var names=['width','thickness'];
for(var i=0;i<2;i++){
    $("#"+ids[i] ).click(function() {
        $('input:radio[name="'+names[i]+'"]').each(function(i) {
            this.checked = false;
        });
    });
}

Answer №3

Make sure to include quotes for the name in the selector.

If you prefer, you can utilize the jquery each function without specifying an element for your array.

$.each(ids, function (i, value) {
    var ids=["width_uncheck","thickness_uncheck"];
    var names=['width','thickness'];

    $("#"+ids[i] ).click(function() {
        $('input:radio[name="'+names[i]+'"]').each(function(i) {
            this.checked = false;
        });
    });
});

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

The buttons mysteriously vanish when hovered over in Internet Explorer 11

I've encountered a strange issue with my website www.webfounded.com when viewed in Internet Explorer - all of my bootstrap buttons disappear on hover! Despite adding CSS classes for multiple browser compatibility and even attempting to remove the hove ...

Using JavaScript regex to substitute white spaces and other characters

Here is a string I need to modify: "Gem. Buitentemperatuur (etmaal)" I want to remove all spaces, capital letters, and special characters from the string so that it becomes: "gem_buitentemperatuur_etmaal" ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

Leveraging AJAX and jQuery for data storage

Need a solution using AJAX and jQuery to save data from one form in another form while preserving the values. The stored information should be hidden from the front end user, with an option for the user to delete the data if desired. Retrieving the stored ...

Close the Bootstrap modal upon clicking the "Ok" button in SweetAlert2

I need help with closing my Modal Bootstrap after clicking the Ok button in SweetAlert. I've attempted various methods, but none of them have worked so far. I'm not sure if I'm implementing it correctly, but I've utilized JQuery for thi ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

Implementing precise search functionality in a table with jquery datatables

Hey there, I'm attempting to implement an exact search feature in jQuery datatables. In my table, I have a column called "status" with values of either "paid" or "unpaid". Currently, when I type "unpaid", it correctly displays only the unpaid record ...

What would be the most optimal choice for sorting in this particular situation within my PHP script?

I have successfully written a PHP script that can extract specific movie titles and ratings from a large file. However, I now need to modify the script to sort the movie titles with 'XXX' at the bottom of the list. I've considered using usor ...

Retrieving JSON Arrays in PHP through an AJAX Request

Having trouble extracting data from multiple arrays in an AJAX request. Can anyone help? Here's what I'm trying to send: https://i.stack.imgur.com/4MEL4.png Executing a jQuery AJAX POST to a PHP file, but uncertain how to retrieve the data. An ...

Avoiding the use of if statements in Javascript

I've recently started learning Javascript and I'm facing an issue with my code. I want to create a functionality where clicking on an image on one page redirects you to another page and shows a specific div based on the clicked image. To achieve ...

Prevent identical values from being added repeatedly to a table while updating in real-time

Currently, I am facing an issue while running through a loop to extract values from an array. When I add a second value, it duplicates both the new and previous values in the table. For example, adding a row with value 488 works fine: <tr class="exe"& ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Using jQuery to send a GET request to the current page with specified parameters

Within my application, hosted on a PHP page, I am aiming to trigger a GET request upon selecting an option from a dropdown menu. The URL of the page is: www.mydomain.it/admin/gest-prenotazioni-piazzola.php I intend to utilize jQuery to execute this GET r ...

Switching icon images using JQuery based on state changes

I'm attempting to switch the background image of my webpage's "body" element when the user toggles between playing and pausing music icons. This is what the CSS for the "body" element looks like: body { background: url('https://s3-us-wes ...

Unable to identify the element ID for the jQuery append operation

After attempting to dynamically append a textarea to a div using jQuery, I encountered an issue. Despite the code appearing to work fine, there seems to be a problem when trying to retrieve the width of the textarea using its id, as it returns null. This s ...

Guide on making a loop inside a JSON request object

I am faced with the task of generating multiple "items" for a json request. Here is an example of a successful request: customs_info = EasyPost::CustomsInfo.create( eel_pfc: 'NOEEI 30.37(a)', customs_certify: true, custo ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

Converting php array submitted from a form using ajax

I have a form on my website that collects user input and sends it to an email address using php. The form includes a checkbox input where users can select multiple options, which are then stored in an array. However, when the form is submitted, the email r ...