on click increment a button text using javascript? [duplicate] - javascript

This question already has answers here:
Increment a number inside a div?
(4 answers)
Closed 3 years ago.
I am creating buttons on click I would like to increment button text on every time a user creates a new button
HTML
<button id="btn">Add button</button>
<div id="movie-block">
</div>
$("#btn").on("click", function(){
var newMovieBlockButton = $("<div class='movie-button w'>Button1<div>");
$("#movieblock" + movieid).append(newMovieBlockButton);
})
I want when user click add button new button should be created starting with eg
button1, if he creates another button it should be button2 etc etc
How can I accomplish that using jquery?

In each click, you can take the length of the button with class movie-button and concatenate that with the text:
$("#btn").on("click", function(){
var len = $('.movie-button').length + 1;
var newMovieBlockButton = $("<div class='movie-button w'>Button"+ len +"<div>");
$("#movie-block").append(newMovieBlockButton);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="btn">Add button</button>
<div id="movie-block">
</div>

A quick google search would have helped.
<button id="btn">Add button</button>
<div id="movie-block">
</div>
let counter = 1;
$("#btn").on("click", function(){
var newMovieBlockButton = $(`<div class='movie-button w'>Button${counter}<div>`);
$("#movieblock" + movieid).append(newMovieBlockButton);
counter++;
})

<!DOCTYPE html>
<html>
<body>
<button onclick="append()">Try it</button>
<div id="myDIV">
New Paragraphs will add on this div
</div>
<script>
function append() {
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
document.getElementById("myDIV").appendChild(para);
}
</script>
</body>
</html>
Hope this will help

Related

How to identify a div id and trigger it

I got a problem with one of the sites with JavaScript, and I need to automate a click and then find out how many turns I got before I run out of them. As in, for example, let's say I have 8 turns. So what I would need is to automatically have JavaScript to trigger said div id, 8 times. (As in, I add like this)
Link:https://jsfiddle.net/yxsgp8tc/
<body>
<button id="test">Test</button>
<p>
On box should be number of tests
</p>
<form>
<label><input type="text"/>00-99</label>
<button>
trigger it
</button>
</form>
</body>
in plain javascript, you would target unique elements (using an id) by using document.getElementById('<element_id'). If you wanted to target a class, you would document.querySelector('.<class_name>') for the first instance of the class, or document.querySeletorAll('.<class_name>')
Also, your input tag was misspelled "imput", and is a singleton tag so you don't have to close it off.
Assuming you wanted a way to trigger a click event, here's a basic example:
<head>
<script>
const test = document.getElementById('test');
const trigger = document.getElementById('trigger')''
test.addEventListener('click', () => {
const num_test = document.getElementById('num_tests').value;
for (let i = 0; i < num_test; i++) {
trigger.click();
}
});
trigger.addEventListener('click', () => {
console.log('trigger clicked');
});
</script>
</head>
<body>
<button id="test">Test</button>
<p>
On box should be number of tests
</p>
<form>
<input type="text" id="num_tests" value="">
<button id="trigger">
trigger it
</button>
</form>
</body>
https://jsfiddle.net/qr1z3d6e/2/
first in the jsfiddle.net link there are some errors such as imput instead of input.
I haven't tested it, but if I understand correctly is it something like this? try it.
<body>
<input id="myinput" type="text">00-99</input>
<button id="clickme">
</body>
<script>
var button = document.getElementById("clickme"),
count = 99;
var myInput = document.getElementById("myinput")
button.onclick = function(count){
count -= 1;
myInput.innerHTML = "00 " + count;
};
</script>

More efficient way to bind variables with buttons? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have 3 different buttons that when clicked on will increment specific variable by 1.
Instead of writing 3 different on clicks, is there more efficient way to do this?
I know i can use data attributes to bind button with correct element, but i don't know how to do that with variables.
var x1 = 0;
var x2 = 0;
var x3 = 0;
$('.btn1').on('click', function() {
x1 += 1;
$('#panel1').html(x1);
});
$('.btn2').on('click', function() {
x2 += 1;
$('#panel2').html(x2);
});
$('.btn3').on('click', function() {
x3 += 1;
$('#panel3').html(x3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1">#btn1</button>
<button class="btn2">#btn2</button>
<button class="btn3">#btn3</button>
An approach using id's or whatever attribute and arrays:
var x = [];
x[1] = 0;
x[2] = 0;
x[3] = 0;
$('.btn').on('click', function() {
var pos = $(this).attr("id");
x[+pos] += 1;
$('#panel'+pos).html(x[pos]);
});
in HTML:
<button class="btn" id="1">#btn1</button>
<button class="btn" id="2">#btn2</button>
<button class="btn" id="3">#btn3</button>
Give them the same class and make it one click listener and put a data attr on each button with the variable name and the panel name. something like this, put all the variables in one object so you can access them also if they are global variables you can access them like this window[variableName]
As always, use a function to abstract over duplicated code.
function counter(buttonSelector, outputSelector) {
var x = 0;
$(buttonSelector).on('click', function() {
x += 1;
$(outputSelector).text(x); // btw, don't use `html`
});
}
counter('.btn1', '#panel1');
counter('.btn2', '#panel2');
counter('.btn3', '#panel3');
You can further remove repetition by putting those calls (or just the function body) in a loop, and/or adjust your selectors appropriately, but for three calls it's not yet worth it.
you can use an array instead of multi variables.
now give all buttons a specific class like btn.
then :
var ar=[0,0,0];
$('.btn').on('click',function(){
var x=$(this).html(); //if text of buttons is #btn1,#btn2 , ....
var num=parseInt(x.substr(x.length - 1));
ar[num]++;
});
Store the count in data attributes instead of a variable.
$('button[data-out]').on('click', function() { // bind on every button
// $(document).on('click, 'button[data-out]', function() { // or use event delegation with one click event
var btn = $(this) // reference the element
var cnt = (btn.data('count') || 0) + 1 // read count or default to zero and increment
btn.data('count', cnt) // update the count data attribute
$(btn.data('out')).text(cnt) // update your text output
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1" data-out="#panel1">#btn1</button>
<button class="btn2" data-out="#panel2">#btn2</button>
<button class="btn3" data-out="#panel3">#btn3</button>
I would either give your buttons a common class, or you could just bind your click event to the button element if you don't have others you need to worry about. Then use the index of the button being clicked to match it to the div you want to change. Essentially a one-liner:
$('button').on('click', function() {
$('div').eq($(this).index('button')).html(+$('div').eq($(this).index('button')).text() + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1">#btn1</button>
<button class="btn2">#btn2</button>
<button class="btn3">#btn3</button>
Parts explained:
$(this).index('button') gets the index of the button among the button elements. See .index().
$('div').eq($(this).index('button')).text() select the div using the index above. See .eq()
+ converts the string content of the div to a number. Also could have used parseInt()
Store the variables as properties of an object.
Use a data-* attribute on each button to store what variable it is
supposed to match.
Bind all buttons to one handler.
In the handler, check the clicked button's data- attribute and
update the associated Object property as needed.
let variableObject = {
x1:0,
x2:0,
x3:0
}
$('.btn').on('click', function() {
variableObject[this.dataset.key]++;
$('#panel' + this.dataset.key.charAt(1)).text(variableObject[this.dataset.key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button class="btn" data-key="x1">#btn1</button>
<button class="btn" data-key="x2">#btn2</button>
<button class="btn" data-key="x3">#btn3</button>
Having said that, do you really need the variables in the first place? Why can't you just adjust the HTML content directly and anytime you may need that data, simply extract it.
$('.btn').on('click', function() {
// Get current value of associated panel
let current = $("#" + $(this).data("key")).text();
// Set text of associated panel to old value plus one
$("#" + $(this).data("key")).text(++current);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button class="btn" data-key="panel1">#btn1</button>
<button class="btn" data-key="panel2">#btn2</button>
<button class="btn" data-key="panel3">#btn3</button>
Here is a version that generates the initial variables too, so it should be scalable.
bindVars = {}
$('[data-bind-id]').each(function() {
var xi = "x" + $(this).data('bind-id');
var pi = "#panel" + $(this).data('bind-id');
bindVars[xi] = 0;
$(this).on('click', function() {
bindVars[xi] += 1;
$(pi).text(bindVars[xi]);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button data-bind-id='1'>#btn1</button>
<button data-bind-id='2'>#btn2</button>
<button data-bind-id='3'>#btn3</button>
Something like this
vars = {
'x1':0,
'x2':0,
'x3':0
}
$('.btn').on('click', function(){
var vn = $(this).data('varname');
var ps = $(this).data('panel-selector');
vars[vn] += 1;
$(ps).text(vars[vn]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn" data-varname='x1' data-panel-selector='#panel1'>#btn1</button>
<button class="btn" data-varname='x2' data-panel-selector='#panel2'>#btn2</button>
<button class="btn" data-varname='x3' data-panel-selector='#panel3'>#btn3</button>
UPD:
For variables can use eval, but this not secure and useless. Do not use this, it's just for demonstration.
var x1 = 0;
var x2 = 0;
var x3 = 0;
$('.btn').on('click', function(){
var vn = $(this).data('varname');
var ps = $(this).data('panel-selector');
eval(vn + '+=1');
$(ps).text(eval(vn));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn" data-varname='x1' data-panel-selector='#panel1'>#btn1</button>
<button class="btn" data-varname='x2' data-panel-selector='#panel2'>#btn2</button>
<button class="btn" data-varname='x3' data-panel-selector='#panel3'>#btn3</button>
You can add every button HTML onclick event and create one function.
function add() {
this.innerHTML(parseInt(this.innerHTML()) + 1);
}
<button onclick=add()>1</button>
<button onclick=add()>1</button>
<button onclick=add()>1</button>

how to generate dynamic id using variable and delete the element using the same variable

Hi i am creating a small web application where if i click create element it should create new button using variable x. When i click the remove element it should delete from the last element until no new element should be there.
But the problem is when i click create element i am not able to add id to the newly created element dynamically.At the same time how can i delete using variable as id to delete new element.
Here element means Button
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
var x=1;
var fd,d;
$(document).ready(function(){
$("#r").click(function(){
$("#fd").remove();
});
$("#c").click(function(){
var txt="<div id='fd"+x+"'><button > New Button </button></div>";
x++;
$("#d").after(txt);
});
});
</script>
</head>
<body>
<button id="c">Create Element</button>
<button id="r">Remove Element</button>
<br> <br>
<div id="fd">
<button id="d">First Element</button>
</div>
<br>
</body>
</html>
I have included the image where i am able to create new element but not able to delete it
Thanks in advance.
Add a common class to each new element and then use last() filter with that class to remove the last one
var x = 1;
var fd, d;
$(document).ready(function() {
$("#r").click(function() {
$(".button").last().remove();
});
$("#c").click(function() {
var txt = "<div class='button' id='fd" + x + "'><button > New Button </button></div>";
x++;
$("#d").after(txt);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="c"> Create Element </button>
<button id="r"> Remove Element </button> <br>
<br>
<div id="fd">
<button id="d"> First Element </button>
</div>
<br>

How to add JavaScript to button where it will generate another button linking to another page?

i am trying to use JavaScript where i can click on a button and it will generate a button above it so for example i have the first button called add additional:
<a href"#"><button type="button">Add Additional</button></a>
When this button is clicked and it will generate another button where i want it to be displayed the below:
<td>
Name
</td>
<td>
<button type="button">Choose another thing</button>
</td>
and is it possible to repeat this process like generating more of the 2nd button "Choose Another thing"
i hope this ins't too confusing
I think you are looking for something like this!! Just add a script so that whenever you click on the button it will execute it and create more buttons.
<!DOCTYPE html>
<html>
<body>
<p>Click the "Add Additional" button to create a BUTTON element with a "Choose Another Thing" text.</p>
<button onclick="myFunction()" type="button">Add Additional</button>
<script>
function myFunction() {
var x = document.createElement("BUTTON");
var t = document.createTextNode("Choose another thing");
x.appendChild(t);
document.body.appendChild(x);
}
</script>
</body>
</html>
I think this is the elegant way.
function appendButton(textContent, selector) {
var button = document.createElement('button');
button.classList.add('any');
button.innerHTML = textContent;
var selectedElement = document.querySelector(selector);
return selectedElement.appendChild(button);
}
// Call this function from wherever u like
// appendButton('click here', '.container');
<div class="container">
<button onclick="appendButton('click here', '.container')">
Click me
</button>
</div>
Run this you will get your solution
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var a=document.createElement("a");
a.setAttribute("href","secondpage.html");
var btn=document.createElement("BUTTON");
var text=document.createTextNode("Choose another thing");
btn.appendChild(text);
a.appendChild(btn);
document.body.appendChild(a);
}
</script>
</head>
<body>
<a href"#"><button type="button" onclick="myFunction()">Add
Additional</button></a>
</body>
</html>
Give an id/class for a division append to it.
<div id='my_id' >
<td>Name</td>
<td><button>click</button></td>
</div>
When you click on addMore button write a function to append it to my_id
function onclickforaddbutton(){
id = document.getElementById('my_id');
var data = prompt("Enter something"); //where you can get data from user
id.innerHTML+="<td>"+data+"</td><td><button>Something</button></td>";
}
You need to first decide (container) where to add a new row. Then on click of add button, you can create a row with two columns, for the name and the new button, and append that row as a child of the container.
Here's how you can do it.
var count = 1;
var name = 'Generated Name';
function addNewRow() {
var container = document.getElementById('container');
var newRow = document.createElement('tr');
newRow.innerHTML = "<td>" + name + (count++) + "</td><td><button>Choose another thing</button></td>"
container.appendChild(newRow);
}
<html>
<head></head>
<body>
<div style="padding: 2rem;">
<table id="container">
</table>
</div>
<button onclick="addNewRow();">Add Additional</button>
</body>
</html>

access the exact view in a raw using js

My view has a button and the view is looped.so it has raws.
when i click the button of a single raw i need to color that button.
so i added a onclick="select_Button(<?php echo $rawID?>)" to the raw's button in my view
select_Button is my funtion in js
function select_Button(rawNumberOfVote) {
var RawNumber = rawNumberOfVote;
alert ("Form submitted successfully" + RawNumber);
var upVote = document.getElementById("up_vote");
upVote.style.background = "green";
}
like above i send the rawID to the funtion.
how can i edit this line to accept the view called up_vote in that particular raw id that i got from parameter.
var upVote = document.getElementById("up_vote");
becuz if i only use this line it will color the first raw's button instead the one i wanted
Thank you
you can use data attribute in your html referencing to this page and this page. and retraive with this this jquery code snippet:
$("[data-test ='my value']")
or this code snnipet in javascript:
document.querySelectorAll(".example").find(function(dom){
return dom.dataset.test == "expected-value"
});
Update:
accourding to this page querySelectorAll return nodeList and NodeList are not array and we cannot use find method so I change my answer to this code:
<html>
<body>
<div class="post" data-key="1">
<lable>test</lable>
<button type="button" onclick="upvote(1)">up vote</button>
</div>
<div class="post" data-key="2">
<lable>test</lable>
<button type="button" onclick="upvote(2)">up vote</button>
</div>
<div class="post" data-key="3">
<lable>test</lable>
<button type="button" onclick="upvote(3)">up vote</button>
</div>
</body>
</html>
<script type="text/javascript">
var upvote = function(id) {
var nodes = document.querySelectorAll(".post");
console.log(nodes.length);
for(i = 0 ; i < nodes.length ; i++){
console.log(nodes[i].dataset.key);
if (nodes[i].dataset.key == id)
nodes[i].style.backgroundColor = "red";
}
};
</script>

Categories

Resources