Retrieve all input elements starting with the name "myname" and loop through each of them using the Exit function

Having a strange issue while trying to exit the JavaScript code.

This particular code involves an array of input elements.

Whenever the "if" statement triggers and the script should return true or false, an unexpected alert('something') pops up.

The script then carries on its execution.

Uncertain if the "..each" loop is still being executed. Any thoughts?

The objective is to break out of the .each loop and terminate the entire script.

If all checkboxes are marked as true, display the alert code located outside the ...each(function()...

<input type="checkbox" id="a" name="test[]" onclick="myfunction('a');" />
<input type="checkbox" id="b" name="test[]" onclick="myfunction('b');" />
<input type="checkbox" id="c" name="test[]" onclick="myfunction('c');" />

and this is the script snippet...

<script>
function myfunction(instuff) {
    $('input[name^="test"]').each(function() {
        if ($(this).prop('checked')  == false) {
            //...execute code...
            return true; //return false; has similar behavior.
        }
    })
    //...execute additional code...
    alert('something');
}
</script>

Answer №1

Returning false from the callback function will cause the .each() loop to stop. However, the execution of the remaining part of myfunction() will continue.

If you desire to halt the rest of the function, you can set a variable that you assess after the loop.

function myfunction(input) {
  let end = false;
  $('input[name^="test"]').each(function() {
      if (!$(this).prop('checked')) {
        end = true;
        return false;
      }
    } // corrected the code error
  )
  if (end) {
    return;
  }
  //...execute other code...
  alert('something');
}

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

Pug conditional elements not styling with CSS

Currently immersed in the world of Pug, node.js, and express as I build a web application. Facing hurdles when trying to style elements within Pug conditionals using CSS. For instance, consider this Pug snippet: div(id='outside') if authoris ...

Resolving the active tab problem within Angular 2 tab components

Can anyone assist in resolving the active tab problem within an angular 2 application? Check out the Plunker link I am using JSON data to load tabs and their respective information. The JSON format is quite complex, but I have simplified it here for cla ...

Determining the optimal times to utilize traditional loops instead of array helpers

After writing in Javascript for some time, I've become quite comfortable with using array helpers. However, there have been moments where traditional for loops seem more practical and easier to work with compared to array helpers. Can you provide me w ...

The Google map shifts beyond the perceived limits of the world

Is anyone else encountering an issue with Google Maps where you can now pan beyond the poles? It used to stop at the poles before, correct? The website I'm currently working on runs a location-based query on our server every time a user pans or zooms ...

Remove httpOnly cookies in Express

Can browser cookies with the attribute HttpOnly:true be deleted? Here is a snippet of my login endpoint: async login(@Ip() ipAddress, @Request() req, @Res() res: Response) { const auth = await this.basicAuthService.login(req.user, ipAddress); ...

Javascript issue: SyntaxError - A numerical value is required after the decimal point

I am currently in the process of setting up an HTML form to trigger an AJAX update when a user exits a field. My current attempt is focusing on one table cell and it looks like this: <td><input type="text" class="form-control" id="firstName" name ...

Using Vue.js to Authenticate Users with JWT Tokens Sent in Registration Emails

Hey everyone, I could really use some assistance with JWT tokens. I created a registration form using Vue.js and sent the data to the database using axios. Now, I need help figuring out how to save the token I receive in the confirmation email so that I ca ...

The POST request functions smoothly in Postman, however, encounters an error when executed in node.js

Just recently I began learning about node.js and attempted to send a post request to an external server, specifically Oracle Commmerce Cloud, in order to export some data. Check out this screenshot of the request body from Postman: View Request Body In Pos ...

Handling invalid JSON data using JavaScript

Looking to extract data from this URL using Javascript. Here is a sample of the JSON content: {"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]} Most tutori ...

Is it possible to have the detailsview checkbox automatically checked when inserting a new record?

When working with the DetailsView, specifically in its DefaultMode: insert, I encountered an issue regarding setting the default status of a checkbox. My aim is to have the checkbox checked by default, but still allow the user to change it to unchecked. Th ...

The fullCalendar plugin fails to display properly when placed within a tab created using Bootstrap

My current challenge involves integrating fullCalendar into a Bootstrap tab. It works perfectly when placed in the active tab (usually the first tab), however, when I move it to another tab that is not active, the calendar renders incorrectly upon page loa ...

Harness the power of JavaScript to generate a dynamic overlay with a see-through image that can be expanded

Within different sections of my website, we display banner ads that are loaded in real-time from third-party sources and come in various sizes. I'm interested in adding a transparent overlay image to each ad which would allow me to trigger a click ev ...

Transmitting arrays containing alphanumeric indexed names via ajax requests

I am facing a challenge in passing an array through a jQuery Ajax call. My requirement is to assign descriptive indexes to the array elements, for example, item["sku"] = 'abc'. When I create the following array: item[1] = "abc"; ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Incorporating code execution during promise completion

I'm currently working on an express application that involves a generator function which takes approximately 5 minutes to process a large amount of data. Unfortunately, I am unable to optimize this function any further. Express has a built-in ti ...

Is there someone who can explain to me the process behind this?

(function(ng, app){ app = angular.module('app', []); app.config(function($provide) { $provide.constant('town', 'Burlington'); }); app.constant('name', 'Rob F.'); app.controlle ...

A step-by-step guide on editing the rerender item using React hooks

Looking to make modifications to my rerendered item for better clarification, allowing me to easily identify the changes made. Below is the array code: const [savedAccounts, setsavedAccounts] = 0: {nick: "xaxa", pass: "215151", uid: "1123151", gallery: [] ...

Rotating an object in Three.js along the radius of a sphere

I want to position an object at the end of a sphere's radius based on its coordinates (x, y, z). In traditional mathematical formulas for the coordinates of a point on a sphere, we use: var x = radius * Math.cos(phi) * Math.cos(theta); var y = radiu ...

Automatically install modules during the execution of the Node Webkit build process

After developing a Node Webkit application, I used NW-Builder to generate the run files. The app's size ended up being quite large at 200MB due to the numerous modules utilized. My question is whether it is feasible to create an installer that will f ...

"Endless loop error in Three.js causing a system crash

I'm currently in the process of developing a library that consists of 'letter' functions responsible for generating letters in vertex coordinates. The main objective here is to allow users to create words or sentences using an interactive Po ...