Debbie Kurth
Debbie Kurth

Reputation: 481

Dynamic JQuery object selector

I have a jquery selector used to select an object within some plugin code, created by a 3rd party. When I hardcode one search item, it works, but when I attempt to use variables in order to adjust the search, the object is not found.

The 3rd party code does not include id handles on all the CSS code. Thus it is necessary to search for the string, in this case a label and the associated value within the label.

I have searched the internet and tried a variety of samples that seem to work for other, but with no success.

The search that works is this:

var $box = $('label[for="MMDListsRecord_0_title"]');
$box.text('<?php echo $NewLabel ?>');

But when I break the search line up, in order to dynamically choose a row, the search fails. I have tried all these combinations:

var $row = 0;
var $box = 'label[for="MMDListsRecord_'+ $row +'_title"]';
$box.text('<?php echo $NewLabel ?>');
var row = 0;
var $x = 'label[for="MMDListsRecord_'+ row +'_title"]';
var $box = $(x);
$box.text('<?php echo $NewLabel ?>');
var $row = 0;
var $box = $('label[for="MMDListsRecord_'+ $row +'_title"]');
$box.text('<?php echo $NewLabel ?>');
var $row = '0';
var $box = $('label[for="MMDListsRecord_'+ $row +'_title"]');
$box.text('<?php echo $NewLabel ?>');
var $row = "0";
var $box = $('label[for="MMDListsRecord_'+ $row +'_title"]');
$box.text('<?php echo $NewLabel ?>');

Then went to trying to just search for all combination of the title, only to have the jquery search crash or fail.

var $box = $("label[for=~'title");
$box.text('<?php echo $NewLabel ?>');
 var $box = $('label[for=~"_title"]');
$box.text('<?php echo $NewLabel ?>');
var $box = $("[for~='_title'");
$box.text('<?php echo $NewLabel ?>');

All combinations fail to find the code object, except for the whole string

var $box = $('label[for="MMDListsRecord_0_title"]');

What is the secret?

Upvotes: 1

Views: 250

Answers (2)

Debbie Kurth
Debbie Kurth

Reputation: 481

Thanks to all. got it working:

$row=0;
var $box = $('label[for="MMDListsRecord_'+ $row +'_title"]');
$box.text('<?php echo $NewLabel ?>');

Upvotes: 0

Viktor Antishov
Viktor Antishov

Reputation: 41

You're defined $row variable, but used row - it's undefined. https://jsfiddle.net/s4cyqku6/

Upvotes: 2

Related Questions