Dynamic event-function binding isn't happening in vbscript / javascript - javascript

Button 1 works fine, but when I try to insert button 2 dynamically the onclick event doesn't call its mapped function, any clue how it works? This is a simple example but later I need to capture events from complex object like trackbar's scroll event.
<html>
<head>
<title>a simple first page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form").append("<input id='button2' type='button' value='button 2'>");
});
</script>
<script language="vbscript">
Sub Button1_OnClick()
MsgBox "button 1"
End Sub
Sub Button2_OnClick()
MsgBox "button 2"
End Sub
</script>
</head>
<body>
<form id="form"><input id="button1" type="button"
value="button 1"></form>
</body>
</html>

If you are adding a new button to the DOM dynamically use the live() function of jquery:
$('[type=button]').live('click', function() { alert('Clicked button'+$(this).val(); } );
That'll add events to all current DOM elements and 'yet' to be created ones!

I am not sure about VB script but this, you can attach a handler to any your button using jQuery live function or by assigning function on onclick event while creating your input and appending to form.
see example
<script type="text/javascript">
$(document).ready(function() {
$("#form").append("<input id='button2' type='button' value='button 2'>");
});
function button_2(){
alert('message 2')
}
// using jQuery live
$('#button2').live('click',button_2);
// other way attaching onclick value to input while creating it
$(document).ready(function() {
$("#form").append("<input onclick='button_2()' id='button2' type='button' value='button 2'>");
});
</script>

How does Button1_Click get called at all? Is there some sort of implicit binding in IE, that I don't know about? The way I'd do it is to add an event with attachEvent().
IE not allowing onClick event on dynamically created DOM 'a' element

Related

Call JS function for specific id in HTML

I have below function in JS file name as hello.js inside js folder.
JS
function hello(){
alert('hello world !);
}
HTML
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="js/hello.js"></script>
<script>
$(function() {
$("#hello").hello();
});
</script>
</head>
<body>
<button type="button" id="hello">Click Me!</button>
</body>
</html>
How do I attach the hello() function to the button with the id="hello"? I'm doing something wrong but I can't find what.
Edit : I recommend reading all answers for completeness.
Edit2: The purpose of this question was to clarify the general method of attaching functions to specific elements on html. The button and the click interaction was an example.
You are probably looking to bind click event on button with id hello using hello as handler
$("#hello").click(hello);
There are many ways to handle events with HTML or DOM.
Defining it in HTML
<button type="button" id="hello" onclick="hello();">Click Me!</button>
Using JQuery
$("#hello").click(hello);
Attaching a function to the event handler using Javascript:
var el = document.getElementById("hello");
if (el.addEventListener)
el.addEventListener("click", hello, false);
else if (el.attachEvent)
el.attachEvent('onclick', hello);
function hello(){
alert("inside hello function");
}
Useful links
MDN - onclick event
SO - Ans 1
SO - Ans 2
Use .on() to bind event handler.
$("#hello").on('click', hello);
Pure javascript:
var elm=document.getElementById("hello");
elm.onclick= function{ hello();};
Jquery:
$("#hello").click(hello() );

Load the javascript file after loading the ajax

I am using jQuery and Ajax.
HOME.html
<html>
<head>
<script src="jquery.js"></script>
<script src="javascript.js"></script>
</head>
<body>
<div id="div1"></div>
<button>click</button>
</body>
</html>
javascript.js
$(document).ready(function(){
$('button').click(function(){
alert('Button is clicked');
$("#div1").load("test2.html");
});
$("#b2").click(function(){
$("#div2").hide();
});
});
TEST2.html
<body>
<div id="div2">
some content
<input type="button" id="b2" value="hide" />
</div>
</body>
<head><script src="javascript.js"></script></head>
When I click on button, Ajax loads the content in div. But when I again click on button then it is clicked twice. I know why this click twice happens, because I again load the javascript.js file.
If I can't do that then the hide button is not working because the JavaScript loads before the div2, that's why hide button is not working.
SOLUTION:
There is one solution is that I use the hide button code in test2.html instead of in javascript.js But I don't want to do that.
Beacuse this is a demo in my original code this is very difficult to do that.
Is there another solution to this?
Repeatedly re-loading the JavaScript is a bad idea.
If you just want to handle clicks on buttons that are dynamically added, you can do that using event delegation. Remove javascript.js from test2.html entirely, and hook up your handlers like this (e.g., change javascript.js to the following):
$(document).on("click", "button", function(){
alert('Button is clicked');
$("#div1").load("test2.html");
});
$(document).on("click", "#b2", function(){
$("#div2").hide();
});
That watches for the click event on the document, but only fires the associated handler if the event passed through an element in the bubbling phase that matches the selector in the second argument. When firing the handler, jQuery makes it look a lot like you had the handler actually attached to that element, rather than to document.
There's a lot more in test2.html than there should be. jQuery will only append the bit in the body (and run the script, but we're removing that). test2.html should just be:
<div id="div2">
some content
<input type="button" id="b2" value="hide" />
</div>
Side note: If you're going to replace it on the next click, I'd use $("#div1").empty() rather than $("#div2").hide() so that you actually proactively remove the content you're going to replace later, rather than just hiding it.

click event does not fire on newly created li tags

With the following code:
<!DOCTYPE html>
<html>
<head>
<title>test list</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<style>
li{
display:inline;
}
</style>
<body>
<input type="hidden" value="4" id="value">
<ol></ol>
<button id="btn2">increase</button>
<button id="btn1">show</button>
<p></p>
</body>
<script>
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
$("#btn2").click(function(){
var text="<li> -> kkk</li>";
$("ol").append(text);
});
$("#btn1").click(function(){
$("p").text($("li").length);
});
</script>
</html>
any newly created "li" tags that appear after clicking "increase" button, do not trigger handlers bound to the click event.
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
Can you please tell me the reason why it's not work. And is it possible to make it work? If yes, How? Thank you very much.
Try like this : As your 'li' are generating dynamically ( For further reading )
$("body").on('click','li',function(){
$(this).nextAll().css({"color":"red"});;
});
From jQuery documentation: "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next."
try this code:
$(document).on('click', 'li', function(){
$(this).nextAll().css({"color":"red"});;
});
May help to put your script library before the closing body tag
...
increase
show
...
see here: fiddle link
$(function() {
$("#btn2").click(function(){
var text= " --> ";
$('ol').append('<li>'+text+'</li>');
$('ol li:not(":first")').css('color','red');
});
$("#btn1").click(function(){
$("p").text($("li").length);
});
});

Simulating Button click in javascript

So what i want to do is when i click on a button, it will pass this click event to another element in webpage, or you can say it will create a new click event in another element. Below is my code, it does not work, please let me know what is wrong with it, it looks make sense...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" onClick=alert("error") /></p>
<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>
</body>
</html>
Since you are using jQuery you can use this onClick handler which calls click:
$("#datepicker").click()
This is the same as $("#datepicker").trigger("click").
For a jQuery-free version check out this answer on SO.
The smallest change to fix this would be to change
onClick="document.getElementById("datepicker").click()">
to
onClick="$('#datepicker').click()">
click() is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.
To simulate an event, you could to use trigger JQuery functionnality.
$('#foo').on('click', function() {
      alert($(this).text());
    });
$('#foo').trigger('click');
The reason your code isn't working the way you would expect is because this line:
<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>
should be changed to:
<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>
There are two things to notice here:
1: The "s around datepicker have been changed to 's so that they do not interfere with the quotes surrounding the onclick event.
2: The click() has been changed to focus() to activate the datepicker calendar. When the button is pressed.
Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>, this should not be a problem.
Inline events are not recommended.
Or you can use what JQuery alreay made for you:
http://jqueryui.com/datepicker/#icon-trigger
It's what you are trying to achieve isn't it?
try this
document.getElementById("datapicker").addEventListener("submit", function())
Use this
jQuery("input.second").trigger("click");

Click event on a button in Safari

In this code have button and anchor with click event.
alert(document.getElementById("btn").click); //not working in safari
alert(document.getElementById("btn1").click); // is working in safari
I want to execute anchor's click event What I do?
<head>
<script type="text/javascript">
function clickMe()
{
alert('My Name is ' + event.srcElement.name);
}
</script>
</head>
<body>
a
<input type="button" href="#" name="btn1" id="btn1" onclick="clickMe()" />
<script>
//document.getElementById("btn").click();
alert(document.getElementById("btn").click);
alert(document.getElementById("btn1").click);
</script>
</body>
Try this way
<!DOCTYPE html>
<html>
<head></head>
<body>
a
<input type="button" href="#" name="btn1" id="btn1" />
<script>
function teste(){
alert('You clicked on an anchor');
}
window.onload = function() {
document.querySelector("#btn").addEventListener("click", teste);
};
</script>
</body>
</html>
Taken from another question Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?
I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.
Safari and Chrome will not allow the link object to have a .click function, because of this behavior. It would appear that IE is less strict.

Categories