Calling a function of a button from another button - javascript

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.

Related

Apply Css to the current button click in Javascript

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.

how to bind onclick method with keydown method

I have an onclick method like this:
onClick: function() {
xx.setValue('i want this to be a button but triggered on keyup');
}
And a keyup method like this:
var that=this;
this.something().on( 'keyup', function() {
xx.setValue('hello'+that.something().getvalue());
} );
this is a preview mode. So i want the text from the onclick button to behave like the text i write with the keyboard
Is this the sort of thing you are wanting to achieve here?
$('#button').click(function() {
$('#output').val('You wanted to type:\n' + $('#textBox').val());
});
$('#textBox').on('keyup', function() {
$('#output').val($('#textBox').val());
});
Check out my fiddle to get a better idea of what I'm suggesting http://jsfiddle.net/ozrevulsion/jssL1xwq/
If this isn't what you wanted then please can you provide your own fiddle of your code failing to do what you want it to do so we can get some more context on what you are asking.
Cheers
Zac
[Edit]
I don't know why I didn't notice you were using native JS for your solution earlier. If you wanted to stick with your native JS and not have to use jQuery here is a solution that does the same as what I did above but in native JS.
function changeTextArea(newValue) {
document.getElementById('output').value = newValue;
}
function printToTextArea() {
changeTextArea('You wanted to type:\n' + document.getElementById('textBox').value);
}
And I guess the HTML is relevant for this native JS solution too so here it is
<input id="textBox" type="text" value="Type Here" onkeyup="changeTextArea(this.value)" />
<br />
<input id="button" type="button" value="Tell me what I typed" onclick="printToTextArea()"/>
<br />
<textArea id="output"></textArea>
And here is the updated fiddle http://jsfiddle.net/ozrevulsion/jssL1xwq/1/
wouldn't this work ?
Html:
<input type=button id=btn value='Submit' onclick=otherFunction(); />
<input type=button id=button value='Submit' onclick=myFunction(); />
<div id="other">
Trigger the handler
</div>
and this:
function myFunction(){
$(#btn).click();
}
function otherFunction(){
alert('this');
}
Note that with jquery you have the keup event :
https://api.jquery.com/keyup/
in this case you could have :
$( "#other" ).click(function() {
$(#btn).click();
});

call javascript a function in html submit button

I have a form which I want to hide or show dependent on the users decision. I got following functions in an external javascript file:
function hide_element() {
$("form").hide();
};
function show_element() {
$("form").show();
};
and this is how I call those functions:
<button type="submit" onclick="show_element;">show</button>
<button type="submit" onclick="hide_element;">hide</button>
<form>
...
</form>
Unfortunately this does not work. Do you have any clues why this is the case?
Since we are using jQuery I would like to propose this approach:
HTML:
<button id='toggleMyForm'>hide</button>
<form id='myForm'>First name:
<br>
<input type=" text " name="firstname " />
<br>Last name:
<br>
<input type="text " name="lastname " />
<br>
<input type="submit" value="Submit"/>
</form>
jQuery:
var myForm = $('#myForm');
var toggleMyForm = $('#toggleMyForm');
toggleMyForm.on('click', function(){
myForm.toggle();
myForm.is(":visible") ? $(this).html('hide') : $(this).html('show');
});
Test here: http://jsfiddle.net/urahara/obm39uus/
NOTE: don't put yourself in the position where you have multiple submit buttons in a <form>, you can distinguish between them by using value attribute, but still in my opinion it's better to keep clean design with one submit per form.
don't repeat jQuery fetching calls. make a handle of a element:
var myForm = $('myForm'); then use it like this e.g: myForm.show()
replace show_element with show_element() & hide_element with hide_element() like below:
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
Now you try to call variables named show_element and hide_element. These doesn't exist.
Function has to be called with brackets. If you have no params, use ().
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
I recommend you to use <button type="button" class="hide">Hide</button>
And, in the js file :
$('button.hide').click(function() {
$('form').hide();
}
Same thing for the show button.
You've to replace "show_element;" with "show_element();".
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
But why?
The () Operator Invokes the Function.
Using the example above, show_element refers to the function object, and show_element() refers to the function result.
Example:
Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
http://www.w3schools.com/js/js_functions.asp
With "show_element" you are able to store the function itself (in a variable for example), but you don't execute it.
is this pseudo-code?
If not I would rewrite it like:
$form = $('#form_id');
function hide_element() {
$form.hide();
$form.submit();
}
function show_element() {
$form.show();
$form.submit();
}
And then:
<button onclick="show_element();">show</button>
<button onclick="hide_element();">hide</button>
<form>
...
</form>
I removed the type submit because it is not good to have more than one submit. Actually both are outside the form. In case you want to submit it I would put it like this:
<button onclick="show_element();">show</button>
<button onclick="hide_element();">hide</button>
<form>
...
</form>

How to make the function only runs once JS

How to make the function only runs once per button?
if clicks in "click me" only works once, and the same for the other buttons.
Order not to put much code, I put an example..:
http://jsbin.com/apexod/2/edit
<input type="button" value="click me" onclick="hello('Jhon')"><br>
<input type="button" value="click me1" onclick="hello('Gerard')"><br>
<input type="button" value="click me2" onclick="hello('Kaoru')">
<script>
function hello(id){
alert("hello "+id);
}
</script>
A solution would be to register what buttons have been clicked :
<script>
var done = {}
function hello(id){
if (done[id]) return;
done[id] = 1;
alert("hello "+id);
}
</script>
(another one would be to use a utility lib like jQuery and its one function but this would be overkill for just that)
You can send the button element reference along to the function, and remove the event from the button:
<input type="button" value="click me" onclick="hello(this,'Jhon')"><br>
<input type="button" value="click me1" onclick="hello(this,'Gerard')"><br>
<input type="button" value="click me2" onclick="hello(this,'Kaoru')">
<script>
function hello(el, id){
alert("hello " + id);
el.onclick = null;
}
</script>
Demo: http://jsfiddle.net/Guffa/CDjGY/
Once executed you can override the function with an empty function
function hello(){
alert("hello " + id);
hello = function(){}
}

How to display second button after the click on first button?

How to display second button after the click on first button??
I mean, when The user clicks on one button, he should see another button, on click of which he should return to his previous button!! Cyclic event kind of...
I wanted to do this using Java script and HTML.
I tried to use 'onclick' but it dint work!! Help!!
This is what I used..
`<body>
function alert()
{
alert("54");
// <input type="button" id="btnSer" value="Back"/>
}
<input type="button" id="btnSearch" value="Search" onClick="alert();">
</body>`
Something like this?
<button id="button1" style="display:block;" onclick="document.getElementById('button2').style.display = 'block'; this.style.display = 'none';">Button 1</button>
<button id="button2" style="display:none;" onclick="document.getElementById('button1').style.display = 'block'; this.style.display = 'none';">Button 2</button>
here is the code using simple plain javascript : (*note that naming your function alert() isnt smart because there is already a predefined function in js called alert)
Javascript Code
function addBtn(){
document.getElementById('btnHolder').innerHTML = '<input type="button" onClick="javascript:removeBtn();" value="click" />';
}
function removeBtn(){
document.getElementById('btnHolder').innerHTML = '';
}
HTML
<div id="btnOne"><input type="button" onClick="javascript:addBtn();" value="click" /></div>
<div id="btnHolder"></div>
this code is not tested but it should work, let me know if you have any other questions

Categories

Resources