John Magnolia
John Magnolia

Reputation: 16793

How can I insert a variable into a variable string?

I have this code which I need to set a unique title:

var tmpImg = '<img src="/admin/icons/cross.png" title="' + title + '" />';

$(this).find("tr td input").each(function(){
    title = $(this).attr("value");
    $(this).hide().before(tmpImg);
});

What I want to happen, is that each time the each iterates over the <input>, it updates the title value in the tmpImg string. I know I could separate the img HTML like below, although I think this would get messy when I need to reuse the image later down the script.

var tmpImg = '<img src="/admin/icons/cross.png" title="';

$(this).find("tr td input").each(function(){
    title = $(this).attr("value");
    $(this).hide().before(tmpImg + title + '" />');
});

Upvotes: 1

Views: 263

Answers (4)

Andy E
Andy E

Reputation: 344575

This is how I'd do it, for what it's worth:

$(this).find("tr td input").each(function(){
    $('<img/>', {
        src: "/admin/icons/cross.png",
        title: this.value
    }).insertBefore(this).next().hide();
});

Upvotes: 1

Jordan Running
Jordan Running

Reputation: 106027

These string replacement solutions are nuts. Just make a copy of the element and set the attribute on it directly.

var tmpImg = $( '<img src="/admin/icons/cross.png" />' );

$(this).find( "tr td input" ).each(function() {   
  $(this).hide().before( tmpImg.clone().attr( 'title', this.value ) );
});

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074295

You can put some kind of placeholder token in the string, then use replace:

var TITLE_TOKEN = '%%TITLE%%';
var tmpImg = '<img src="/admin/icons/cross.png" title="' + TITLE_TOKEN + '" />';

$(this).find("tr td input").each(function(){
    $(this).hide().before(tmpImg.replace(TITLE_TOKEN, $(this).attr("value")));
});

Side note: $(this).attr('value') is usually better written this.value or $(this).val().

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

Change the variable to sort of template:

var tmpImg = '<img src="/admin/icons/cross.png" title="$title" />';

Then replace it with the input value:

$(this).hide().before($(tmpImg.replace("$title", this.value)));

The above has minimal changes to original code, the better jQuery way though is this:

$(this).hide().before($("<img />").attr("src", "/admin/icons/cross.png").attr("title", this.value));

Upvotes: 2

Related Questions