Java script function gets called when i pass arguments - javascript

I have created a dynamic button when that button gets clicked it will invoke a javascript function with an arguments but the other lines are getting skipped during this process
function mainradio() {
var dyndiv = document.createElement("div");
dyndiv.id = "div_temp";
var dynradiogroup = document.createElement("label");
dynradiogroup.name="rdlbl";
dynradiogroup.className="rdmainclass";
dynradiogroup.innerHTML="Please enter your question";
var nextradio = document.createElement("input");
nextradio.type="button";
nextradio.id="nxtbtnid";
nextradio.name="nxtbtnnme";
nextradio.value="Add more button";
nextradio.onclick =createRadio(dyndiv.id);
dyndiv.appendChild(dynradiogroup);
dyndiv.appendChild(nextradio);
document.getElementById("dynElements").appendChild(dyndiv);
}
the dynamically created label and button are not attached to the div that was also created dynamically
dyndiv.appendChild(dynradiogroup);
dyndiv.appendChild(nextradio);
document.getElementById("dynElements").appendChild(dyndiv);
function get invoked before these 3 statements gets executed.

Use nextradio.onclick = createRadio.bind(this, dyndiv.id); or nextradio.onclick = () => { createRadio(dyndiv.id); };

Related

Why is my counter number not updating using DOM

the counter number is not updating even after clicking the button.
var counterNumber = 0;
var counterText = document.querySelector("strong");
var reduceButton = document.querySelectorAll("button")[0];
var increaseButton = document.querySelectorAll("button")[1];
increaseButton.addEventListener("click", function() {
counterNumber++;
})
reduceButton.addEventListener("click", function() {
counterNumber--;
})
counterText.textContent = counterNumber;
Your eventListener acts on the button clicks and counterNumber are increased as it should (you can add a console.log to see this) But you never assign the new value to your text counterText. That row is run once and not everytime you click a button.
Move this row:
counterText.textContent = counterNumber;
to be within your eventListener functions

Dynamically created form called via onclick disappears immediately Javascript

I have dynamically created a button in my Javascript function and called another function onclick, as shown below.
streambtn = document.createElement("button");
streambtn.setAttribute("onclick","createattribute()");
The createattribute() method opens a subdivision within the dynamically created form and this function is as follows.
function createattribute() {
inputval.innerHTML = "Provide a Stream name and click to add attribute-type pairs to yours stream.";
var input = document.createElement("input");
input.type = "text";
input.placeholder="Attribute name";
input.id="attr"+attrID;
input.className = "attr-textfield-style";
inputval.appendChild(input);
//Display the drop down menu
var newDiv=document.createElement('div');
var html = '<select>', attrtypes = typeGenerate(), i;
for(i = 0; i < attrtypes.length; i++) {
html += "<option value='"+attrtypes[i]+"'>"+attrtypes[i]+"</option>";
}
html += '</select>';
newDiv.className="attr-combobox-style";
newDiv.id="type"+attrID;
newDiv.innerHTML= html;
inputval.appendChild(newDiv);
attrID++;
alert("attrname id: "+input.id+" attrtype id: "+ newDiv.id);
}
The inputval is a division within the dynamically created form where the newly created form elements from the createattribute() function will be appended to. But the issue that I'm facing right now, is that though the method is correctly called, the form(dynamically created form) immediately disappears in a split second once the streambtn is clicked. Once it is clicked, it displays the first line "Provide a Stream name and click to add attribute-type pairs to yours stream." in a flash and disappears. Is there a way to keep it onscreen and then hide it depending on any conditions(like after the user finishes entering the data corresponding to that newly opened form-> created via createattribute() method)?
Add type = "button" as <button> without type = "button" will act as submit button and over click of the submit buttopn, page will be unloaded.
streambtn = document.createElement("button");
streambtn.type = 'button';
streambtn.setAttribute("onclick","createattribute()");

Delete Button not working properly (DOM)

