What is wrong with binding onclick event like this?? Somehow the function never gets triggered.
I think more elaborate codes will explain the question better, I was using es6 template to generate the above codes sippet:
let tmp = ` <div id="pageAppointment">
${this.renderDates(this.data.dateOptions)}
${this.renderTimes(this.timeOptions)}
${this.data.tip ? `<div class="tip flex align-center">${this.data.tip}</div>` : ``}
<div class="btn-wrap mui-flex">
<div class="ok-btn cell" onclick="${this.onOK}">OK</div>
</div>
</div>`
$(this.root).html(tmp);
Your handler just defines a function onOK, but you never call it so why should it be called? If you want it to be executed turn it into an IIFE like so
(function onOK() { ...})()
Because onclick="function name();" creates a function, it doesn't call it. You can do
onclick="alert(111);" instead.
<button onclick="alert(111);"> click </button>
Or call the function which is in a .js file like :
function onOK(){
alert(111);
}
<button onclick="onOK();">click</button>
It is really bad, but as an example, you can do :
<button onclick="function onOK(){
alert(111);
}; onOK();" >click</button>
which creates the function THEN call it. It is an example, don't do that but now you understand how it works
The correct way would be:
<div onclick="alert(111);">ok</div>
Use onclick function on your script file, then append on your elements.
<div onclick="someFunc()">ok</div>
Script file:
function someFunc(){
...
}
Call your function in the end function name();
<button onclick = "function clck(){alert('hi');}clck();">
Click
</button>
It should be like this
function myFunction(){
alert('Clicked');
}
<div onclick="myFunction()">Button Div</div>
Related
This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 4 years ago.
In the code below, why does the header text change on page load, and not only after the button is clicked?
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = change_text("header", "something")
</script>
If you wanted to reuse that function and keep the onclick out of the markup, you could do this:
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = function () {
change_text("header", "something");
}
</script>
This uses something called an anonymous function.
Learn more here: JavaScript Functions
The issue is this line:
button1.onclick = change_text("header", "something")
The JS engine will do the following in this order:
Call change_text with the arguments "header" and "something"
Assign the result of change_text (in this case, undefined) to button1.onclick
Jane Doe's answer should work. If you want to keep your current code structure, then you could use the following:
button1.onclick = function(){
change_text("header", "something");
};
This creates an anonymous function and assigns it to onclick. When onclick is triggered, it will execute the function which calls change_text.
Can you try:
<h1 id="header">This is a header</h1>
<button onclick="change_text('header', 'something')" id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
</script>
I am pretty confident that will work as intended for you..
The reason is simple: you have already called change_text("header", "something") in your code. You are basically doing the same thing as:
let res = change_text("header", "something") // already called, res is undefined
button1.onclick = res
If you are actually passing an event handler, it should looks like button1.onclick = change_text, with change_text() taking an event as param instead. OR as seen in the other answer, <button onclick="change_text('header', 'something')" id="btn1">Change text</button> (this creates an anonymous function that would be called on click event)
My jquery is not alerting anything when I click the button with the id decrease. This is my code. I am using external js file.
$(document).ready(
$('#decrease').click(function() {
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
}))
I tried doing this and it is working fine.
$(document).ready(function(){
alert("Ready");
})
This is the html code:
<div class="row justify-content-center d-flex">
<button id="decrease" class="btn btn-warning">-</button>
<input type="number" id="amt" value="1"/>
<button id="increase" class="btn btn-warning">+</button>
</div>
what's wrong with my first code snippet?
The value you pass to ready() needs to be a function.
In your first example, you are passing the return value of $('#decrease').click(...).
This means that $('#decrease').click(...) has to be evaluated immediately, so it is looking for #decrease before the DOM is ready and the element doesn't exist yet.
ready() then ignores the value you pass to it because it isn't a function.
Wrap the call to $('#decrease').click(...) in a function, just as you did for alert(...) in the second example.
You also have a missing ); at the end but I'm guessing that just got cut off when you transcribed your code to the question.
Try using this:
$('#decrease').on('click', function(){
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
})
if you have the right html syntax, the right syntax for your js script is:
(you have to use a function for document.ready):
$( document ).ready(function() {
$('#decrease').click(function() {
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
});
});
you could use the shorthand syntax:
$(function() {
$('#decrease').click(function() {
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
});
});
html
<button id="test1" onclick="getclickname(); return false;">click</button>
javascript (it's showing "Undefined")
function getclickname()
{
alert(this.id);
}
i dont want code like this
<button id="test1" onclick="alert(this.id);">click</button>
call getclickname is needed, thanks guys
You have to pass corresponding argument to the function.
You need to pass button object to onclick function to get the id of button.
function getclickname(obj)
{
//By passing object as argument you can access all properties of that element
alert(obj.id);
alert(obj.className);
}
<button id="test1" onclick="getclickname(this); return false;" class="test_1">click</button>
You can directly pass this.id as well as an argument
function getclickname(id) {
alert(id);
}
<button id="test1" onclick="getclickname(this.id); return false;">click</button>
Note:
A bit code modification is instead of return false; you can add return before function name and that will do the same thing. like :- onclick="return getclickname(this.id);"
By passing object as argument you can access all properties of that element (check first code sample modification).
Hope this Helpful...
view
onclick="return getclickname(this);"
js
function getclickname(these)
{
alert(these.id);
}
Please try the below code. It's working for you.
Use class for click event in button.
<button id="test1" class="test-btn" >click</button>
Use the below click event function to get id after click.
$('.test-btn').click(function() {
var id = $(this).attr('id');
alert(id)
});
Use like this
<button id="test1" onclick="getclickname(this); return false;">click</button>
<script>
function getclickname(e)
{
alert(e.id);
}
</script>
EDIT: Just an example. I need support for if/else
I want to do this:
<button onclick="function() {alert('Hi!');prompt('What can I do for you?', 'make a Sandwich');}">Hello World!</button>
Apparently this doesn't work.
Do you know how I could do this?
How can I "call" a new function?
I cannot simply define it in a <script></script>-node.
You don't need a function to call. You can directly use Javascript code. This is considered bad practice.
<button onclick="alert('Hi!'); prompt('What can I do for you?','make a Sandwich');">
Hello World!
</button>
Demo
You can also use function as event handler as follow:
HTML
<button onclick="fnHandler();">
Hello World!
</button>
Javascript
function fnHandler() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
}
Demo
Using addEventListener you can bind events from javascript instead of inline in the HTML(Recommended):
HTML
<button id="myButton">
Hello World!
</button>
Javascript
document.getElementById('myButton').addEventListener('click', function() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
});
Demo
It is not recommended to write the functions inside the parameter. It is better to write them on a separate function and then link it with one of the methods listened above. You can still do what you said in the example by using the anonimous function like this:
<button onclick='(function(){
alert("hello world");
prompt("I am the Doctor","oh yeah");
})()'></button>
Updated version for general function because add listner adds uniqueness for click
<button onclick="function_name() id="button">Some Text</button>
Now to write the function definition in js
function function_name(){ .... statements; }
A typical example using this with if-else
<script>
document.getElementById('button').onclick = function() {
if (Calc.Input.value == '' || Calc.Input.value == '0') {
window.alert("Please enter a number");
} else {
document.getElementById('button').value=' Justera längd ';
}
return false;
}
</script>
I need to be able to change the onclick event of an id so that once it has been clicked once it executes a function which changes the onclick event
Here is my code:
Javascript:
function showSearchBar()
{
document.getElementById('search_form').style.display="inline";
document.getElementById('searchForm_arrow').onclick='hideSearchBar()';
}
function hideSearchBar()
{
document.getElementById('search_form').style.display="none";
document.getElementById('searchForm_arrow').onclick='showSearchBar()';
}
and here is the HTML:
<!-- Search bar -->
<div class='search_bar'>
<img id='searchForm_arrow' src="images/icon_arrow_right.png" alt=">" title="Expand" width="10px" height="10px" onclick='showSearchBar()' />
<form id='search_form' method='POST' action='search.php'>
<input type="text" name='search_query' placeholder="Search" required>
<input type='image' src='images/icon_search.png' style='width:20px; height:20px;' alt='S' >
</form>
</div>
Thanks
Change your code in two places to reference the new functions directly, like:
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
Can you try this,
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
You were nearly right. You are settingthe onclick to a string rather than a function. Try:
in showSearchBar()
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
in hideSearchBar()
document.getElementById('searchForm_arrow').onclick=showSearchBar;
You do not need to create two function.
Just create one function and using if condition you can show and hide the form tag..
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display=''; // no need to set inline
}else{
document.getElementById('search_form').style.display='none';
}
}
function searchBar(){
var x = document.getElementById('search_form').style.display;
x = (x == 'inline') ? 'none' : 'inline';
}
You can wrap up both functions into one by adding a check to the current condition of the element and applying your style based on that condition. Doesn't actually change the function but doesn't need to as there is now only one functon performing both actions.
With javascript you can check and perform opration
function SearchBarevent()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
or if you may go for jquery there is better solution toogle
Like:
$("#button_id").click(function(){
$( "#search_form" ).toggle( showOrHide );
});
Fiddle is example
Here is an option that uses jQuery:
$('#searchForm_arrow').click(function() {
$('#search_form').slideToggle();
});
http://jsfiddle.net/PuTq9/