13

I would like to perform something with all my text areas, however selecting all of them with $("textarea") wont do. Here's what I am trying to do in Pseudo code:

for each textarea do
  alert(textarea.val)

In my case, I need to do a Word replacement in all of my textareas, so I thought doing it with iteration would be a lot cleaner, however I cant figure out how to do it.

Here is what I currently do, which is very tedious:

var txtcode = $("#txt_banner1").text().replace("AFFURL",producturl);
$("#txt_banner1").text(txtcode);

var txtcode = $("#txt_banner2").text().replace("AFFURL",producturl);
$("#txt_banner2").text(txtcode);

... and on and on....

Thanks!

4 Answers 4

25
$(function(){
    $("textarea").each(function(){
        this.value = this.value.replace("AFFURL",producturl);
    });
});

See a working demo

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for REGULAR FREAKING JAVASCRIPT for getting the textarea's value instead of $(this).val() or .text() nonsense.
Accepted this one because of the regular javascript, which makes for better readability. Thanks! :)
I get ReferenceError: textarea is not defined when I try to do $("textarea") from within my code. I am executing this from within my $(document).ready function, is this not correct?
9

You can use .each to iterate over all of the textarea elements and do what you need to with them via jQuery.

Live Demo

$('textarea').each(
    function(){
        alert($(this).val());
    }
);

Reference

Comments

3

instead using id do below

$("textarea").each ( function () {

// whatever u want
});

Comments

1

http://jsfiddle.net/PKenB/

//alternative 1
$(function() {
    $('textarea').each(function() {
        alert($(this).text())
    })
})

//alternative 2 only those who has specific class  
$(function() {
    $('textarea.myTextArea').each(function() {
        alert($(this).text())
    })
})

//alternative 3, handpicked textareas    
$(function() {
    var handPicked = ['#2', '.myTextArea']
    for (x = 0; x < handPicked.length; x++) {
        alert($(handPicked[x]).text())
    }
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.