Hugolpz
Hugolpz

Reputation: 18278

JQuery: How to select content of textarea as html string & extract text from it?

(Failling JSfiddle on bottom)

Given JS such :

// Fill the textarea for testing!
$("#input").val("hello <b>2</b> and <b>3</b>");
// Get the textarea, convert to html string, find b elements, get text content:
$("#input").keyup(function () {
    $('#output').html($("#input").val()).find("b").text();
}).keyup();

Given HTML such:

<!-- INPUT: -->
<fieldset>
    <textarea id="input"></textarea>
</fieldset>

<!-- OUTPUT: -->
<b>List of text in b balises is:</b>
<div id="output">
    Here should be the list of n strings in b n balises (aka: ["2", "3"])
</div>

How to get the list of n strings within b elements ?

That currently doesn't works, see JSfiddle. Answer with JSfiddle appreciate.

Upvotes: 0

Views: 812

Answers (3)

Hugolpz
Hugolpz

Reputation: 18278

Answer:

// Fill the textarea for testing!
$("#input").val("hello <b>2</b> and <b>3</b>");

// Get the textarea, convert to html string, find b elements, get text content:
$("#input").keyup(function () {
    $('#output').html($('#input').val());
    var list = $('#output').find("b");
    $('#output').html(""); //clean up
    list.each(function( i ) {
        $("#output").append(  "Element "+i+":" + $( this ).text() +"<br />");
    });
}).keyup();

Fiddle: http://jsfiddle.net/6hCwZ/18/

Upvotes: 0

// Fill the textarea for testing!
$("#input").val("hello <b>2</b> and <b>3</b>");

// Get the textarea, convert to html string, find b elements, get text content:
$("#input").keyup(function () {
    var $el = $('<div>'+$("#input").val()+'</div>');
    var result = '';
    $.each($el.find('b'),function(){
        result += $(this).text()+' ';
    });

    $('#output').html(result);
}).keyup();

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49920

You could take the text, put it into a hidden element as HTML, which will turn it into a DOM object, which you can then navigate to the element and extract it contents.

Upvotes: 1

Related Questions