I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element
Related
I am facing a problem while removing a paragraph, which I have added using javascript.
Adding buttons work fine. The problem occurs when I try to remove the paragraph.
function rdn_id(){return Math.random().toString(36).substring(7);}
//create button
function create_btn()
{
//Create a remove button
var btn_remove = document.createElement("BUTTON");
//create a unique button ID
id_btn_remove = rdn_id();
btn_remove.id = id_btn_remove ;
btn_remove.textContent = "Remove file";
return [btn_remove, id_btn_remove];
}
//add elt function
function create_p_btn()
{
//Create paragraph
var paragraph = document.createElement("P");
//create a unique p ID
id_paragraph = rdn_id();
paragraph.id = id_paragraph;
paragraph.style.paddingTop = "5px";
paragraph.style.background = "blue";
document.getElementById("setItHere").appendChild(paragraph);
// add button
var values = create_btn();
var btn_rmv = values[0];
var id_btn = values[1];
paragraph.appendChild(btn_rmv);
document.getElementById(id_btn).addEventListener("onclick", function(){remove_func(id_paragraph);});
}
//Remove function
function remove_func(id_el)
{
var elt = document.getElementById(id_el);
elt.parentNode.removeChild(id_el);
}
<div id="setItHere">
<Button id="start" onclick="create_p_btn();">add</Button>
</div>
Am I missing something ?
Thank you in advance.
You need to make two changes:
Event name should be click instead of onclick
elt.parentNode.removeChild(id_el); should be elt.parentNode.removeChild(elt);
Check out this pen
https://codepen.io/tanmayv/pen/yLNwNNJ
I have this HTML:
<div id = "options"></div>
I access to this div trough this Javascript:
var test = "hola";
document.getElementById('options').innerHTML=
<p>Test</p> <li>${test}</li>
And I have this button:
function click({
document.getElementById("Click").addEventListener("click", function(){
});
};
click();
I need that when that function called "click" is executed automatically that <li> can clean that value of the variable: "test" and it is seen empty.
How can I do it? Thank you
el.innerHTML is the property which keeps track of HTML text values shown inside the element. You can set that to empty whenever you want to clear it.
Try this sample - https://jsitor.com/J0gXikZmV
<div id = "options"></div>
var test = "hola";
let el = document.getElementById("options");
el.innerHTML = "<p>Test</p> <li>${test}</li>";
el.addEventListener('click', () => {
el.innerHTML = '';
})
Here it clear the html content of div
I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.
I am having an issue deleting or replacing a div with a either an empty div or a new veriosn of the div. I have tried to destroy the div with delete $targetname I've tried to replace the div with $("#divname").replace() and I seem to be missing some. I have the function tied to a button click that also clears a textarea and that part works fine but my form continues to show the divs that are getting appended but never removed. Below is the link to the fiddle for my code, any help is appreciated.
http://jsfiddle.net/fNfK8/
emWindow = window.open("", null, "height=400,width=800,status=yes,toolbar=no,menubar=no,location=no");
emWindow.document.title = "Emote Builder";
emWindow.document.body.style.background = "#00214D";
emWindow.document.body.style.color = "White";
// create a form and set properties
var emForm = document.createElement('form');
emForm.id = 'emForm';
// insert into the body of the new window
emWindow.document.body.appendChild(emForm);
// add text before the input
var emoteBuildL = document.createElement('emoteBuildL');
emForm.appendChild(document.createTextNode('Emote Build Window:'));
//add linebreak
var linebreak = document.createElement('br');
emForm.appendChild(linebreak);
// add a text input
var emoteBuild = document.createElement('textarea');
emoteBuild.type = 'text';
emoteBuild.name = 'emoteBuild';
emoteBuild.id = 'emoteBuild';
emoteBuild.rows = 6;
emoteBuild.cols = 80;
emoteBuild.value = '';
emForm.appendChild(emoteBuild);
var emoteTosend = document.getElementById('emoteBuild');
//add linebreak
var linebreak = document.createElement('br');
emForm.appendChild(linebreak);
var ePreview = document.createElement('button');
ePreview.type = 'button';
ePreview.innerHTML = 'Preview Emote';
ePreview.onclick = emoteFunc;
emForm.appendChild(ePreview);
var eSubmit = document.createElement('button');
eSubmit.type = 'button';
eSubmit.innerHTML = 'Send Emote';
eSubmit.onclick = function () {
client.send_direct("" + emoteBuild.value);
};
emForm.appendChild(eSubmit);
var eClear = document.createElement('button');
eClear.type = 'button';
eClear.innerHTML = 'Clear Emotes';
eClear.onclick = function () {
emoteBuild.value = '';
delete $emPreviews;
};
emForm.appendChild(eClear);
//add linebreak
var linebreak = document.createElement('br');
emForm.appendChild(linebreak);
// add text before the input
var emotePviewL = document.createElement('emotePviewL');
emForm.appendChild(document.createTextNode('Emote Previews:'));
//add linebreak
var linebreak = document.createElement('br');
emForm.appendChild(linebreak);
//add linebreak
var linebreak = document.createElement('br');
emForm.appendChild(linebreak);
function emoteFunc() {
var emPreview = emoteBuild.value;
emPreview = emPreview.replace(/%%(.+?)%%/g, "\<font color=\"red\"\>\"$1\"\</font\>");
emPreview = emPreview.replace(/%%/g, "\"");
emPreview = emPreview.replace(/\^/g, "");
emPreview = emPreview.replace(/(\w+_him)/g, "(him/her)");
emPreview = emPreview.replace(/(\w+_his)/g, "(his/her)");
emPreview = emPreview.replace(/(\w+_he)/g, "(he/she)");
emPreview = emPreview.replace(/#/g, "");
var div = document.createElement("div");
div.class = 'emPreviews';
div.id = 'emPreviews';
div.style.color = "black";
div.style.backgroundColor = "white";
div.innerHTML = emPreview;
emForm.appendChild(div);
emForm.appendChild(linebreak);
}
You will find it very much more efficient to put the HTML into a separate file and use that as the source for the new window. Alternatively, use document.write to add content to the page, e.g. the following replaces about 20 lines at the start of your script:
function openWin() {
var emWindow = window.open("", null, "height=400,width=800,status=yes");
emWindow.document.write(
'<!doctype html><title>Emote Builder<\/title>' +
'<style type="text/css">body{background-color: #00214D;color:White;}<\/style>' +
'<form id="emForm">' +
'Emote Build Window:<br>' +
'<textarea name="emoteBuild" id="emoteBuild" rows="6" cols="80"><\/textarea>'
);
emWindow.document.close();
}
Note that when you do:
var linebreak = document.createElement('br');
it creates an element in the current document, but then:
emForm.appendChild(linebreak);
appends it to an element in a different document. You really should do:
var linebreak = emWindow.document.createElement('br');
emForm.appendChild(linebreak);
Or just put it in the HTML above.
You are also creating a button in the opener window, appending it to the form, then having it call a function in the opener. The new window has a new global context, it doesn't have access to the opener's scope. You can do:
ePreview.onclick = window.opener.emoteFunc;
or similar but you might find that blocked in some browsers.
I'd suggest you re–write the function to firstly generate the HTML you want, then write it to a new window using emWindow.document.write. Don't forget to call emWindow.document.close at the end.
Edit
Remember that you are working across documents. So if you are still running the script in the opener (the original window), you have to preface any reference to methods in the child window with a reference to emWindow, e.g. to get a reference to the form in the child window you have to use:
function emoteFunc() {
// Get a reference to the form in the child window
var emPreview = emWindow.document.getElementById('emoteBuild');
...
// Create a div in the child window to append to it
var div = emWidnow.document.createElement('div');
...
// The form and div are in the same document, so just append
emForm.appendChild(div);
// Create a BR element in the child and append it
emForm.appendChild(emWindow.document.createElement('br'));
...
}
Edit 2
Here is a trivial example of sending data between a child and opener.
<script>
var win;
function newWin(){
win = window.open('','','');
win.document.write(
'<title>new window<\/title>' +
'<script>function getValue() {' +
'document.getElementById("i0").value = opener.document.forms.f0.i0.value;}<\/script>' +
'<input id="i0">' +
'<input type="button" onclick="getValue()" value="Get value from opener">' +
'<input type="button" onclick="opener.getValue()" value="Get value using function in opener">'
);
win.document.close();
};
function getValue() {
console.log('getValue called');
console.log(win.document.getElementById('i0').value);
win.document.getElementById('i0').value = document.f0.i0.value;
}
function sendValue(value) {
win.document.getElementById('i0').value = value;
}
</script>
<button onclick="newWin()">Open child</button>
<form id="f0">
<p>Value to get from child
<input name="i0" value="value in opener">
<input type="button" value="Send value" onclick="sendValue(this.form.i0.value)">
</form>
You will discover that (in IE at least) you can:
call a function in the child window to get a value from the opener
call a function in the opener to send a value to the child
call a function in one window from the other,
but you can't call a function in the other window that updates the current window, that's one too many hops.
So any function you want to call from the child should be in the child, and any function you want to call from the opener should be in the opener.
I am adding a button dynamically in html like below:
On click of that button I want to call a Javascript function:
var but = document.createElement("button");
but.value="delete row";
but.setAttribute("onclick","callJavascriptFunction()");
//this is not working
but.onclick="callJavascriptFunction()"
//this is also not working
document.getElementById("but").onclick="callJavascriptFunction()"
//this is also not working
but.id="but"+inc;
How can this be resolved?
try this:
but.onclick = callJavascriptFunction;
or create the button by wrapping it with another element and use innerHTML:
var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
Remove the () from your expressions that are not working will get the desired results you need.
but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;
This code work good to me and look more simple. Necessary to call a function with specific parameter.
var btn = document.createElement("BUTTON"); //<button> element
var t = document.createTextNode("MyButton"); // Create a text node
btn.appendChild(t);
btn.onclick = function(){myFunction(myparameter)};
document.getElementById("myView").appendChild(btn);//to show on myView
Try
but.addEventListener('click', yourFunction)
Note the absence of parantheses () after the function name. This is because you are assigning the function, not calling it.
but.onclick = function() { yourjavascriptfunction();};
or
but.onclick = function() { functionwithparam(param);};
I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:
//Bad code.
var btn = document.createElement('button');
btn.onClick = function() { console.log("hey"); }
to this:
//Working Code. I don't like it, but it works.
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);
document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){ console.log("hey"); }
I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.
Try this:
var inputTag = document.createElement("div");
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";
document.body.appendChild(inputTag);
This creates a button inside a DIV which works perfectly!
but.onclick = callJavascriptFunction;
no double quotes no parentheses.
Using modern JavaScript, this solution works well:
let btn = document.getElementById("btnID");
btn.onclick = () => {onAction(url, method);};
for me this works!
button.onclick = () => (removechore());