Reputation: 543
I'm developing this javascript code for awhile which it only run a function once when the button is click.
JAVASCRIPT:
var a = 1;
function add(name)
{
if (a <= 9)
{
a++;
var parent = name.parentNode;
var content = parent.querySelector("div");
var str = content.innerHTML;
str = str.replace(/_1/gi, '_' + a);
var divtest = document.createElement("div");
divtest.setAttribute("id", a);
divtest.innerHTML = str + a;
parent.appendChild(divtest);
}
}
HTML:
<div id="main1">
<button onclick="add(this);return false;">+</button>
<div id="content1">
A
</div>
</div>
<div id="main2">
<button onclick="add(this);return false;">+</button>
<div id="content2">
B
</div>
</div>
The code above only calls the function once but I want it to run the function at the same time.
OUTPUT:
+
A
A 2
A 3
A 4
A 5
A 6
A 7
A 8
A 9
A 10
+
B
When I click the button on both divs it should add both on there main divs per click.
EXPECTED OUTPUT:
+
A
A 2
A 3
A 4
A 5
A 6
A 7
A 8
A 9
A 10
+
B
B 2
B 3
B 4
B 5
B 6
B 7
B 8
B 9
B 10
Upvotes: 3
Views: 1258
Reputation: 5766
Assuming the code is working, this is simple enough:
function add(me)
{
var buttons = document.querySelectorAll('button.add');
var btn;
for(var b = 0; b < buttons.length; b++)
{
btn = buttons[b];
if(me === btn) {
btn.a = btn.a || 1;
btn.a++;
addForButton(btn);
}
}
}
function rem(me)
{
var buttons = document.querySelectorAll('button.remove');
var btn;
for(var b = 0; b < buttons.length; b++)
{
btn = buttons[b];
if(me === btn) {
var divs = me.parentNode.querySelectorAll('div > div');
if(divs.length > 1){
divs[divs.length - 1].parentNode.removeChild(divs[divs.length - 1]);
btn.a--;
}
}
}
}
function addForButton(name) {
var parent = name.parentNode;
var content = parent.querySelector("div");
if (name.a <= 9)
{
var str = content.innerHTML;
str = str.replace(/_1/gi, '_' + name.a);
var divtest = document.createElement("div");
divtest.setAttribute("id", name.a);
divtest.innerHTML = str;
parent.appendChild(divtest);
}
}
Then add IDs to the buttons:
<button onclick="add();return false;">+</button>
<button onclick="add();return false;">+</button>
Upvotes: 2