简体   繁体   中英

How to return a specific part of a string in an array?

I have a table in which every row has a checkbox for selection. Every checkbox has an unique id so it can be called on by JS or Jquery.

The table consists of variable data, for one user it could have 5 rows and for another 10.

The id's are succesfully being retrieved by using: $('input[id^="incident_vga_"]')

After that I have to strip every item of the incident_vga_ part. Which also is done successfully by looping through the result by using:

$('input[id^="incident_vga_"]').each(function(){
var id = this.id;
var idNumber = id.replace(/\D+/, '');
elements.push(idNumber); 
//console.log(idNumber);
});

Now comes the problematic part, when checking the results in another loop writing every item to the console it's writing every item as a string made up by the entire array separated by comma's.

It's done by using the following code:

for (var i in elements) 
{
console.log("row " + i);
console.log(" " + elements[i]);
}

Which outputs something like this in the console:

row 21
,5728,5729,5732,5733,5724,5730,5731,5734,5735,5740,5746,5747,5748,5726,5738,5741,5742,5743,5744,5745,5739,5727,5736,5737

I wanted to check if the each() function was pushing the string into the array by using console.log(idNumber); . It is not, when writing every idNumber to the console it writes every idNumber as single. Not as a complete string divided by comma's.

Now I'm not an expert in jquery and javascript. I sort of know my way around it but this baffles me. I've researched for a good amount of time but I can't find the answer. I've tried multiple alternatives for either retrieving the id's, stripping them and pushing them into the array and for writing it to the console. Sadly every alternative I've tried results in failure or as a duplicate of the current situation.

Eventually I have to check the stripped id against an id from an array brought in through PHP (it's known on page load) to perform (or not perform) an action when a checkbox is ticked that is in a row that meets a specific condition.

Any help would be appreciated. I might have overloked something or just have been stuck in a case of tunnelvision but I can't see the right solution myself at the moment.

is this what you want?

$(function() {

    let elements = [];

    $('input[id^="incident_vga_"]').each(function(){
        let id = this.id;
        let idNumber = id.replace(/\D+/, '');
        elements.push(idNumber); 
    });


    for (let i in elements) {
      console.log('row ' + i + ': ' + elements[i]); 
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM