How to select a div and delete the selected div using javascript - javascript

I had like to create an CRUD operation. I can able to create an DIV, Save the content to the Div, I'm unable to delete the DIV. I need to delete the selected DIV which i has created. I stuck how to select the DIV and delete the selected DIV.
Note: Should use only plain javaScript only.
Problem:
Need to delete that highlighted Div.
Please refer my below try code
<html>
<head>
<script>
var addid = 0;
function createJob() {
var jobList = document.getElementById("jobList");
if(document.getElementById('jobitem_' + (addid))) {
if((document.getElementById('jobitem_' + (addid)).textContent) == "") {
}else{
addid++;
jobNameCreation(jobList,addid);
}
}
if(addid == 0){
addid++;
jobNameCreation(jobList,addid);
}
}
function saveJob() {
var text_id = 'jobitem_' + addid;
var mainDiv = document.getElementById(text_id);
if(mainDiv.children[0].value == ""){
alert("please enter job name");
}else{
mainDiv.textContent =mainDiv.children[0].value;
}
}
function deleteJob() {
/*var t = '';
if(window.getSelection){
alert("1");
t = window.getSelection();
}else if(document.getSelection){
alert("2");
t = document.getSelection();
}else if(document.selection){
alert("3");
t = document.selection.createRange().text;
}
alert(t);
*/
}
function selectText(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
}
}
function jobNameCreation(jobList,addid){
var text = document.createElement('div');
text.id = 'jobitem_' + addid;
text.innerHTML = "<input type='text' value='' style='padding:5px; width: 185px;' />";
text.onclick = function (e) {
selectText(text.id);
};
jobList.appendChild(text);
}
</script>
</head>
<body>
<button type="button" onclick="createJob();"> Create </button>
<button type="button" onclick="saveJob();"> Save </button>
<button type="button" onclick="deleteJob();"> Delete </button>
<br>
<div id="jobListContainer">
<div id="jobList">
</div>
</div>
</body>
</html>
Please help me on this. Thanks

One solution is that when your function selectText(containerid) is called store your containerid into global variable and based on that id you will remove your selected div in deleteJob() function which is call on Delete button click.
var addid = 0;
var selectedId = '';
function selectText(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
}
selectedId = containerid;
}
function deleteJob() {
document.getElementById(selectedId).remove();
}

You can try the remove() function
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
// or
elem.remove();

Guess what you are looking for is anchorNode
Selection.anchorNode
Returns the node in which the selection begins.
-- https://developer.mozilla.org/en-US/docs/Web/API/Selection.anchorNode
… and the dynamically created ‘job'’ divs should be valid for the anchorNode to fetch them. So, use the below code to create and delete them — http://jsfiddle.net/uMhXM/2/
document.onLoad = function () {
jobListContainer = document.getElementById('jobListContainer');
jobList = document.getElementById('jobList');
}
function createJob() {
//Create an INPUT to get user input
var input = document.getElementById('input');
if (input === undefined || input === null) {
input = document.createElement('input');
input.type = 'text';
input.id = 'input';
}
//Add the created INPUT to 'jobListContainer'
jobListContainer.appendChild(input);
}
function saveJob() {
var input = document.getElementById('input');
if (input !== undefined && input !== null) {
if (input.value !== "") {
//Create the 'job' DIV enclosing INPUT value
var job = document.createElement('div');
job.setAttribute("id", "job_" +jobList.children.length);
job.textContent=input.value
//Add the created 'job' DIV to 'jobList'
jobList.appendChild(job);
//Remove the INPUT
input.remove();
} else {
alert("Please Enter Job");
}
}
}
function deleteJob(){
window.getSelection().anchorNode.remove();
}

Related

Replace selected HTML only in a specific div

