how to index inside onclick in javascript - javascript

I have simple 5 buttons like this:
<button class="btn btn-success">Button 1</button>
<button class="btn btn-success">Button 2</button>
<button class="btn btn-success">Button 3</button>
<button class="btn btn-success">Button 4</button>
<button class="btn btn-success">Button 5</button>
I have this corresponding javascript code:
document.addEventListener("DOMContentLoaded",function(){
var button = document.getElementsByClassName('btn');
for (var i = 0; i < button.length; i++) {
button[i].onclick = function(){
console.log("button " + i)
}
}
},false)
I want to index i for button array inside onclick, for purpose such as button[i].classList.add("something"), I don't want to use "this" like this.classList.add("something"). How can I do that?, thanks

try to
const buttons = document.querySelectorAll(".clickme");
var count = 0;
buttons.forEach(btn => {
btn.addEventListener("click", (e) => {
const index = Array.from(buttons).indexOf(e.target);
alert(index);
});
});
I found it on https://www.mejorcodigo.com/p/20019.html

Related

How to get id of a button from a group of buttons on click event using Pure Javascript

I am trying to get the Id of a button for DOM manipulation. I have a group of buttons and I want to get Id of only the button which is clicked.
My Code is:-
<div class="row mb-5" id="widthRow">
<div class="col-md-12 mx-auto">
<p class="text-info font-weight-bold">Width :-</p>
<button class="btn btn-sm btn-success w" id="200">200px</button>
<button class="btn btn-sm btn-success w" id="400">400px</button>
<button class="btn btn-sm btn-success w" id="600">600px</button>
<button class="btn btn-sm btn-success w" id="800">800px</button>
</div>
</div>
I tried searching on stack overflow and got an answer with code:-
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}
});
But when I use it on my page, I get the error:-
https://imgur.com/a/cnLrVGp.
Note:- (I also used this code with getElementsByClassName. )
I tried searching for this error also. And some said that DOM is not loaded before manipulation. So, I added defer to script and also added
window.addEventListener("DOMContentLoaded", function() {}
But nothing helped. Kindly help. Thanks in advance.
Probably you are executing your code before the DOM is fully loaded. You can either place the code at the bottom of the body or wrap your code with DOMContentLoaded:
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Please Note: As getElementsByTagName() returns HTMLCollection which maintains 0 based indexing, you are iterating your loop more than the length of buttons, change <= to <.
<script>
document.addEventListener('DOMContentLoaded', (event) => {
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (let i = 0; i < buttonsCount; i++) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}
});
</script>
<div class="row mb-5" id="widthRow">
<div class="col-md-12 mx-auto">
<p class="text-info font-weight-bold">Width :-</p>
<button class="btn btn-sm btn-success w" id="200">200px</button>
<button class="btn btn-sm btn-success w" id="400">400px</button>
<button class="btn btn-sm btn-success w" id="600">600px</button>
<button class="btn btn-sm btn-success w" id="800">800px</button>
</div>
</div>

Simple calculator in html/javascript

