1

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 + '" />');
});
1
  • 1
    I find it mildly amusing that you spelled the word "variable" 2 different ways – both incorrect – in the question title :-) Commented Jan 23, 2012 at 9:59

4 Answers 4

2

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 ) );
});
Sign up to request clarification or add additional context in comments.

1 Comment

this looks like what i would have put as an answer.
2

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));

Comments

1

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();
});

Comments

0

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().

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.