generating a button in javascript - javascript

I am using js to generate a webpage, and need to generate a button. The code is mostly working, but when I try to set the onclick attribute, I run into a problem. The onclick attribute is calling a function, and I need to give it an attribute. I have a variable in my code that contains the value I need to give to the function, but i don’t know how to put this value in the parameters. If this doesn’t make sense, it’s probably because I’m not good at explaining things.
Basically, I have:
var potato = 5;
var btn = document.createElement(“button”);
btn.setAtribute(“onclick”, “coolFunction(potato);”);
When I open the page and go to dev view, the button looks like this:
<button onclick=“coolFunction(potato);”>this is a button</button>
However, I want the value of potato there, instead of potato itself.
Anny Ideas?

You can do this
var potato = 5;
var btn = document.createElement('button');
btn.setAttribute('onclick',`coolFunction(${potato});`);

You could also call an anonymous function with onclick:
btn.onclick = () => coolFunction(potato)

I would forego the inline JS altogether. Add the value of potato to a data attribute on the button, and some text content, and add that to the page.
Next add an event listener to the button. When the click event on the button is fired it calls the function, and that can grab the value of the data attribute and do something with it. Here I'm just logging the value to the console.
const potato = 5;
const btn = document.createElement('button');
btn.textContent = 'Click me for potato';
btn.dataset.potato = potato;
document.body.append(btn);
btn.addEventListener('click', coolFunction);
function coolFunction() {
console.log(this.dataset.potato);
}

Related

javascript on onclick="return func();" stop working after first element by id

