0

I'm passing an array idArray to a jQuery each function, which I'm then using to get the values. I'm trying to use the values to create a new jQuery selector.

Here's what an example idArray looks like:

Array[4]
0 : "5"
1 : "6"
2 : "8"
3 : "9"

Here's my code:

function editGigs(idArray) {
    console.log(idArray); // Produces array correctly
    $(idArray).each(function(k, v) {
        trId = "'#row" + v + "'";
        console.log(trId); // Produces '#row5'
        $(trId).find('.td.forename').css('background-color', 'black');
    });
}

I'm getting an error, as follows:

Uncaught Error: Syntax error, unrecognized expression: '#row5'

However, when I add '#row5' into the last line of the code itself as the id selector, it works...?! Something appears to be wrong in the way I'm using a value from the jQuery each function as the id selector.

5
  • 2
    Remove the single quotes -> trId = "#row" + v; Commented Feb 3, 2017 at 11:05
  • 1
    Also $(idArray) isn't a great idea as jQuery is expecting an array of DOMElements, not strings. You could use idArray.forEach(), or a simple for loop instead Commented Feb 3, 2017 at 11:05
  • Thanks @Andreas - that works... why is it necessary to remove the single quotes? Commented Feb 3, 2017 at 11:08
  • Thanks @RoryMcCrossan - that's useful. I was thinking that there might be a better way. Will try these. Commented Feb 3, 2017 at 11:09
  • 1
    Because '#row5' (with the quotes) is not a valid selector Commented Feb 3, 2017 at 11:10

1 Answer 1

1

You don't have to use single quotes '' in the selector :

trId = "'#row" + v + "'";

Should be :

trId = "#row" + v;

Since the string has already double quotes "" by default, so when you add the single ones the result is an invalid selector looks like :

$("'#rowV'")

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.