I want to select the HTML of whatever the user selects in a contenteditable div. I found some code to retrieve the HTML of the selection, but it's not limited to just the div.
What I want to do is copy the selected HTML, wrap tags around it, and then replace the selection with it. So, 'test' would become 'test' for instance.
<div contenteditable="true" class="body" id="bodydiv"></div>
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
}
HI for getting content(text) inside a selected div I have create a little code you can check it out if it works for you :
$(document).ready(function(){
$(document).bind('mouseup', function(){
var content = getSelected();
content = "<b>"+content+"</b>";
$('#selected').html(content);
});
});
function getSelected(){
var t;
if(window.getSelection){
t = window.getSelection();
var start = t.focusOffset;
var end = t.baseOffset;
t = t.anchorNode.data;
t = t.slice(start, end);
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
And
<div id="selected"></div>
Hope this helps.

Javascript: How to implement the "enter/return key" to save a value?

Sorry, I am not really good with JS.
The code is essentially the user double clicks on the text, textbox appears, changes text, and saves a new value. However, I want the user to be able to also click enter to save the new value.
In addition, if possible, to have a dedicated "Save" button to save the new value and "discard" to keep the old value.
Also, if I double click many times, the text appears as "(input type="text")". Is there a way to remove that?
Please help if you can.
The HTML + JS code
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var elements = getElementsByClassName('text-edit', '*', document);
for(var i = 0; i < elements.length; i++) {
elements[i].ondblclick = function() {
this.setAttribute('oldText', this.innerHTML); // not actually required. I use this just in case you want to cancel and set the original text back.
var textBox = document.createElement('INPUT');
textBox.setAttribute('type', 'text');
textBox.value = this.innerHTML;
textBox.onblur = function() {
var newValue = this.value;
this.parentNode.innerHTML = newValue;
}
this.innerHTML = '';
this.appendChild(textBox);
}
}(i);
}
function getElementsByClassName(className, tag, elm) {
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i = 0; i < length; i++) {
current = elements[i];
if(testClass.test(current.className)) {
returnElements.push(current);
}
}
return returnElements;
}
</script>
</head>
<div><span class="text-edit">Some text</span></div>
</html>
The snippet below allows you to modify the value of a textbox using save button or enter key and discarding any changes using cancel button.
<!-- HTML -->
<h1 id="editable">Lorem Ipsum</h1>
// JavaScript
window.onload = function(){
var h1 = document.getElementById('editable');
h1.onclick = function(){
var old = this;
var input = document.createElement("INPUT");
input.type = "text";
input.value = this.innerHTML;
input.onkeyup = function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
save.parentNode.removeChild(save);
cancel.parentNode.removeChild(cancel);
}
};
this.parentNode.replaceChild(input, this);
var save = document.createElement("INPUT");
save.type = "button";
save.value = "Save";
(function(old, input){
save.onclick = function(){
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
cancel.parentNode.removeChild(cancel);
};
})(old, input);
input.parentNode.insertBefore(save, input.nextSibling);
var cancel = document.createElement("INPUT");
cancel.type = "button";
cancel.value = "Cancel";
(function(old, input){
cancel.onclick = function(){
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
save.parentNode.removeChild(save);
};
})(old, input);
input.parentNode.insertBefore(cancel, input.nextSibling);
};
};
Working jsBin

how to combine two vars in javascript?

i am trying to create dynamic textboxes. The textbox should be created only if the previous textbox is non-empty. So far i have done this
<!DOCTYPE html>
<html>
<head>
<script>
var i=0;
function myFunction()
{
var box = document.createElement("input");
box.type = "text";
var str=box+i;
if(i==0)
{
document.body.appendChild(box);
}
else if(document.getElementById('str').value!=0)
{
document.body.appendChild(box);
}
i++;
}
</script>
</head>
<body>
<input type="button" id="button" onclick="myFunction()" value="Show box" />
</body>
</html>
but str is not recognised as element id. Any help will be appreciated.
var i = 0;
function myFunction() {
var lastInput = document.getElementById('box' + i);
if (!lastInput) {
// always put first input
document.body.appendChild(createInput(0));
} else if (lastInput.value != 0) {
// append another one only if previous input content is non-null
i++;
document.body.appendChild(createInput(i));
}
}
function createInput(i) {
var box = document.createElement("input");
box.type = 'text';
box.id = 'box' + i;
box.value = 0;
return box;
}
Your wrongs:
str = 'box' + i;
Forget to assign box.id = str
Use getElementById(str) instead of getElementById('str')

Alerting the selection from a textarea in CKEDITOR