Ok here is what I was trying to do... Create a delete button along with edit by using DOM while creating a paragraph. But delete button always seems to be deleting first paragraph instead of deleting the corresponding paragraph.. here's my code:
Javascript:
function writePara()
{
var comment = document.getElementById("usrinput").value;
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;
document.getElementById("updateDiv").appendChild(newParagraph);
var button = document.createElement("button");
var Btext=document.createTextNode("EDIT");
button.appendChild(Btext);
document.getElementById("updateDiv").appendChild(button);
button.onclick =
(
function()
{
var edit = prompt("Type to edit", "");
newParagraph.innerHTML = edit;
}
);
var button2 = document.createElement("button");
var Btext2=document.createTextNode("DELETE");
button2.appendChild(Btext2);
document.getElementById("updateDiv").appendChild(button2);
button2.onclick =
(
function ()
{
var items = document.querySelectorAll("#updateDiv p");
if (items.length)
{
var child = items[0];
child.parentNode.removeChild(child);
}
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);
addBr();
}
Any ideas guys?
You already have a reference to the new paragraph in the writePara function and you already used it once in the edit handler, so why don't you use it again in the delete handler?
button2.onclick =
(
function ()
{
newParagraph.parentNode.removeChild(newParagraph);
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);
Here's how it works: http://jsbin.com/nohud/1/edit. Write something in the input and click outside of it a few times to generate some paragraphs.
Edit: The code above utilizes closures. It is important to understand that each time writePara is called, the newParagraph variable points to a new DOM element and each click event handler defined in the same function has access to that specific element in the newParagraph variable. So whenever the edit/delete handlers are called newParagraph is the element with which the associated buttons have been created when writePara has been called.
Here's some code that explains that clearer that I do:
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
It is taken from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures. More also here: How do JavaScript closures work?.
From there on newParagraph.parentNode is the container containing the new paragraph, so newParagraph.parentNode.removeChild(newParagraph) just removes that specific element from its container.
Its because you are always giving index[0] so that its deleting first paragraph as shown below
var child = items[0];
it should be
newParagraph.parentNode.removeChild(newParagraph);

Using this within functions called with onclick event in Javascript

I'm currently building a small Todo list application using vanilla Javascript but I'm having some issues creating a delete button that onClick removes it's parent element.
From what I have read, when an onClick is called in Javascript the this keyword can be used to refer to the element that called the function. With this in mind I have the following code:
window.onload = initialiseTodo;
function addRecord(){
var title = document.getElementById('issueTitle');
var issueContent = document.getElementById('issueContent');
var contentArea = document.getElementById('contentArea');
if(title.value.length > 0 && issueContent.value.length > 0){
var newItem = document.createElement('div');
newItem.id = 'task' + count++;
newItem.className = 'task';
newItem.innerHTML = '<div class="taskbody"><h1>' + title.value + '</h1>'+ issueContent.value + '</div><div class="deleteContainer">'
+ '<a class="delete">DELETE</a></div>';
contentArea.appendChild(newItem);
assignDeleteOnclick();
}
}
function deleteRecord(){
this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
}
function assignDeleteOnclick(){
var deleteArray = document.getElementsByClassName('delete');
for(var i=0;i<deleteArray.length;i++){
deleteArray[i].onclick= deleteRecord();
}
}
function initialiseTodo(){
var btn_addRecord = document.getElementById('addRecord');
btn_addRecord.onclick = addRecord;
}
Basically I have a form that has two fields. When these fields are filled and the addRecord button is clicked a new div is added at the bottom of the page. This div contains a delete button. After the creation of this I assign an onclick event to the delete button which assigns the deleteRecord function when the delete button is clicked. My issue is with the deleteRecord function. I have used this to refer to the calling element (the delete button) and wish to remove the task div that is the outermost container however I current get a message that says: 'Cannot read property 'parentNode' of undefined ' which suggests to me the this keyword is not working correctly.
Any help would be greatly appreciated.
I've added the full code to a fiddle.
http://jsfiddle.net/jezzipin/Bd8AR/
J
You need to provide the element itself as a parameter. I did so by changing the html to include onclick="deleteRecord(this)" to make it a little easier to deal with. This means you can remove the assignDeleteOnclick() function
function deleteRecord(elem){
elem.parentNode.parentNode.remove();
}
Demo
You might style the .content to be hidden better if there are no elements to prevent that extra white space
Edit
Since you don't want an inline onclick, you can do it with js the same:
function deleteRecord(elem){
elem.parentNode.parentNode.remove();
}
function assignDeleteOnclick(){
var deleteArray = document.getElementsByClassName('delete');
for(var i=0;i<deleteArray.length;i++){
// Has to be enveloped in a function() { } or else context is lost
deleteArray[i].onclick=function() { deleteRecord(this); }
}
}
Demo

obj is null, javascript

function init()
{
alert("init()");
/**
* Adds an event listener to onclick event on the start button.
*/
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
});
ok so what I have here is a event listerner function, the case is when viewInvitation is clicked , the program will fetch my xml file and run page master function where I created my decline button with id="declinebutton", however this does not work, the error message that i get is obj=null or the program could not find id = declinebutton, why is it so? I have created it when I called page master using dom. any help will be appreciated.
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
var subjectList;
var i;
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table=document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
var input=document.createElement("p");
var inputText=document.createTextNode("You are invited to join " + groupName + "(groupId : " + groupId +")");
input.className="style11";
var blank=document.createElement("nbps");
input.appendChild(inputText);
var acceptButton=document.createElement("input");
acceptButton.type="button";
acceptButton.id="acceptbutton";
acceptButton.value="accept";
var declineButton=document.createElement("input");
declineButton.type="button";
declineButton.id="declinebutton";
declineButton.value="decline";
table.appendChild(input);
table.appendChild(acceptButton);
table.appendChild(declineButton);
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
/**function getValueOf()
{
return i;
}**/
function declineInvitation()
{
alert("decline");
}
function acceptInvitation()
{
alert("hello");
/**var pos=getValueOf();
alert(subjectList[pos].attributes[0].nodeValue);**/
}
That's my page master function, and I definitely have created the button. but it does not work.
Try calling your function like this:
window.onload=init;
The javascript runs as the page loads. At that point, the element does not yet exist in the DOM tree. You'll need to delay the script until the page has loaded.
The example you gave doesn't create the "Decline" button, as your question suggests it should. If it should, you might want to look at that.
Of course, if the button already exists, please disregard this answer.
You have a listener inside a listener. Is that right?
What about this?:
function init(){
alert("init()");
/** * Adds an event listener to onclick event on the start button. */
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
}
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
As far as I understand, you create button with id="declinebutton" for each entry from xml, is that right?
If yes, I'd suggest you to generate different id's for each button (for example, append line index to 'declinebutton', so you have buttons 'declinebutton0', 'declinebutton1' an so on), and assign event listener to buttons separately in the loop.

Categories