I need to change the background color for three buttons using Javascript. Below is the code:
<input type="button" id="btn" value="Box 1" onclick="changeColor(this)">
<input type="button" id="btn" value="Box 2" onclick="changeColor(this)">
<input type="button" id="btn" value="Box 3" onclick="changeColor(this)">
<script>
function changeColor(this) {
this.document.getElementById("btn").style.backgroundColor = "red";
}
</script>
It works well for first button(Box 1).
When I click the second and third buttons, the background color of first button changes.
But I need to change the background colors of respective buttons that I have clicked.
Can anyone please help me to know where I was wrong?
The issue is that you are using same id for all the buttons. Use class instead.
Also, this is a reserved keyword and since you're using it as parameter name causes an error.
function changeColor(elem) {
elem.style.backgroundColor = "red";
}
<input type="button" class="btn" value="Box 1" onclick="changeColor(this)">
<input type="button" class="btn" value="Box 2" onclick="changeColor(this)">
<input type="button" class="btn" value="Box 3" onclick="changeColor(this)">
Using this as a variable name causes a Javascript error, since this is a reserved keyword. Change this to the button variable (element in the snippet below) and pass it to your function.
Also - never set the same ID for multiple elements! This renders as an invalid HTML document.
Here's a working code snippet:
<input type="button" id="btn" value="Box 1" onclick="changeColor(this)">
<input type="button" id="btn" value="Box 2" onclick="changeColor(this)">
<input type="button" id="btn" value="Box 3" onclick="changeColor(this)">
<script>
function changeColor(element) {
element.style.backgroundColor = "red";
}
</script>
id need to be unique also in the function changeColor , this as an argument may not be relevant, you can provide any other name. In the function the argument elem will represent the context which has triggered the click event.
The the id from it and change it's style
function changeColor(elem) {
this.document.getElementById(elem.id).style.backgroundColor = "red";
}
<input type="button" id="btn1" value="Box 1" onclick="changeColor(this)">
<input type="button" id="btn2" value="Box 2" onclick="changeColor(this)">
<input type="button" id="btn3" value="Box 3" onclick="changeColor(this)">
Your function is always referencing the element with the id of btn, which all three of your inputs have.
Where you are passing (this) into your function, you should instead pass in the button's id.
In your function, you can then reference the id that was passed in:
function changeColor(id) {
document.getElementById(id).style.backgroundColor = "red";
}
Then, just change your onclicks to something more like onclick="changeColor('btn1')".
You may also want to consider adding a class to the element, as opposed to adding inline styling. This gives you more flexibility:
function changeColor(id) {
let btn = document.getElementById(id);
btn.classList.add('red-button');
}
Then just add some CSS:
.classList {
background-color: red;
}
Replace this into your param with whatever you want. Because this is a keyword which represents a context. Here it is window object.
function changeColor(element) {
element.style.backgroundColor = "red";
}
You should change the id to class because id has to be unique.
Try it like this:
<input type="button" class="btn" value="Box 1" onclick="changeColor(this)">
<input type="button" class="btn" value="Box 2" onclick="changeColor(this)">
<input type="button" class="btn" value="Box 3" onclick="changeColor(this)">
<script>
function changeColor(this) {
element.style.backgroundColor = "red";
}
</script>
Here is a working snippet with 2 different solutions, the one you wanted to achieve, and a better one, where I suggest you to not use inline Javascript:
(See comments in my code)
function changeColor(elm) { // "this" is reserved keyword, changed to "elm"
elm.style.backgroundColor = "red"; // No need for getElement here, we already have it, it's "elm"
}
// Better solution: for no use of inline JS, do the following :
var btns = document.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
this.style.backgroundColor = "red";
});
}
<!-- I guess this one is waht you wanted to achieve -->
<input type="button" value="Box 1" onclick="changeColor(this)">
<!-- Changed id to class for the 2 next, to make it work without inline JS -->
<input type="button" class="btn" value="Box 2">
<input type="button" class="btn" value="Box 3">
Hope it helps.
Related
Is there an easy way to link both functions and variables to a DOM element?
Below is an example of how this might work:
function logfunc(value){
console.log(value)
}
document.getElementById('logger1').onclick = logfunc('this is button1')
document.getElementById('logger2').onclick = logfunc('this is button2')
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">
Expected result:
'This is Button x' on button click.
There are many ways to give a callback/listener function data
One would be to use a closure. Change logfunc to return a function the "closes" over value.
see How do JavaScript closures work?
function logfunc(value){
return function() {
console.log(value);
}
}
document.getElementById('logger1').onclick = logfunc('this is button1')
document.getElementById('logger2').onclick = logfunc('this is button2')
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">
Otherwise you can put data in the DOM in various ways. DOM data is generally limited to strings, variables are not.
function logfunc(value){
return function() {
console.log(value);
}
}
document.getElementById('logger1').onclick = logfunc({name: 'Joe', age: 12})
document.getElementById('logger2').onclick = logfunc({name: 'Bob', age: 14})
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">
Otherwise if you want to put data in the DOM itself then you're mostly limited to strings. You can reference the value attribute in your code
function logfunc(e){
console.log(e.target.value);
}
document.getElementById('logger1').onclick = logfunc;
document.getElementById('logger2').onclick = logfunc;
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">
But value is not available on all DOM elements.
You can instead use dataset attributes to store arbitrary data on elements
// select all elements that have a "data-name" attribute
document.querySelectorAll('*[data-name]').forEach((elem) => {
// on each element add a click handler (better than using onclick!)
elem.addEventListener('click', () => {
// access the dataset attributes
console.log(elem.dataset.name, elem.dataset.major);
});
});
div[data-name] {
background: pink;
display: inline-block;
margin: 0.25em;
padding: 0.25em;
}
<div data-name="Bill" data-major="dance">Button 1</div>
<div data-name="Mary" data-major="science">Button 2</div>
The snippet below uses .addEventListener() to do something when you click the button, and .value to get the value of the element. The this is a keyword that in this case means the button you clicked. In other words, since the button you clicked is represented by document.getElementById('logger1') in the DOM, you can simply use this to represent that.
Also I don't know if it was an actual error, or a typo, but you spelled function like fucntion. I fixed that error for you in the snippet.
And finally, you used .onclick. That works, and is valid code, but it isn't the best way to do it. Since I won't be going into this (this isn't the main question), you might want to go here to find out more.
function logfunc(value) {
console.log(value)
}
document.getElementById('logger1').addEventListener("click", function() {
logfunc('this is ' + this.value);
});
document.getElementById('logger2').addEventListener("click", function() {
logfunc('this is ' + this.value);
});
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">
The function that is bind to an element will has a scope that "this" is refering to the element self. so you can get the value of the input by "this.value"
function logfunc(){
console.log('this is ' + this.value);
}
document.getElementById('logger1').onclick = logfunc
document.getElementById('logger2').onclick = logfunc
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">
I have two textfields with different IDs as shown
<textarea id="textfield">Hello World</textarea>
This will be updated with the content of the first textarea
<input id="messageID">
This is my script
<script type=text/javascript>
function() {
var value = document.getElementById("textfield").value;
document.getElementById('#messageID').val(value);
alert(value);
}
</script>
This is the onclick button and nothing happens when I click it
<button onclick="myfunction()" type="button" class="btn btn-danger" id="button">Alert</button>
Kindly assist!
Three things I'm seeing wrong:
.val(value); is a jQuery' method, not javascript... you should change it to .value = value;
to call onclick="myfunction()" you should name it: var myfunction = function(){
The document.getElementById() method doesn't need sharp # before the name.
Hope it helps.
Try something like this:
function myfunction() {
var value = document.getElementById("textfield").value;
document.getElementById('messageID').value=value;
alert(value);
}
<input type="button" value="Alert" onclick="myfunction()" type="button" class="btn btn-danger" id="button"/>
<textarea id="textfield">Hello World</textarea>
<input id="messageID">
The most important catch is whenever you declare function on button click you should define that function inside javascript.
<script type=text/javascript>
function myfunction() {
var value = document.getElementById("textfield").value;
document.getElementById("messageID").value = value;
alert(value);
}
</script>
<textarea id="textfield">Hello World</textarea>
<input id="messageID">
<button onclick="myfunction()" type="button" class="btn btn-danger" id="button">Alert</button>
Here you go a working fiddle
https://jsfiddle.net/blazeeboy/fNPvf/
Its inner Html you are trying to get
<textarea id="textfield">Hello World</textarea>
<input id="messageID"/>
<button type="button" class="btn btn-danger" id="button" onclick="myfunction()">Alert</button>
function myfunction(){
alert(1);
var v = document.getElementById("textfield").innerHTML ;
document.getElementById('messageID').innerHTML = v;
alert(v);
}
I try to make a line graph in Canvas,
I had a main.html and script in main.js (dosen`t matter what is inside - I will paste only the end of the code).
This is the end of main.js - plot,plot2,plot3 is a function to draw a line.
document.getElementById("button").onclick = plot; ///drawing line 1
document.getElementById("button2").onclick = plot2; //drawing line 2
document.getElementById("button3").onclick = plot3; //drawing line 3
document.getElementById("button4").onclick = plot4; //drawing ....
document.getElementById("button5").onclick = plot5; //drawing ...
In main.html i had
<input type="submit" name="button" id="button" value="Rysuj" /></td>
<input type="submit" name="button2" id="button2" value="Rysuj2" /></td>
<input type="submit" name="button3" id="button3" value="Rysuj3" /></td>
<input type="submit" name="button4" id="button4" value="Rysuj4" /></td>
<input type="submit" name="button5" id="button5" value="Rysuj5" /></td>
And when I press buttons Rysuj, Rysuj2, Rysuj3 all are drawing.
But i would like to make just 1 button like a 'Rysuj' and i try to change a ID after click but something dosn`t work.
In main.html I wrote:
<script language="text/javascript">
function something(){
document.getElementById("button").id = "button2"
}
</script>
<input type="button" onclick="something()" value="Rysuj" id="button">
What i should do to Make just a 1 Button which after click will change ID to button2, after next click to button3 etc ?
How about change draw line function of the first button after each click?
var arr = ['plot','plot2','plot3','plot4','plot5'];
var count=0;
document.getElementById("button").onclick = something;
function something(){
eval(arr[count%arr.length]+'();');
count++;
}
You can set counter:
<script language="text/javascript">
var counter = 1;
function something(){
document.getElementById("button").id = "button" + counter;
counter++;
}
</script>
And try to separate your javascript code and html. Inline js like onclick doesn't look like nice code.
I have a complicated case here, but below is an example just to make it simple.
I have two buttons, each with their own onClick function. I want to call the onClick function of button A when I click on button B.
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="sayHiA()"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB()"></input>
Note that the event can be onClick() or onMouseUp()
p.s. I have to do it using only javascript. (NO jQuery). Thanks
<input type="button" onclick="fnc()"/>
<input type="button" id="message" onclick="alert('ok')" />
<script type="text/javascript">
function fnc()
{
document.getElementById("message").click();
}
</script>
are you looking for this?
<html>
<head>//I guess something like setTimeout(function,timeInMilliseconds)
<script language = "javascript">
function sayHiA(){
var v = document.getElementById('buttonB').getAttribute("onClick");
setTimeout(v,0);
}
function sayHiB(){
document.getElementById('para').innerHTML = 'wrote';
}
</script>
</head>
<body>
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="sayHiA()"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB()"></input>
<p id = "para">
Write Here
</p>
</body>
</html>
function sayHiB() {
sayHiA();
}
Did you tried this with an external js ? This is quite the most basic thing you can do in javascript.
I made you a jsfiddle : http://jsfiddle.net/pjDVP/4/
The html :
<input id='bta' type='button' value='button a'></input>
<input id='btb' type='button' value='button b'></input>
The js (with jquery laoded) :
$(function(){
$('#bta').click(function(){aORbClick();});
$('#btb').click(function(){aORbClick();});
})
function aORbClick(){alert('I clicked a or b');}
just call function sayHiA from sayHiB or call it after.
Call from sayHiB
function sayHiB()
{
sayHiA();
}
or after
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB(); sayHiA();"></input>
or easier way is to use jQuery, so you can do this
function sayHiB(){
if($('#id-of-a').attr('onclick'))
$('#id-of-a').click();
else if ($('#id-of-a').attr('onmouseup'))
$('#id-of-a').mouseUp();
}
function sayHiB(){
$('#buttonA').click();
}
Raw JS:
function sayHiB(){
var buttonA = document.getElementById('buttonA');
buttonA.onclick.apply(buttonA); // in onclick function you can get buttonA as 'this'
}
I'd probably make a generic function that switches on the button's name/id to figure out what to do - this would also make your code work independent of the event attribute used to call the function.
HTML:
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="myFunc(this)"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="myFunc(this)"></input>
JavaScript:
function myFunc(elem){
switch(elem.id){
case 'buttonA':
sayHiA();
break;
case 'buttonB':
sayHiB();
sayHiA();
break;
}
}
This would also help with any DOM manipulation you might need as the button which was clicked is passed to the generic function myFunc, allowing you to quickly access other attributes or nearby elements.
these days i read and learn more about my problem!the code is here:
<div align="right" id="parent" name="parent">
<select name="select30" id="select30" value=""/>here inside i have options values and work dynamically with query to my DB</select>
<input type="button" id="moreFields" value="+" onclick=""/> //add select tags
<input type="button" value="-" onclick="" /> //remove select tags
<div name="child" id="writeclone"></div> //here cloned the child from parent DIV
</div>
<input type="button" name="enter" id="" value="ENTER" onclick="getoptionvalues();"/>
My problem is how i can get the names or id's from child DIV when + button fired.When this button fired create child DIVs in Child DIV!!Can anybody HELP ME to correct my JAVASCRIPT code
<script>
function getoptionvalues() {
var parent=document.getElementById('parent');
for (var count=0;count<parent.childNodes.length;count++) {
if(parent.childNodes[count].tagName =='DIV') {
alert ('parent.childNodes[count]');
}
}
}
</script>
As ThiefMaster pointed out, 'parent.childNodes[count]' should be parent.childNodes[count]. Then to get the id, it is just .id and name is .name
if(parent.childNodes[count].tagName =='DIV') {
alert (parent.childNodes[count].id);
alert (parent.childNodes[count].name);
}
At the very least, you need to add a method name to your onClick:
<input type="button" id="moreFields" value="+" onclick="$:getoptionvalues()"/>
Then, using jquery, you can grab an array of components of a certain type, and then loop through w/ alerts:
function getoptionvalues() {
var dropdownMenus = $("select");
dropdownMens.each(function () {
var id = $(this).id;
alert(id);
});
}