I have a textarea in a DIV that I can not modify.
I need to add an element, an input checkbox, just after the text area with javascript.
This is the code :
<div id="msgrapidosinick"><p class="msguser">My Wall</p>
<form method="post" id="messaggioajaxd" name="frm2">
<textarea class="areamsgnoava" 开发者_开发百科name="messaggio"></textarea>
<input type="hidden" value="1" name="invia" id="invia">
<input type="hidden" value="1" name="riceve" id="riceve">
<input type="hidden" value="/assyrian" name="pagina" id="pagina">
<input type="submit" value="Share" class="submsg" name="senda2" style="display: none;">
</form>
</div>
So just after the textarea I need to add an element, that is a input checkbox, when the textarea is clicked.
How do I do that?
Please help me.
Just to let you know my site loads also jQuery 1.3.2
Thank you
You can use the aptly-named after() method:
$("textarea[name=messaggio]").click(function() {
$(this).after("<input type='checkbox' name='yourCheckBoxName' />");
});
If you want to avoid creating the check box if it already exists, you can do something like:
$("textarea[name=messaggio]").click(function() {
var $this = $(this);
if (!$this.next(":checkbox").length) {
$this.after("<input type='checkbox' name='yourCheckBoxName' />");
}
});
Presuming you only want the checkbox created on the first click to the textarea, you could do something like this:
$("#messaggioajaxd textarea").click(function(){
if ($('#createdCheckbox').length==0){
$('<input />').attr('type','checkbox').attr('id','createdCheckbox').insertAfter($(this));
}
});
Example on jsfiddle
Niklas beat me to it but here is what I was going to suggest...
Demo: http://jsfiddle.net/wdm954/ppnzf/1/
$('textarea.areamsgnoava').click(function() {
if ($('input.new').length == 0) {
$(this).after('<input type="checkbox" class="new" />');
}
});
I think that some IE version will not like that you add a field dynamically. If you can add an element to the form, may be you could change the form totally, and inject it as a new form instead, using div.innerHTML
or using the DOM.
And add the checkbox in the original HTML as hidden, and show it if the textarea is clicked.
eg:
<div id="msgrapidosinick"><p class="msguser">My Wall</p>
<form method="post" id="messaggioajaxd" name="frm2">
<textarea class="areamsgnoava" name="messaggio"></textarea>
<input type="checkbox" name="checkBox" id="checkBox" style="display:none">
<input type="hidden" value="1" name="invia" id="invia">
<input type="hidden" value="1" name="riceve" id="riceve">
<input type="hidden" value="/assyrian" name="pagina" id="pagina">
<input type="submit" value="Share" class="submsg" name="senda2" style="display: none;">
</form>
</div>
Then if you have the reference of the textarea
DOM node:
textarea.onfocus = function(ev){
var ta = ev.target || ev.srcElement;
ta.form.checkBox.removeAttribute('style');
}
Or using jQuery and focus
.
精彩评论