Alex Rivera | Logout

Iterating through all Textareas with Javascript (jQuery)

Asked 2011-06-01T13:11:02.427
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!

Edit
Report

3 Answers

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

See a working demo

answered 2011-06-01T13:15:14.747
3

instead using id do below

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

// whatever u want
});
answered 2011-06-01T13:15:03.630
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())
    }
})
answered 2011-06-01T13:21:11.303

Your Answer