I have a problem in the following JavaScript function.
I am trying to create buttons dynamically based on details from the results variable.
The button are created and an event is attached but it seems each button has the exact same event attached.
I need the address variable to be different for each event attached to a button and for that button then to be added to replace text in my macField variable.
function (results) {
var r;
var x, i;
var btn;
for (i = 0; i < results.length; i++) {
app.display("Paired to" + results[i].name + results[i].address);
x = document.getElementById("message2");
r = results[i].address;
w = document.getElementById('macField').value;
btn = document.createElement('input');
btn.onclick = function () {
document.getElementById('macField').value = r;
};
btn.setAttribute('type', 'button');
btn.setAttribute('name', 'sal' + [i]);
btn.setAttribute('id', 'Button' + [i]);
btn.setAttribute('value', results[i].name);
appendChild(btn);
}
}
function (error) {
app.display(JSON.stringify(error));
}
Use immediate function. Change this part:
btn.onclick = function () {
document.getElementById('macField').value = r;
};
like this:
(function(r){
btn.onclick = function () {
document.getElementById('macField').value = r;
};
})(r);
Have a look: http://jsfiddle.net/uebD8/1/
create your function seperately like below
function macFieldValue(val)
{
document.getElementById('macField').value = val;
}
and set button onclick attribute like this
btn.setAttribute('onclick', 'macFieldValue('+r+')');
Just modifying this part:
btn = document.createElement('input');
btn.onclick = function () {
document.getElementById('macField').value = r;
};
to
btn = document.createElement('input');
btn.setAttribute('some_id', r);
btn.addEventListener('click',
function (e) {
var addr = e.source.some_id;
document.getElementById('macField').value = addr;
}, false);
You are hitting an unfortunate curse of JS. Your code would have worked if it wasn't within a for-loop. In any case, you should be using addEventListener.
Related
I am trying to pass the value of a button to a function when it is clicked. Because the buttons were created as a javascript element I'm not sure how to do it.
methods:{
createButtons() {
var i;
var rows =["9","8","7","6","5","4","3","2","1","0","•","="];
var elDiv = document.getElementById("myDIV");
for (i=0; i<12; i++){
var btn = document.createElement("BUTTON");
btn.value = i
btn.style.height = "40px"
btn.textContent = rows[i];
btn.onclick = buttonvalue;
elDiv.appendChild(btn);
}
var pressedbutton = document.getElementById("calculate");
pressedbutton.remove();
},
}
}
function buttonvalue(i){
alert(i);
}
This is an XY problem. Don't create DOM elements manually like this, that's what Vue is for.
But to answer your question, you can do something like this:
const captureI = i;
btn.onclick = () => buttonvalue(captureI);
I copied i into a new local variable because i changes value by the for loop.
Or you can just write the for loop like this instead:
for (let i = 0; i < 12; i++) {
// ... omitted code ...
btn.onclick = () => buttonvalue(i);
}
I'm trying to take the user input, which is obtained with an event listener, display it on the page, and store the value in an array for further use. However, the array stays empty. Any ideas?
let arr = [];
function display() {
let p = document.querySelector('p');
let btn = document.querySelector('btn');
let input = document.querySelector('input').value;
btn.addEventListener('click', () => {
p.textContent = input;
arr.push(input);
});
}
display();
function display() {
let p = document.querySelector('p');
let arr = [];
let btn = document.querySelector('btn');
btn.addEventListener('click', () => {
let input = document.querySelector('input').value; // <-- move this line here
p.textContent = input;
arr.push(input);
});
}
display()
Your problem is that you're reading input out before the button has an event listener - so the current value (an empty string) will be read. Make sure to declare input inside the event listener:
btn.addEventListener('click', () => {
let input = document.querySelector("input").value;
p.textContent = input;
arr.push(input);
});
I believe the issue is that document.querySelector('btn') is not properly selecting the button because there is no such thing as a btn element. You'll need to change that to document.querySelector('button'). Then, combine that with what the other answers have mentioned -- you also need to capture the input value inside the event handler function.
let arr = [];
function display() {
let p = document.querySelector("p");
let btn = document.querySelector("button");
btn.addEventListener("click", () => {
let input = document.querySelector("input").value;
p.textContent = input;
arr.push(input);
});
}
display();
How can I dynamically create HTML buttons, in Javascript, that when users click on them they call a same function, but with a different parameters.
For example:
function a(param){console.log(param);};
for (int i = 0; i < 10; i++)
{
button = document.createElement('button');
button.onclick = <place a function that when button is clicked, calls function a with parameter i>;
}
Can someone give me a clue?
Call the a function:
button.setAttribute('data-param', i);
button.onclick = function () {a(this.getAttribute('data-param'));};
jsFiddle: http://jsfiddle.net/systemovich/asw3myqg/1/
function b(param){
var myParam = param;
return function a() {
console.log(myParam);
}
}
for (int i = 0; i < 10; i++)
{
button = document.createElement('button');
button.onclick = b(i);
}
function B(sName) {
this.name = sName;
}
B.prototype = {
instanceCreatButtonCount: 0,
funA: function () { // alert instance's name
alert(this.name);
},
funB: function () { // create a button which clikced can alert this instance's name through funA;
var that = this;
B.prototype.instanceCreatButtonCount++;
var id = "_id" + that.instanceCreatButtonCount;
var str = "<button id='" + id + "' >clike me</button>";
var a = document.getElementById("btns");
a.innerHTML += str;
var btn = document.getElementById(id);
btn.onclick = function () {
that.funA();
};
}
};
var b1 = new B("Jim");
var divB1 = document.getElementById("b1");
divB1.onclick = function () {
b1.funB();
}
var b2 = new B("Dad");
var divB2 = document.getElementById("b2");
divB2.onclick = function () {
b2.funB();
}
After I click divB1, I create a button through b1.funB().
After I click divB2, I create a button througb b2.funB().
Why can only newest button alert name ? I find that other button's onclick function is null.
When you use a.innerHTML += str to append a new element, the entire subtree of a gets removed before the new elements are added again; the removal also unbinds any events you have added before.
It's better to use proper DOM functions in this case, i.e. var btn = document.createElement(), etc. and a.appendChild(btn).
Fiddle provided by #ShadowWizard: http://jsfiddle.net/qR6e8/
I have this function:
function addButtonLookup() {
var element = document.getElementById("btnToolBar");
var index;
for (var i = 0; i < lookupArray.length; i++) {
index = i;
var btn = document.createElement('input');
btn.type = 'button';
btn.value = '' + lookupArray[i];
btn.name = 'btnLookup' + i;
btn.id = i;
btn.className = 'CommonButtonStyle';
element.appendChild(btn);
btn.onclick = function() {
debugger;
tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
};
}
}
onbutton click the i is undefined
Instead of this:
btn.onclick = function() {
debugger;
tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
};
Try this:
btn.onclick = (function(i) {
return function() {
debugger;
tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
}
})(i);
The issue with the first version is that the i variable is copied from the current scope. However the i variable varies in the current scope (it's part of a for loop), this is why you're getting this weird behavior.
By passing the i variable as a paremeter to a new function (like the second example) the current i variable is copied.
You should take a look at how Closures work in JavaScript.