derek8
derek8

Reputation: 269

Passing numeric variable in jQuery

Why can't I pass the num variable to this function like so:

    function getColumnData(num) {
    var colVals = $('#newtable td:nth-child(num)').map(function(){
       return $(this).text();
    }).get();
    alert(colVals);
    }

Is there an easy way around this?

Thanks.

Upvotes: 1

Views: 789

Answers (3)

edgarpetrauskas
edgarpetrauskas

Reputation: 401

try on line 2

var colVals = $('#newtable td:nth-child(' + num + ')').map(function(){

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45058

Because your jQuery selector is a string, you need to 'build' it using concatenation, like so:

$('#newtable td:nth-child(' + num + ')')

Otherwise num is just some characters in the string literal.

Upvotes: 3

James Allardice
James Allardice

Reputation: 166031

You need to concatenate the value of num with the selector string:

var colVals = $('#newtable td:nth-child(' + num + ')').map(function() {
    //Do stuff
});

Currently you just have a string literal "#newtable td:nth-child(num)", instead of something that makes sense to the selector engine, such as "#newtable td:nth-child(2)".

Upvotes: 3

Related Questions