Suppose to have more buttons:
<input type="button" id="number_1" value="A">
<input type="button" id="number_2" value="B">
<input type="button" id="number_n" value="N">
I want get click when the user click on them. So I would use something like this code (without Jquery):
var button=document.getElementById('[id^=number]');
button.onclick=function(){alert("HIII")};
But this code is not work. Anyone can help?
Attribute selectors
document.querySelectorAll()
Array.prototype.forEach()
Function.prototype.call()
EventTarget.addEventListener()
Array.prototype.forEach.call(document.querySelectorAll('[id^=number_]'), function (element) {
element.addEventListener('click', function (e) {
alert(e.target.id);
});
});
<input type="button" id="number_1" value="A">
<input type="button" id="number_2" value="B">
<input type="button" id="number_n" value="N">
'[id^=number]'
That's an attribute selector, not an ID and not a regular expression. You shouldn't pass it to getElementById.
You can use selectors with querySelectorAll
var buttons = document.querySelectorAll('[id^=number]');
but that returns a NodeList, not a single element, so you have to loop over it:
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.onclick=function(){alert("HIII")};
}
and there is no point in creating a new function each time you go around the loop, create one and reuse it:
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.onclick = myFunction;
}
function myFunction () {
alert("HIII");
}
Related
I am trying to loop a radio-button form but with no success.
Despite the length of the form is 3 (same as number of radiobuttons) I can not access individual elements.
The purpose is to change the text. Its works If I want to access the first element:
var child = form.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
this returns the first radiobutton text.
But if I create a loop out of this
function getRadioBInfo() {
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var iForm = form[i];
var child = iForm.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
}
}
.. I get I TypeError: child is null
What is wrong with this code?
HTML
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
I think you are looking for something like following.
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var child = form.getElementsByTagName('input')[i];
alert(child.nextSibling.nextSibling.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
Since you've tagged jquery, you could use:
$('[name=delivering']).each( function() {
alert( $(this).find('label').html() );
});
To get the label followed after the radio button you could try this:
function getRadioBInfo() {
var form = document.getElementById("myform");
var radios = form.querySelectorAll('input[type=radio]');
var i;
for (i = 0; i < radios.length; i++) {
var radio = radios[i];
console.log(radio.nextSibling.innerHTML);
}
}
getRadioBInfo();
pitfall: there shouldn't be whitespace between the radio or the button. Otherwise nextSibling returns text and not the label
demo
Why you are not getting by name
Try this
function getRadioBInfo() {
var arrRadioBtns = document.getElementsByName("delivering");
for (var i = 0; i < arrRadioBtns.length; i++) {
var btn = arrRadioBtns[i];
alert (btn.value);
}
}
Working Example
form[i] contains only radio buttons.If You want to take the labels Try using
var lbl = document.getElementsByTagName('label');
for (var i=0;i < lbl.length; i++){ lbl[i].innerHTML = 'radio' + i; }
and loop through the labels and change the text
Couple of observation
var form = document.getElementById("myform");
form will not be an array,Instead it will be a String,So you are iteration of the string.length;
You can use doucment.getElementsByName to get all radio buttons with common name
Hope this snippet will be useful
function getRadioBInfo() {
//Retun collection of radio button with same name
var _getRadio = document.getElementsByName("delivering");
// loop through the collection
for(var i = 0;i<_getRadio.length;i++){
//nextElementSibling will return label tag next to each radio input
console.log(_getRadio[i].nextElementSibling.innerHTML)
}
}
getRadioBInfo();
Jsfiddle
I am trying to show error messages below an array of textboxes that I have selected using Javascript. The error messages are being put by creating a new span element and using the insertBefore() method. The span element is created in the function since I don't want to hard code it into the DOM. The span messages do show but each time I submit the form, they are appended over and over again. I'd like to show the span messages only once and each time the form is submitted, they are shown once only. Below is my code.
HTML
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" />
<input type="text" name="2" class="textbox" />
<input type="text" name="3" class="textbox" />
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
JAVASCRIPT
<script>
var slideshow = document.querySelector('.slideshow');
// var span = document.createElement('span');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function(e)
{
e.preventDefault();
for( var i=0; i<inputs.length; i++ )
{
var span = document.createElement('span');
(function(index)
{
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
</script>
Each time I submit, I'd like the error messages to be shown below the textbox and not appended over and over again. They should be shown just once and I'd like to do this without using jQuery or any sort of library.
I rewerite your example to create available 3 span tags instead of crate them in code. If there are some errors, populate them to span rather than creating/deleting the spans in code.
var slideshow = document.querySelector('.slideshow');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
(function (index) {
document.getElementsByTagName('span')[index]
.innerHTML = 'error ' + index;
})(i);
}
}, false);
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" /><span></span>
<input type="text" name="2" class="textbox" /><span></span>
<input type="text" name="3" class="textbox" /><span></span>
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
Hope this help.
Just do a check before you insert. Here is one way to do it.
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
if (inputs[index].nextElementSibling.tagName !== 'SPAN')
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
You have to wait for page to be load, the you should run JavaScript.
PageLoad Event : window.onload=function(){}
Code :
<script type="text/javascript">
window.onload = function () {
var slideshow = document.querySelector('.slideshow');
var form = document.getElementById('form');
var inputs = document.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
}
</script>
Put your code in window.onload event.
I have three different boxes which all have a button inside.
I want to register an onclick event for every button with a specific data attribute.
I've started a jsfiddle, any suggestions?
http://jsfiddle.net/mwils/w6gofb30/
var buttons = document.querySelectorAll("button[data-donation]");
for (i = 0; i < buttons.length; i++) {
document.querySelectorAll("button[data-donation]")[i].onclick = console.log(buttons[i]);
}
function letsGo(init) {
var input = document.body.querySelector("input[name='amount']"),
amount = parseInt(input.value, 10) * 100,
url = "https://donate.shelter.org.uk/b?cid=152&freeamount=1&amount=";
if (input.value === '' || parseInt(input.value, 10) >= 0) {
window.location.href = url + init * 100;
} else {
window.location.href = url + amount;
}
}
<div class="shopping-item">
<p><span>£33</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£33" class="shopping-1-input">
<button data-donation="33" class="donate-button shopping-1-button">donate now</button>
</div>
<div class="shopping-item">
<p><span>£50</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£50" class="shopping-2-input">
<button data-donation="50" class="donate-button shopping-2-button">donate now</button>
</div>
<div class="shopping-item">
<p><span>£188</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£188" class="shopping-3-input">
<button data-donation="188" class="donate-button shopping-3-button">donate now</button>
</div>
While there are really many ways to do that i, most of the time, prefer a simple click delegation. I set that on elements that contain the buttons(could be the window or document.body itself).
To make it simple i show you that with a container first.
<div id="container">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
here is the js
document.getElementById('container').onclick=function(e){
if(e.target.nodeName=='BUTTON'){
alert(e.target.textContent);
}
}
What does this???
if i click on the container it checks if the target element is a button.
if yes it alerts the textContent of the button. simple right?
Doing so you avoid alot of extra variables.
In your case
document.onclick=function(e){
if(e.target.dataset['donation']){
alert(e.target.dataset['donation']);
}
}
shorter
document.onclick=function(e){
e=e.target.dataset; // reuse the variable e
!e['donation']||alert(e['donation']);
}
using
<button data-donation="33">donate now</button>
DEMO's
http://jsfiddle.net/j8xgqfmk/
Extra
button text followed by $ symbol done with css
http://jsfiddle.net/j8xgqfmk/1/
preceded by a £
http://jsfiddle.net/j8xgqfmk/2/
but returning the desidered value
Why?
No loops!!!
Only one event handler!!!!
Less variables!!!
Short code !!!
Faster then multiple complex eventhandlers.
other considerations:
var buttons = document.querySelectorAll("button[data-donation]");
for (i = 0; i < buttons.length; i++) {
document.querySelectorAll("button[data-donation]")[i].onclick=console.log(buttons[i]);
}
Should be written
var buttons=document.querySelectorAll('button[data-donation]'),
btnlength=buttons.length; //cache variables
for (var i = 0; i < btnlength; i++) { // var i
buttons[i].onclick=function(){ //buttons is already defined
console.log(this);
}
// and you need to pass a function to the onclick event
}
or even better
function handler(e){
console.log(this,e);
}
var btns=document.querySelectorAll('button[data-donation]'),
l=btns.length;
while(l--)btns[l].addEventListener('click',handler,false);
or the "Haters gonna hate" version
http://jsfiddle.net/Lbk1ueme/
var B=document.querySelectorAll('button[data-donation]'),
L=B.length,
I=0,
H=function(){console.log(this)};
for(;I<L;B[I++].onclick=H);
https://stackoverflow.com/a/21353032/2450730
if you have difficulties to understand that i can help you to write it based on your requests. For any other question just ask.
keep stuff simple
Loop through your element array (as you already are doing) and use addEventListener to bind the click event to each...
var buttons = document.querySelectorAll("button[data-donation]");
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(event) {
alert(this.getAttribute('data-donation')); // alert the value of data-donation attribute
});
}
<div class="shopping-item">
<p><span>£33</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£33" class="shopping-1-input">
<button data-donation="33" class="donate-button shopping-1-button">donate now</button>
</div>
<div class="shopping-item">
<p><span>£50</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£50" class="shopping-2-input">
<button data-donation="50" class="donate-button shopping-2-button">donate now</button>
</div>
<div class="shopping-item">
<p><span>£188</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£188" class="shopping-3-input">
<button data-donation="188" class="donate-button shopping-3-button">donate now</button>
The problem is you are not attaching events correctly to the element. You are assigning console.log and not a function to it. Seconds querySelectorAll is expensive. You should not keep looking things up in a loop. Create a variable and store the live html node collection it returns into it.
var btns = document.querySelectorAll("button[data-donation]");
for (var i=0; i<btns.length; i++) {
btns[i].onclick = function() {
console.log(this);
console.log(this.getAttribute("data-donation"));
}
}
function letsGo(init) {
var input = document.body.querySelector("input[name='amount']"),
amount = parseInt(input.value, 10) * 100,
url = "https://donate.shelter.org.uk/b?cid=152&freeamount=1&amount=";
if (input.value === '' || parseInt(input.value, 10) >= 0) {
window.location.href = url + init * 100;
} else {
window.location.href = url + amount;
}
}
<div class="shopping-item">
<p><span>£33</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£33" class="shopping-1-input">
<button data-donation="33" class="donate-button shopping-1-button">donate now</button>
</div>
<div class="shopping-item">
<p><span>£50</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£50" class="shopping-2-input">
<button data-donation="50" class="donate-button shopping-2-button">donate now</button>
</div>
<div class="shopping-item">
<p><span>£188</span> could help a family find and keep a home</p>
<input type="number" name="amount" placeholder="£188" class="shopping-3-input">
<button data-donation="188" class="donate-button shopping-3-button">donate now</button>
</div>
You've got the selector right already, i.e. var buttons = document.querySelectorAll("button[data-donation]") is pulling in all the buttons having data-donation, but there's no need to do another querySelectorAll inside your loop, you just need to reference each button in your result with buttons[i].
Your other mistake is setting onclick = console.log(), instead of onclick = function() { console.log() }. So all you need to change to get it working is:
var buttons = document.querySelectorAll("button[data-donation]");
for (i = 0; i < buttons.length; i++) {
var button = buttons[i];
buttons[i].onclick = function() { console.log(button) };
}
http://jsfiddle.net/w6gofb30/4/
document.querySelectorAll("button[data-donation]").every(function(e,i,a){
e.addEventListener("click", function(){
console.log(this);
console.log(this.getAttribute("data-donation"));
}, false);
});
but before this u need:
NodeList.prototype.every = function(f){
for(var k=0;k<this.length;k++)
f(this[k],k,this);
}
http://jsfiddle.net/sa0ezut7/
Here are my 2 radios buttons :
<input type="radio" name="sex" id="Button1" class="Button"/>
<input type="radio" name="sex" id="Button2" class="Button"/>
When I call a function that countains :
document.getElementById('Button2').checked = false;
It unchecks the Button2. But I want to uncheck it by using the class
And when the function contains :
document.getElementsByClassName('Button').checked = false;
It does not uncheck the Button2
Why and what is the solution ?
Thank you. :)
getElementsByClassName() returns a collection (like an array). So you would actually have to do
document.getElementsByClassName('Button')[1].checked = false;
But you can't be sure that your Button2 is the second element in the array if you have more elements with class Button.
you must iterate over the class elements !
var elements=document.getElementsByClassName('Button');
Array.prototype.forEach.call(elements, function(element) {
element.checked = false;
});
getElementsByClassName returns a node list (which is like an array) not an element.
If you want to do something to every element in the node list, then you have to loop over it and do the thing on each item in the list.
var node_list = document.getElementsByClassName('Button');
for (var i = 0; i < node_list.length; i++) {
node_list[i].checked = false;
}
document.getElementsByClassName returns an nodelist (kind of like an array of these elements)of elements of that class name. So you should cycle through it and change the checked status of each element.
For a generic approach (you can have as many check boxes as you like), use this code.
var allButtons = document.getElementsByClassName("Button");
for (i=0; i<allButtons.length; i++) {
allButtons[i].checked = false;
}
If you are going to have only 2 elements, you can use
var allButtons = document.getElementsByClassName("Button");
for (i=0; i<2; i++) {
allButtons[i].checked = false;
}
or
var allButtons = document.getElementsByClassName("Button");
allButtons[0].checked = false;
allButtons[1].checked = false;
You are calling document.getElementsByClassName('Button').checked = false; when it should be document.getElementsByClassName('Button')[1].checked = false;
getElementsByClassName() returns an array
function unCheck(){
document.getElementsByClassName('Button')[1].checked = false;
}
<input type="radio" name="sex" id="Button1" class="Button" />
<input type="radio" name="sex" id="Button2" class="Button" checked/>
<input type="button" value="Uncheck Radio" onclick="unCheck()"/>
I want to Simulate a button click via JavaScript using a button's value, not its id.
Here is the code using the button id
<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">
I've tried getElementByValue('Button') but it didn't work.
Here's how I'd do it using jQuery:
http://jsfiddle.net/skilldrick/R27rQ/1/
$('input[type=checkbox]').click(function () {
$('input[value=Button]').click();
});
but as Senad said, IDs are much better-suited for this type of thing.
<script type="text/javascript">
function getButtonByValue(value) {
var els = document.getElementsByTagName('input');
for (var i = 0, length = els.length; i < length; i++) {
var el = els[i];
if (el.type.toLowerCase() == 'button' && el.value.toLowerCase() == value.toLowerCase()) {
return el;
break;
}
}
}
</script>
<input type="checkbox" onClick="getButtonByValue('Button').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">
jsfiddle example
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'button' && buttons[i].value == val)
{
buttons[i].click();
break; //this will exit for loop, but if you want to click every button with the value button then comment this line
}
}
}
this is solution...
HTML
<input type="checkbox" onClick="clickButton('Button');">Check the box to simulate a button click
But its best to find element by its ID