开发者

Can you use jQuery to manipulate html entered into a form text area?

I'm wondering if I can use jQuery to recode HTML that's entered into a form. For example, I would like to "stri开发者_如何学Cpe" HTML table code that users manually enter into a form text area. If the textarea has an id=tablecode it does not work to do

$('textarea#tablecode tr:even').addClass('table_even');

Is there some way to use jQuery to manipulate the html that the users enter into the form box? or do I need to submit the form to the server and then use regular expressions in PHP to add my classes? Thanks.


try

var code = $('textarea#tablecode')[0].value;
var parsedHTML = $(code);

there you have a jQuery object wih the parsed HTML. Then you can manipulate it

$("tr:even", parsedHTML).addClass('table_even");

And optionally put the changes back in the textarea.

$('textarea#tablecode')[0].value = parsedHTML[0].outerHTML;


Not directly since the contents of the text area are just text..

You can however read the value of the textarea and create an in-memory representation of that (as long as it is valid html), and process that.

$('#convert').click(function(){
  var $html = $( $('#tablecode').val() ).wrapAll('<div />').parent();

    // manipulate html
  $('tr:even', $html).addClass('table_even');

    //show altered html in another textarea with id=result
    $('#result').val($html.html());
});

demo at http://jsfiddle.net/gaby/f4FuG/


You'll need to pull the text out of the textarea and create a DOM node out of it. (Then you could serialise it back into a string and put it back in the textarea, if required.)


IDs apply to individual elements. They must be unique. Try changing the id to a class, and change your # to a ..


textarea model is a plain text. So this selector $('textarea#tablecode tr:even') will simply not work.

You will need to pass your text to html parser in order to get DOM. Then modify it. Then serialize it back to HTML.

This Robust and Mature HTML Parser for PHP can be useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