Reputation: 67
I have an input field and enter a XHTML code in it it returns me the output the modified code, for example I digit in the following input:
<label> Text <label>
<p> RESULT TEXT </p>
<label> Text <label>
<p> RESULT TEXT </p>
<label> Text <label>
<p> RESULT TEXT </p>
<label> Text <label>
<p> RESULT TEXT </p>
I need to add the following word "Box" inside the tag <p>
and leave only the first letter in uppercase and the rest in lowercase. Getting your bottom line this way:
<label> Text <label>
<p> Result text box </p>
<label> Text <label>
<p> Result text box </p>
<label> Text <label>
<p> Result text box </p>
<label> Text <label>
<p> Result text box </p>
I'm trying to do this using the following code:
var code = $('textarea[name=message]').val();
/* prevent the creation of multiple output-blocks if someone clicks on the submit-button more than once */
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
code = code.find(p).text("box");
code = code..replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
$('#output').val(code);
Upvotes: 1
Views: 267
Reputation: 195992
Some issues:
label
tags are wrongly closed (you forgot the /
)code
variable is a string and not a jquery object so you cannot perform find
on it.code..replace
(double dot).find(p)
, p
is not defined. What you want is to pass a string so you must wrap it in quotes. .find('p')
Fixing all those issues you end with something like this
var code = $('textarea[name=message]').val();
/* prevent the creation of multiple output-blocks if someone clicks on the submit-button more than once */
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
// create a jquery object out of the code
var livehtml = $('<div/>', {
html: code
});
// find the <p> elements and alter their html
livehtml.find('p').append("box").html(function (idx, currentHtml) {
return currentHtml.charAt(0).toUpperCase() + currentHtml.substr(1).toLowerCase();
});
$('#output').val(livehtml.html());
Demo at http://jsfiddle.net/UpYgA/
Upvotes: 2