I'm trying to make a calculator with html and JavaScript. After clicking on the button i'm trying to insert the number into my div. When i do so the default '0' disappears and it does not insert anything at all.
function copy(event) {
var newValue = event.target.value;
document.querySelector("#display").innerHTML = newValue;
}
var textfield = document.querySelector("#btn_7");
textfield.addEventListener("click", copy);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="frame">
<div id="display">0</div>
<button id="btn_7">7</button>
<button id="btn_8">8</button>
<button id="btn_9">9</button>
<button id="btn_div">/</button>
<button id="btn_4">4</button>
<button id="btn_5">5</button>
<button id="btn_6">6</button>
<button id="btn_prod">*</button>
<button id="btn_1">1</button>
<button id="btn_2">2</button>
<button id="btn_3">3</button>
<button id="btn_min">-</button>
<button id="btn_clear">C</button>
<button id="btn_0">0</button>
<button id="btn_eq">=</button>
<button id="btn_plus">+</button>
</div>
If I add a string to newValue variable it shows in my div. So it means like when I press on the button it doesnt give anything to the div. Is there a way to solve this?
And about var textfield = document.querySelector("#btn_7");
For now I have to make this for each button and thats will take a lot of rows is there a better way to do so?
Buttons don't have a default attribute value, so in this case use the attribute textContent.
I recommend you to use a hidden input to store the values or you can also use data-attributes.
For now i have to make this for each button and that will take alot of rows is there a better way to do so?
You can use the function document.querySelectorAll(selector) and loop over it to bind the specific event.
function copy(event) {
var newValue = event.target.textContent;
document.querySelector("#display").innerHTML = newValue;
}
Array.prototype.forEach.call(document.querySelectorAll('button'), function(b) {
b.addEventListener("click", copy);
});
<div id="frame">
<div id="display">0</div>
<button id="btn_7">7</button>
<button id="btn_8">8</button>
<button id="btn_9">9</button>
<button id="btn_div">/</button>
<button id="btn_4">4</button>
<button id="btn_5">5</button>
<button id="btn_6">6</button>
<button id="btn_prod">*</button>
<button id="btn_1">1</button>
<button id="btn_2">2</button>
<button id="btn_3">3</button>
<button id="btn_min">-</button>
<button id="btn_clear">C</button>
<button id="btn_0">0</button>
<button id="btn_eq">=</button>
<button id="btn_plus">+</button>
</div>
try like this
$(function(){
$('button[id^="btn_"]').click(function(){
var display;
if($('.tmp').length > 0){
display = $('.tmp').text();
}else{
$( "<p class='tmp' style='display:none;'></p>" ).appendTo( "#frame" );
display = '';
}
switch($(this).text()){
case 'C' :
display = '0';
break;
case '=' :
display = eval(display);
break;
default :
display = display.concat($(this).text());
}
$('#display').text(display);
$('.tmp').text((display != '0') ? display : '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="frame">
<div id="display">0</div>
<button id="btn_7">7</button>
<button id="btn_8">8</button>
<button id="btn_9">9</button>
<button id="btn_div">/</button><br/>
<button id="btn_4">4</button>
<button id="btn_5">5</button>
<button id="btn_6">6</button>
<button id="btn_prod">*</button><br/>
<button id="btn_1">1</button>
<button id="btn_2">2</button>
<button id="btn_3">3</button>
<button id="btn_min">-</button><br/>
<button id="btn_clear">C</button>
<button id="btn_0">0</button>
<button id="btn_eq">=</button>
<button id="btn_plus">+</button>
</div>
Here is to select value and replace html of display div. You need to do some extra stuff to achieve what is your desired output.
var display = $('#display');
$('.btn').click(function(e) {
var btn = e.target;
display.html(btn.id);
});
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<div id="frame">
<div id="display">0</div>
<button class="btn" id="btn_7">7</button>
<button class="btn" id="btn_8">8</button>
<button class="btn" id="btn_9">9</button>
<button class="btn" id="btn_div">/</button>
<button class="btn" id="btn_4">4</button>
<button class="btn" id="btn_5">5</button>
<button class="btn" id="btn_6">6</button>
<button class="btn" id="btn_prod">*</button>
<button class="btn" id="btn_1">1</button>
<button class="btn" id="btn_2">2</button>
<button class="btn" id="btn_3">3</button>
<button class="btn" id="btn_min">-</button>
<button class="btn" id="btn_clear">C</button>
<button class="btn" id="btn_0">0</button>
<button class="btn" id="btn_eq">=</button>
<button class="btn" id="btn_plus">+</button>
</div>

How to get the index of a list of buttons in jquery

I have a couple of buttons
<button id="btn-ok[1]" class="btn-ok"></button>
<button id="btn-failed[1]" class="btn-failed"></button>
<button id="btn-ok[2]" class="btn-ok"></button>
<button id="btn-failed[2]" class="btn-failed"></button>
<button id="btn-ok[3]" class="btn-ok"></button>
<button id="btn-failed[3]" class="btn-failed"></button>
And I am running differnt jquery functions for btn-ok and for btn-failed.
I would like to use the index number of the id. How can I obtain it?
<script>
$(document).ready(function() {
$('#btn-ok').click(function() {
console.log('I would like to print the index of the pressed button here. (i.e. 1,2,3)');
});
});
</script>
Use html5's data attributes and separate the index and status into separate elements - I added some teext to each button so it could be easily seen and then the click grabs the data-attributes and console.logs the values.
$(document).ready(function() {
$('.btn').click(function() {
var index = $(this).data('index');
var status = $(this).data('status')
console.log(index + ' / ' + status);
}); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button data-index="1" data-status ="ok" class="btn btn-ok">1 Ok</button>
<button data-index="1" data-status ="failed" class="btn btn-failed">1 Failed</button>
<button data-index="2" data-status ="ok" class="btn btn-ok">2 OK</button>
<button data-index="2" data-status ="failed" class="btn btn-failed">2 Failed</button>
<button data-index="3" data-status ="ok" class="btn btn-ok">3 OK</button>
<button data-index="3" data-status ="failed" class="btn btn-failed">3 Failed</button>
Create a collection of all those buttons to index against. Note that index() is zero based
var $buttons = $('.btn-ok, btn-failed').click(function(){
alert($buttons.index(this));
})
Or for more specifc target:
var $buttons = $('.btn-ok, btn-failed');
$('#btn-ok\\[1\\]').click(function(){
alert($buttons.index(this));
})
Or use data attributes instead of messing around with [] in ID
<button class="btn-ok" data-index="1"></button>
..
$('.btn-ok').click(function(){
alert($(this).data('index'));
})
HTML id's shouldn't use an index. Instead use a class to hold the selector and a data attribute to hold the other values you'll need like this:
The HTML:
<button class="btn-ok" data-index="1">Ok</button>
The JS:
$('.btn-ok').click(function() {
$(this).data('index');
});
The fiddle:
https://jsfiddle.net/kLvqe8dw/2/
did you mean to get id ?
$("button").click(function(){
alert($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn-ok[1]" class="btn-ok">ok[1]</button>
<button id="btn-failed[1]" class="btn-failed">failed[1]</button>
<button id="btn-ok[2]" class="btn-ok">ok[2]</button>
<button id="btn-failed[2]" class="btn-failed">failed[2]</button>
<button id="btn-ok[3]" class="btn-ok">ok[3]</button>
<button id="btn-failed[3]" class="btn-failed">failed[3]</button>

Dynamically generated button remove by onClick in jQuery

I have inserted button by onclick in a way that if you click on the button then it will append within <div id="article-tags"></div> just like the below image,
To create that, I have arranged the HTML code segment below:
<div id="article-tags">
</div>
<div>
<button type="button" data-id="1" data-name="tag" class="tag-item">tag</button>
<button type="button" data-id="2" data-name="tag2" class="tag-item"> tag2</button>
<button type="button" data-id="3" data-name="tag3" class="tag-item">tag3</button>
<button type="button" data-id="4" data-name="tag4" class="tag-item">tag4</button>
</div>
And the jQuery code segment is below,
$(".tag-item").click(function(){
var btnid = $(this).data("id");
var btnname = $(this).data("name");
$("#article-tags").append("<button type='button' class='tag-selected ntdelbutton'>"+ btnname +" <i class='fa fa-times-circle' aria-hidden='true'></i></button>");
$(this).css({"background-color": "#DFE2E5", "color": "#ababab"});
$(this).attr("disabled", true);
return false;
});
But right now, I would like to remove the button by onClick that is populated within
<div id="article-tags"></div>
I have tried to by using the following jQuery code segment below:
$(".tag-selected").click(function(){
$(this).remove();
});
or
$(".tag-selected").live("click", function() {
$(this).remove();
});
But neither is working. Please help me to solve this problem.
Try following code. Do you want to restore 'disabled': false attribute after removing specified element?
$(".tag-item").click(function() {
var btnid = $(this).data("id");
var btnname = $(this).data("name");
$("#article-tags").append("<button type='button' class='tag-selected ntdelbutton'>" + btnname + " <i class='fa fa-times-circle' aria-hidden='true'></i></button>");
$(this).css({
"background-color": "#DFE2E5",
"color": "#ababab"
});
$(this).attr("disabled", true);
$(".ntdelbutton").click(function() {
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article-tags">
</div>
<div>
<button type="button" data-id="1" data-name="tag" class="tag-item">tag</button>
<button type="button" data-id="2" data-name="tag2" class="tag-item"> tag2</button>
<button type="button" data-id="3" data-name="tag3" class="tag-item">tag3</button>
<button type="button" data-id="4" data-name="tag4" class="tag-item">tag4</button>
</div>
Here is an approach using plain javascript (rather than the jQuery library) and a dash of CSS:
var upperButtons = document.querySelectorAll('.upper button');
var lowerButtons = document.querySelectorAll('.lower button');
for (let i = 0; i < lowerButtons.length; i++) {
lowerButtons[i].addEventListener('click', function(){upperButtons[i].style.visibility = 'visible'; lowerButtons[i].setAttribute('disabled','disabled');}, false);
}
for (let i = 0; i < upperButtons.length; i++) {
upperButtons[i].addEventListener('click', function(){upperButtons[i].removeAttribute('style'); lowerButtons[i].removeAttribute('disabled');}, false);
}
.upper button {
visibility: hidden;
}
<div class="upper">
<button type="button">tag</button>
<button type="button">tag2</button>
<button type="button">tag3</button>
<button type="button">tag4</button>
</div>
<div class="lower">
<button type="button">tag</button>
<button type="button">tag2</button>
<button type="button">tag3</button>
<button type="button">tag4</button>
</div>

JavaScript - getElementsByClassName works for one function but not the other

I am trying to code a simple page where each click will change the pricing on the website using getElementsByClassName.
This is working :
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>
Not working after adding 1year():
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
function 1year() {
var price2 = document.getElementsByClassName("price");
price2[0].innerHTML = "$8";
price2[1].innerHTML = "$16";
price2[2].innerHTML = "$24";
price2[3].innerHTML = "$32";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>
Does anyone know why?
TIA.
A function or variable in JavaScript cannot start with a number.
Identifiers must start with either a dollar sign ($), an underscore (_) or a unicode character.
In your case,
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
All 3 functions are invalid.
Thanks to #Richard Hamilton, this is the full working code snipplet.
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
function annually() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$8";
price[1].innerHTML = "$16";
price[2].innerHTML = "$24";
price[3].innerHTML = "$32";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="annually()">1 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>

Categories

Resources