I have a problem with the use of the javascript removeChild function.
Here's my script:
////function to add element by ID////
var i=1;
$("#buttonAdd").live('click',function() {
$("#list1 li:last-child").parent().append('<li>'+
'<label for=njajal[]>njajal'+
'<textarea class="tinymce" name="njajal[]" id="aaa'+i+'"></textarea>'+
'<span><a class="delIt" id="'+i+'"><b>Hapus</a></span></label>'+
'</li>');
tinyMCE.execCommand('mceAddControl', false, 'aaa'+i);
console.log('add '+i);
i++;
});
////Function to delete element by ID/////
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('njajal');
parentEle.removeChild(ele);
}
What is the problem?
Here's the HTML code:
<div id="form">
<form method="post" action="">
<fieldset>
<ol id="list1">
<li>
<label for="njajal[]">njajal
<textarea name="njajal[]" class="tinymce" ></textarea>
</label>
</li>
</ol>
<div id="addOpt">
<a id="buttonAdd" class="bt"><b>Tambah</a>
</div>
</fieldset>
</form>
</div>
Screnshot:
You use jQuery in your first function, so the easiest way to remove that element would be with jQuery:
$('#myElementID').remove();
Here's how you can accomplish the same thing with plain javascript:
var myElement = document.getElementById('myElementID');
myElement.parentNode.removeChild(myElement);
EDIT:
To make things simpler read > as "child of:
From what I can tell the problem is thattextarea > label > li > ol. The only element actually having an id is <ol> so to remove the label (as you show in the image) change delIt to:
function deleteLabelTextArea(){
var elementRemove = document.getElementById("list1").firstElementChild.firstElementChild;
elementRemove.parentNode.removeChild(elementRemove);
}
Old Answer:
As we cannot see the HTML I am not certain what the problem is other than as Marc B has mentioned that 'njajal' is not the parent of eleID. To fix that I would recommend:
function delIt(eleId){
var ele = document.getElementById(eleId);
ele.parentNode.removeChild(ele);
}
The solutions presented till now won't work because tinymce IS NOT the textarea!!
Tinymce gets initialized using the content of a specified html-element - a textarea in this case. After initialization an iframe with a contenteditable body is created where users may edit html content.
In order to get rid of the tinymce editor you need to shut it down first:
tinymce.execCommand('mceRemoveControl', false, 'content'); // your textarea got no id, then tinymce uses 'content' as default editor id
Second, you may remove the initial html elements like label and textarea as the other solutions to your question show.
I just wonder why you have have two tinymce editors on your page?
For me it looks like you might prefer to initialize just one them instead of removing the second one afterwards.
Related
I am not sure if what I am trying to do is possible at all. Ok, so I have successfully created a "drop your images" feature for a site I am working on. This is how it looks (looks will improve).
Now, I have this textbox where I can edit the caption but I am trying to make it so that when I type the text I am able to edit parts of the hidden input box. For, example, the enter caption would edit the Caption part inside the hidden input box.
This is how it looks:
<input value="meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"","DateStamp":"","Privacy":""}">
This is the code I have used
<div class="addtextTopic">
<div class="leimage">
<img src="funnylookingcar.png">
<input class="tosend" value="meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"","DateStamp":"","Privacy":""}">
</div>
<textarea class="lecaptine" placeholder="Enter A Caption"></textarea>
</div>
$(document).ready(function() {
$(".addtextTopic .lecaptine").onchange(function() {
var $cap = $(this)
$(".tosend").val($cap);
});
});
Now, the code above doesn't work, and for some reason, I am beginning to think that if it works, it will replace the entire value, instead of the caption part.
Also, am I on the right direction? is this even possible?
Here's a possible solution.
http://jsfiddle.net/o2gxgz9r/3167/
$(document).ready(function() {
$(".addtextTopic .lecaptine").keyup(function() {
var metaDefault = '"meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"{{CAPTION}}","DateStamp":"","Privacy":""}';
var $cap = $(this).val();
$(".tosend").val(metaDefault.replace('{{CAPTION}}', $cap));
});
});
A few things wrong with your original code.
The change event will only fire when the textarea is blurred, not on keystroke. I changed this to keyup
I created a default string of metaDefault with a magic string of {{CAPTION}} so .replace() would know what to replace.
$cap needs to be the .val() of $(this).
First change your Onchange method to change method and copy value of .lecaptline to .tosend use $cap.val() please find below fiddle for more info
$(document).ready(function() {
$(".addtextTopic .lecaptine").change(function() {
debugger;
var $cap = $(this);
$(".tosend").val($cap.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addtextTopic">
<div class="leimage">
<img src="funnylookingcar.png">
<input class="tosend" value="meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"","DateStamp":"","Privacy":""}">
</div>
<textarea class="lecaptine" placeholder="Enter A Caption"></textarea>
</div>
how about change like this?
$('.addtextTopic .lecaptine').bind('input propertychange', function({
});
jQuery:
$('.clickhere').click(function(e){
e.preventDefault();
$(this).closest('.row').children('.abc').hide(); // working
$(this).closest('.row').children('.abc').children('input').value = ''; // not working
$(this).closest('.bookingrow').children('.addressbox').children('input').value(''); // alternative - not working
});
html
<div class="row">
<div class='abc'>
<input type='text' class='unknown' />
</div>
<div class="clickhere">hide</div>
</div>
my target is if i click the "clickhere" class, content under "abc" class will hide and whatever content added by customer on those input box, they will be clear.
same html used multiple time on the same form. that's why using "$(this)".
any solution? what i am doing wrong?
Thanks in advance.
You need to use .val() to set the value, jQuery methods normally will return a jQuery object not a dom element reference so you would not have a properly called .value.
$(this).closest('.row').find('.abc input').val('');
So
$('.clickhere').click(function (e) {
e.preventDefault();
//cache the value of .row since it is used multiple times
var $row = $(this).closest('.row');
$row.children('.abc').hide(); // working
$row.find('.abc input').val('');
});
I thought for long how to define the question but i couldn't, i need to explain the code.
I want to make a simple organizer in JavaScript. You enter the task and click on the button "add to the list" and a script makes a checkbox with paragraph that contains the task's text. The second part is the disabling the checkbox, and striking through that tasks text when you click on it. I tried to do that by giving every checkbox i create a function (destroyIt() that gets element by id and than disables it, but it works only for the last checkbox added to the page. I am looking at this code for long time and i can't see what is wrong. Please help. Here is my code:
<html>
<head>
<style id="stil">
.over{
text-decoration:line-through;
}
</style>
<script type="text/javascript">
var numberOfTasks=1;
function insertNew(){
tekst = document.getElementById("zadatak").value;
if(tekst.length>0){
var idEl= "check"+numberOfTasks;
document.getElementById("ispis").innerHTML+="<input type='checkbox' id='check"+numberOfTasks+"'> "+"<span class='"+idEl+"'>"+tekst+"</span> <br/>";
document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };
numberOfTasks++;
}
}
function destroyIt(idEl){
document.getElementById(idEl).disabled=true;
document.getElementById("stil").innerHTML+= "."+idEl+"{text-decoration:line-through;}";
alert(idEl+"{text-decoration:line-through;}");
}
</script>
</head>
<body>
Tasks for: <span id="date"> </span>
<script>
var date= new Date();
document.getElementById("date").innerHTML= ""+ date.getDay() +"." +date.getMonth() +"." +date.getFullYear();
</script>
<br/> <br/>
New task: <input type="text" id="zadatak"> <button onclick="insertNew()"> add to the list </button>
<button onclick="provera()">Provera</button>
<p id="ispis"> </p>
</body>
The problem is that when you do .innerHTML += "...", it destroys the existing nodes and their event handlers, and replaces them with new, clean nodes. For this and other reasons, you should almost never use += after .innerHTML.
A better way to insert new content from HTML markup is to use .insertAdjacentHTML() instead. The first argument describes the position relative to the element on which it was invoked, and the second argument is the new content.
So your code with .insertAdjacentHTML() would look like this:
function insertNew(){
tekst = document.getElementById("zadatak").value;
if(tekst.length>0){
var idEl= "check"+numberOfTasks;
document.getElementById("ispis")
.insertAdjacentHTML("beforeEnd", "<input type='checkbox' id='check"+numberOfTasks+"'> "+"<span class='"+idEl+"'>"+tekst+"</span> <br/>");
document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };
numberOfTasks++;
}
}
Furthermore, you can modify the destroyIt function to operate on its this value, which will give you the input element that has the handler. You can then use its .id to get the class of the span, or you can just traverse to the next element.
Also, you shouldn't modify the style sheet to hide the element. Just add a class or a direct style property.
So in the above function, this:
document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };
becomes this:
document.getElementById(idEl).onclick= destroyIt;
And then the destroyIt function becomes this:
function destroyIt(){
var span = this.nextElementSibling;
this.disabled=true;
span.style.textDecoration = "line-through";
}
The .nextElementSibling will need to be patched in IE8, but this is just for simple demonstration.
HTML:
<div class="my_1"></div>
<div class="my_big">
<div class="small" id="id_1"></div>
<div class="small" id="id_2"></div>
<div class="small" id="id_3"></div>
<div class="small" id="id_4"></div>
</div>
javascript:
var css_scope=$(".my_big");
var next_div=$(".my_1").nextAll('.small',css_scope).first();
console.log(" \n next div = "+ next_div.attr('id'));
console shows undefined. But if I exclude the my_big div from html and define var next_div in javascript as follows:
var next_div=$(".my_1").nextAll('.small').first();,
expected output is obtained.
How to make nextAll() work with the mentioned css scoping ?
.nextAll is used to find all the next siblings, you should find the .small from the result of nextAll.
var next_div=$(".my_1").nextAll('.my_big').find('.small').first();
You cannot get to .small from my_1 using nextAll() since they are not siblings. You can get to it using the following selector.
// Get the first element matching ".small" inside an element matching ".my_big"
// that comes immediately after an element matching ".my_1"
var next_div = $('.my_1 + .my_big > .small:first');
Check this demo: http://jsfiddle.net/q6XKR/
If you want to access the first element in my_big div, there's no need to bring my_1 into the scene.
var next_div = $('.my_big').find('.small').first();
console.log(" \n next div = "+ next_div.attr('id'));
Hope it clarifies you somewhat about traversing elements in jQuery.
I am trying to use a code snippet I found online to implement charcount. It works for one single text area. I have multiple text areas with different count limits. Here is the code that works for one single form.
Javascript:
function countChar(val,count,focus){
var len = val.value.length;
var lim=count;
var focussed=focus;
if (len >= lim) {
$('#charNum').text(lim - len);
$('#charNum').addClass('exceeded');
/* val.value = val.value.substring(0, lim);*/
}else {
if(focussed===0){
$('#charNum').html('<a> </a>');
}
else {
$('#charNum').text(lim - len);
$('#charNum').removeClass('exceeded');
}
}
};
HTML:
<div id='charNum' class='counter'> </div>
<textarea id='description' name='description' onkeyup=\"countChar(this,200,1)\" onblur=\"countChar(this,200,0)\" rows='10' cols='20'></textarea>
If I have two text areas, how can I modify this code to work ? I know how to get the id of the div in the script, But I dont know how to correctly update the counter div, say #charNum1, and #charNum2. Appreciate some hints. Thanks
EDIT:
I was thinking, I can name the counter div as "Charnum+divName" if that helps
If you attach your event handler(s) with jQuery you can use this within the handler to refer to whichever element the event was triggered on, thus avoiding having to hardcode element ids inside your function.
I'd suggest adding an attribute with the max chars allowed and removing the inline event handlers:
<div id='charNum' class='counter'> </div>
<textarea id='description' name='description' data-maxChars="200" rows='10' cols='20'></textarea>
<div id='charNum2' class='counter'> </div>
<textarea id='otherfield' name='otherfield' data-maxChars="400" rows='10' cols='20'></textarea>
Then:
$(document).ready(function() {
$("textarea[data-maxChars]").on("keyup blur", function(e) {
var $this = $(this),
$counter = $this.prev(),
len = $this.val().length,
maxChars = +$this.attr("data-maxChars");
$counter.text(maxChars - len).toggleClass("exceeded", len > maxChars);
});
});
Demo: http://jsfiddle.net/nnnnnn/GTyW3/
If each textarea is going to have it's own div, you can just add an extra parameter to the countChar function which would be the name of the div. So you'd have something like:
function countChar(val,count,focus, charCountDiv)
then, instead of hardcoding it in the function, the jQuery would be:
$(charCountDiv)
That should do what I think you are looking to do.