<button onclick="return validateEdit();" class="btn btn-primary submit-btn">Submit</button>
function validateEdit() {
var name = document.getElementById("sftName").value;
aler("name")
var startTime = document.getElementById("startTimeEdit").value;
aler("start time")
}
The function execute first alert and don't show second aler.I am using also:
$('#edit_shift').on('show.bs.modal', function (event) {
var anchor = $(event.relatedTarget) // Button that triggered the modal
var id = anchor.data('whatever')
var from = anchor.data('fromtime')
var modal = $(this)
$("#sftName").attr("value", name);
$("#startTimeEdit").attr("value", from);
In the another form is working fine.
Edit: start time with value and without value is not working in both cases.
I am full zero at javascript.
There are some typo error. Make sure its alert in your code and not aler. Also html content you posted having only button, whereas you are trying to fetch two elements with id sftName and startTimeEdit, make sure those elements are there in your code.
For better understanding can you recreate above issue on codepen.

Button onClick Event Listener not working in Electron app

Background:
I am using ElectronJS to make a game and I have a class for a shop which I named Shop.
It has a method that I call 'createItemElement' which takes an object named 'item' and creates an li element to be later added to a ul element. The code for this can be found below.
class Shop {
// ...
createItemElement(item) {
// Item Container
const li = document.createElement("li");
// Title
const title = document.createElement("h3");
title.textContent = item.title;
// Info
const info = document.createElement("p");
info.textContent = `Type: ${item.type}`;
// Add to Cart
const addButton = document.createElement("button");
addButton.textContent = "Add to Cart";
addButton.onclick = () => console.log("Adding to cart!");
li.appendChild(title);
li.appendChild(info);
li.appendChild(addButton);
return li;
}
// ...
}
Problem:
Interestingly, all of the HTML is correctly rendered and everything looks as it should, but the 'onclick' event just plain does not work.
Since all of these elements are in fact being rendered, it should be safe to assume that the code is indeed being run in the renderer process.
For some reason, however, the event is not being carried over to the app.
When I click the button in the app, nothing happens.
I checked the devTools and looked at the elements individually.
As expected, all of the elements were listed out correctly in element inspector, but when I inspected that 'addButton' button, there was no 'onclick' property to be seen.
Also, there are no errors in the console whatsoever, so that's nice (sarcasm).
And I am aware that there are many seemingly similar questions asked on StackOverflow, but none of the answers that I found have helped or applied to my situation.
It is extremely confusing as to why the elements are being rendered perfectly but the event listener is not working.
The full project can be found here and the file being excerpted below can be found here.
I looked at your shop.js page, and you incorrectly camel-case the onclick event in one place, but not in another. Using the camel-cased version of onclick will yield no error and do nothing.
Won't work:
empty_cart_button.onClick = (evt) => this.emptyCart();
Works:
addButton.onclick = () => this.addToCart(item);
As I can see from you're code, you're using el.innerHTML in the shop instance .getHTML() method. this will return the inner HTML as a raw string without any event listeners, this is why you see the rendered content as expected but the click listener doesn't work.
In the sketch.js file, the toggleShop function should use appendChild so instead of:
document.querySelector("#shop-container").innerHTML = shop.getHTML();
you should do:
document.querySelector("#shop-container").appendChild(shop.getElement())
and in the Shop class add the getElement method:
getElement() {
return this.el;
}
Be sure to toggle the shop and remove the #shop-container innerHTML when you want to toggle it off.
Also, as #Andy Hoffman answered, you should set the onclick property and not the onClick.

Polymer Selenium Test Accessing Sub-Element Data

In a firebase-login element I have
<paper-button id="btnLogin" data-dialog="login-modal" on-tap="toggleLogin">
<iron-icon icon="account-box"></iron-icon>
Login
</paper-button>
Where toggleLogin calls:
toggleLogin: function() {this.$.loginModal.toggle();},
In the Polymer test suite I am using:
Polymer.dom(element.root).querySelector('#btnLogin').click();
But Selenium is giving me the error of:
this.$.loginModal.toggle is not a function
Long story short, how can I click the button and check the modal pops up?
Note: Polymer team's test looks like:
Polymer.dom(myEl.root).querySelector('button').click()
Since they are naming their element myEl instead of element and looking for the button tag instead of the tag with id of btnLogin I felt that my solution was suitable. What am I doing wrong here?
UPDATE:
While looking at the bind event I still have not gotten things working.
CODE:
var btnLogin = Polymer.dom(myEl.root).querySelector('#btnLogin');
// This does the same thing as
// var btnLogin = element.$.btnLogin;
btnLogin.click.bind(btnLogin);
The above code allows me to move past the line but does not actually toggle the dialog. I am not sure why. When I add in click() instead of click it gives me the this.$.loginModal.toggle() is not defined error that I have been struggling with.
UPDATE:
Still have not found a good answer to this. Was looking into some code that may help and found the submenu element that wants to know information about it's content elements. I will include their testing below.
CODE:
suite('<paper-submenu>', function() {
var menu,
sub1, sub2, sub3,
collapse1, collapse2, collapse3,
trigger1, trigger2, trigger3;
setup(function() {
menu = fixture('basic');
sub1 = menu.querySelectorAll('paper-submenu')[0];
sub2 = menu.querySelectorAll('paper-submenu')[1];
sub3 = menu.querySelectorAll('paper-submenu')[2];
collapse1 = Polymer.dom(sub1.root).querySelector('iron-collapse');
collapse2 = Polymer.dom(sub2.root).querySelector('iron-collapse');
collapse3 = Polymer.dom(sub3.root).querySelector('iron-collapse');
trigger1 = sub1.querySelector('.menu-trigger');
trigger2 = sub2.querySelector('.menu-trigger');
trigger3 = sub3.querySelector('.menu-trigger');
});
test('selecting an item expands the submenu', function() {
assert.isFalse(collapse1.opened);
assert.isFalse(collapse2.opened);
assert.isFalse(collapse3.opened);
MockInteractions.tap(trigger1);
assert.isTrue(collapse1.opened);
assert.isFalse(collapse2.opened);
assert.isFalse(collapse3.opened);
});
Following the above example I tried the following:
test('Login Modal Opens', function(done) {
expect(loginModal).to.exist;
console.log(loginModal);
console.dir(loginModal);
expect(loginModal.opened).to.exist;
assert.isFalse(loginModal.opened);
btnLogin.click.bind(btnLogin);
assert.isTrue(loginModal.opened);
});
Unfortunately I am getting loginModal.opened as undefined. loginModal.toggle() gives toggle is not a function error.
UPDATE:
I found that bind does not actually call the function. It only binds the this to a new location. So when I was doing btnLogin.click.bind(btnLogin) it was doing the binding so when I called btnLogin.click() it would have a binding to btnLogin rather than ... btnLogin. Therefore it would have been the same to just call btnLogin.click() without ever calling the bind function.
Now that this is figured out, I decided to mess with call instead of bind but again I only was binding the this to the same scope so that was no help. I then tried btnLogin.click.call(element) but it still gave me the error that this.$.loginModal.toggle is not a function.
Just a wild guess, I don't know JS well
var el = Polymer.dom(element.root).querySelector('#btnLogin');
el.click().bind(el)();

Creating a new window that has a button in JavaScript

Hey Im trying to to learn JavaScript at the moment, and I want to be able to create a button on a page that I created in JavaScript, but it always adds the button to index.html instead. Please note I am running this off of WebStorm IDE and don't have a URL/ dont know what to put for window.open(____) because of that.
It successfully creates a new window saying "Hello", but there is no button.
var myWindow=window.open('');
myWindow.document.write('Hello');
var button=myWindow.document.createElement("newbutton");
button.onclick= function(){
alert("blabla");
};
var buttonParent= myWindow.document.getElementById("buttonParent");
buttonParent.appendChild(button)
It looks as though you're creating a new window called myWindow, and writing the text hello to it. However, the container with the id "buttonParent" does not reside within the new window, but rather the document that index.html is in.
Try this out:
var newDiv = document.createElement("div");
newDiv.id = "newButtonParent" //make sure you pick a unique id
myWindow.document.appendChild(newDiv);
var buttonParent= myWindow.document.getElementById("newButtonParent");
buttonParent.appendChild(button);
Edit: Fixed a typo. From:
var buttonParent= myWindow.document.getElementById("buttonParent");
to
var buttonParent= myWindow.document.getElementById("newButtonParent");
When was the element with the ID buttonParent created? If this is your entire snippet, you'd first need to create that element as well, otherwise .getElementById isn't going to find anything in the new window, meaning .appendChild won't work properly.
The other thing to note is that alert is a property of the window object, so just calling alert('!') will attach the alert the the main window. You need to call it as myWindow.alert('!') to have it fire on the new window.
Also, document.createElement takes a tag name, so if you want default button behaviour it should be
myWindow.document.createElement('button');
Here's a working example. I've set the background of the container element to red so you can see it is there.
DEMO - (Click the run button.)
var w = window.open(''),
button = w.document.createElement('button');
button.innerHTML = 'My Button';
button.addEventListener('click', function () {
w.alert('!');
});
var container = w.document.createElement('div');
container.id = 'buttonParent';
container.style.background = 'red';
w.document.body.appendChild(container);
container.appendChild(button);

Button.onclick automatically triggers, then will not trigger again

I have a script, which I'm using to try and display only one section of a webpage at a time.
function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}
Currently, I'm using buttons to change which section is displayed.
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");
However, when I load the page, the following happens:
I see the function attached to each button activate once in sequence in the console.
The page refuses to respond to further button inputs.
Testing with the console shows that showMe() and the functions it calls still all work properly. I'm sure I'm making a very basic, beginner mistake (which, hopefully, is why I can't find this problem when I Google/search StackOverflow/read event handling docs), but I'm at a loss for what that mistake is. Why would my script assume my buttons are clicked on load, and why won't it let me click them again?
You're calling the function an assign the value to onclick property instead of attach the function, try defining your onclick property as:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
Try the follow jsfiddle:
function showMe(id){ // some stuff..
console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>
Hope this helps,

Categories