i am trying to alert the selection that i choose from the textarea in CKEDITOR.
when i run, just "No text is selected." comes out.
i want to see the alert "The current selection is: "+ selection.
i think i need to change here var textarea = document.getElementById('editor1');
could anyone help me with the problem??
setup:
function ()
{
var selection = "";
var textarea = document.getElementById('editor1');
if ('selectionStart' in textarea)
{
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd)
{
selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
}
}
else
{
// Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement();
if (rangeParent === textarea)
{
selection = textRange.text;
}
}
if (selection == "")
{
alert("No text is selected.");
}
else
{
alert("The current selection is: " + selection);
}
}
To obtain the selection use the following code:
CKEDITOR.instances.youEditorInstance.getSelection().getSelectedText();
This method however returns text only (no HTML markup).
To save HTML markup, you can try something like this:
var range = CKEDITOR.instances.editor1.getSelection().getRanges()[ 0 ];
var rangeClone = range.clone();
range.collapse();
var el1 = range.getCommonAncestor( true, true );
range.splitElement( el1 );
rangeClone.collapse( true ); // to beginning
var el2 = rangeClone.getCommonAncestor( true, true );
rangeClone.splitElement( el2 );
var html = '';
var newRange = CKEDITOR.instances.editor1.getSelection().getRanges()[ 0 ];
var children = newRange.cloneContents().getChildren();
var element;
for( var i = 0 ; i < children.count() ; i++ ) {
element = children.getItem( i );
html += element.$.innerHTML ? element.getOuterHtml() : '';
}
html will store your selection HTML.

set execcommand just for a div

it has any way for bind execcommand with a div element not for whole document , i try this :
document.getElementById('div').execcommand(...)
but it has an error :
execcommand is not a function
it has any way for bind the execcommand with just div element not whole document !!
i don't like use iframe method .
This is easier to do in IE than other browsers because IE's TextRange objects have an execCommand() method, meaning that a command can be executed on a section of the document without needing to change the selection and temporarily enable designMode (which is what you have to do in other browsers). Here's a function to do what you want cleanly:
function execCommandOnElement(el, commandName, value) {
if (typeof value == "undefined") {
value = null;
}
if (typeof window.getSelection != "undefined") {
// Non-IE case
var sel = window.getSelection();
// Save the current selection
var savedRanges = [];
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
savedRanges[i] = sel.getRangeAt(i).cloneRange();
}
// Temporarily enable designMode so that
// document.execCommand() will work
document.designMode = "on";
// Select the element's content
sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
// Execute the command
document.execCommand(commandName, false, value);
// Disable designMode
document.designMode = "off";
// Restore the previous selection
sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedRanges.length; i < len; ++i) {
sel.addRange(savedRanges[i]);
}
} else if (typeof document.body.createTextRange != "undefined") {
// IE case
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.execCommand(commandName, false, value);
}
}
Examples:
var testDiv = document.getElementById("test");
execCommandOnElement(testDiv, "Bold");
execCommandOnElement(testDiv, "ForeColor", "red");
Perhaps this helps you out:
Example code 1 on this page has the execcommand on a div by using a function. Not sure if that's what you're after? Good luck!
Edit: I figured out how to put the code here :o
<head>
<script type="text/javascript">
function SetToBold () {
document.execCommand ('bold', false, null);
}
</script>
</head>
<body>
<div contenteditable="true" onmouseup="SetToBold ();">
Select a part of this text!
</div>
</body>
Javascript:
var editableFocus = null;
window.onload = function() {
var editableElements = document.querySelectorAll("[contenteditable=true]");
for (var i = 0; i<editableElements.length; i++) {
editableElements[i].onfocus = function() {
editableFocus = this.id;
}
};
}
function setPreviewFocus(obj){
editableFocus = obj.id
}
function formatDoc(sCmd, sValue) {
if(editableFocus == "textBox"){
document.execCommand(sCmd, false, sValue);
}
}
HTML:
<div id="textBox" contenteditable="true">
Texto fora do box
</div>
<div contenteditable="true">
Texto fora do box
</div>
<button title="Bold" onclick="formatDoc('bold');">Bold</button>
You can keep it Simple, and add this to your div.
<div contenteditable="true" onmouseup="document.execCommand('bold',false,null);">

Categories

Resources