Append a SPAN to all input type="text" fields

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Append a SPAN to all input type="text" fields

Post by icesolid »

Is there a way to onload, append a span tag to to the end of all input fields that are equal to type text.

ex: <input type="text"><span></span>

All text inputs will have that span tag added to the end of it on page load.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Append a SPAN to all input type="text" fields

Post by Darhazer »

It's really easy with a JavaScript framework like jQuery:

Code: Select all

 
$(document).ready(function(){
    $('input[type="text"]').each(function(){
        $(this).append('<span> ...</span>');
    });
});
 
code not tested ;)

It's possible with pure javascript of course, you can get all input elements via document.getElementsByTagName() and then in a loop check their type and append the span element.
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Re: Append a SPAN to all input type="text" fields

Post by icesolid »

I do run jQuery and love it. However that does not work with it?
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Re: Append a SPAN to all input type="text" fields

Post by daedalus__ »

he said he didn't test the code. it may need adjustments
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Append a SPAN to all input type="text" fields

Post by Darhazer »

icesolid wrote:I do run jQuery and love it. However that does not work with it?
Well, the code above produces invalid HTML - <input type="text"><span/></input>
The correct code, and this time it's tested, is:

Code: Select all

$(document).ready(function(){
     $('input[type="text"]').each(function(){
         $(this).after('<span> ...</span>');
     });
 });
Post Reply