user1015214
user1015214

Reputation: 3091

jquery append not working right

I have a table with a each td element containing an input tag. I wrote the following code

var elements = $('#booklist .ISBN_number');

to make an array of all of the isbn numbers contained in those input tags.

I am trying to write a jquery command to append an image to the content of those input tags. I had written

$(elements[index]).val().append("<img src = 'pics/green_checkmark.png'>");

which doesn't work. I have checked and $(element[index]).val() does have a numeric isbn value. Why can't I append to it? (I wan't to image to show up on the right of the input tag)

Upvotes: 1

Views: 212

Answers (4)

swatkins
swatkins

Reputation: 13640

Because .val() returns a string, not a jquery object. You'd have to do something like this:

$(elements[index]).val( $(elements[index]).val() + "<img src = 'pics/green_checkmark.png'>") );

However, you can't add an image inside of an input. You'd have to add it after the input, then move it over the input with css; something like:

img { margin-left: -15px; }

Upvotes: 0

Alastair Pitts
Alastair Pitts

Reputation: 19601

Assuming your HTML looks something like this:

<table id="booklist">
    <tr>
        <td>
            <input class="ISBN_number" />
        </td>
    </tr>
    <tr>
        <td>
            <input class="ISBN_number" />
        </td>
    </tr>
    ...
</table>

What you need to do is use the .after() method which will append the value after the selector.

Also, if you have a jQuery object that selects more than 1 object, any method performed on that object will apply to all the objects that selector hits.

So change your code to.

var elements = $('#booklist .ISBN_number');
elements.after("<img src = 'pics/green_checkmark.png'>");

And this will give you html ala:

<table id="booklist">
    <tr>
        <td>
            <input class="ISBN_number" /><img src="pics/green_checkmark.png">
        </td>
    </tr>
    <tr>
        <td>
            <input class="ISBN_number" /><img src="pics/green_checkmark.png">
        </td>
    </tr>
    ...
</table>

Upvotes: 0

Will
Will

Reputation: 20235

The jQuery val function returns a string of the current value of the element.

If you want to append the image after the input tag, you can use the after function.

elements.eq( index ).after( "<img src='pics/green_checkmark.png'>" );

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86892

You cannot append an image in a text input tag

You should try after() and place the image after the input.

Upvotes: 1

Related Questions