Warface
Warface

Reputation: 5119

Return the content from textarea with element inside

I would like to make a script that would extract me everything within a defined element. In this exemple it's the <u> element.

HTML

<textarea cols="75" rows="25" id="textShit"><u>sd</u></textarea><br>
    <input type="submit" name="submit" id="submit"/>
    <div id="res"></div>

JS

$(function(){
    $('#submit').on('click',function(){
        $('textarea:contains("u")').each(function() {
            //$('#res').html($(this).val()+'<br>');
            alert($(this).val());
        })
    });
});

I would like when I hit submit, in the <div class="res"> it returns what's inside every <u>.

How to achieve this ?

http://jsfiddle.net/warface/Ewve8/

Upvotes: 1

Views: 63

Answers (2)

Ram
Ram

Reputation: 144729

$(function () {
    $('#submit').on('click', function () {
        var val = $.trim( $('textarea').val() );
        var text = $('<div/>').html(val).find('u').text();
        // console.log(text);
    })
});

http://jsfiddle.net/Ewve8/1/

Update: You can use map method and join the returned array's elements:

$('#submit').on('click', function () {
    var val = $.trim( $('textarea').val() ),
        text = $('<div/>').html(val).find('u').map(function(){
            return $(this).text();
        }).get();

    $('.res').html( text.join('<br>') ); 
})

Upvotes: 2

Jeff B
Jeff B

Reputation: 30099

You are close. For one thing, you aren't including the jQuery library in your fiddle.

Just load your textare content into a jQuery object and it will be parsed. Then you can use .filter('u') to get the content you want:

var html = $($(this).val());
$('#res').html(html.filter('u').html());

Demo: http://jsfiddle.net/QhsDY/

The one "gotcha" is that .filter() will only return top-level elements, so if the <u> is nested it won't work. The fix is to use .find(), but the trick there is that .find() won't look at top-level elements. So, wrap the contents in a div and then use .find():

var html = $('<div/>').html($(this).val());
$('#res').html(html.find('u').html());

Demo: http://jsfiddle.net/QhsDY/1/

As for multiple <u> elements, use .each():

var html = $('<div/>').html($(this).val());

html.find('u').each(function() {
    $('#res').append($(this).html()+'<br>');
});

Demo: http://jsfiddle.net/QhsDY/2/

Upvotes: 0

Related Questions