How can I have every button on an html page perform the same function using prototype.js?
I used the someElement.observe() method and it worked for one button. But how can I do this for every button on the page without coding separately for each button?
Use the css selector to select multiple elements:
$$('input[type="button"]').observe(...)
You can also use event delegation to register one event handler on the element that contains your buttons (e.g. the document body) and take advantage of the fact that events bubble up the DOM.
This will ensure that your event handler is called for every button, even if you dynamically add new buttons to the page.
E.g.
document.observe( 'click', function( event )
{
var elem = event.element();
if ( elem.match( 'input[type="button"]' ) )
{
// Do your event handler
}
});
You can use this also:
Event.observe(window, 'load', function(){
$('idForm').getInputs('radio', 'nameRadio').each(function(el){
el.onclick = function(){
//Actions<br>
});
});
Related
In JsViews i can bind events in the following way:
<li id="myElement" data-link="{on 'click' eventHandler}">Some Content</li>
This will execute the method "eventHandler" after a click.
But I need an event which will be fired when the template is loaded. I tried "ready" or "show", but nothings works. Is there a event which can handle this?
The {on xxx eventHandler} handles events on HTML elements, such as mouse events, submit, change, blur, etc.
With JsViews, the loading of the template happens directly as a result of your own code calling the link method. So elements in the rendered template will have been rendered during that call, and immediately after you can run whatever code you want to call after rendering and linking, such as using jQuery to find your <li> element, and act on the element
JsViews also provides many life-cycle events on tags, so if you want you can create a custom tag just for handling those events:
For example, try running the following code:
<span id="result"></span>
<script>
var data = {};
$.views.tags("test", {
attr:"none",
render: function(data) {
debugger;
},
onBind: function(tagCtx, linkCtx) {
var elem = this.parentElem;
elem.textContent += " added text";
}
});
var myTmpl = $.templates('<ul><li id="myElement" data-link="{test}">Some Content</li></ul>');
myTmpl.link("#result", data);
$("#myElement").css('color', 'red');
</script>
You could use an onload event:-
https://www.w3schools.com/jsref/event_onload.asp
and attach that to the template itself. If you're limited in your options or need to do it in a specific way, explain the use case and why you want to do it a certain way and we'll try to help.
All the best,
Phil
I want to capture which button is clicked in page load method of code behind file.
Button is user control button and It does not post back. Since it used by many other forms, I don't want to changes that button.
I tried this
Dim ButtonID As String = Request("btnRefresh.ID")
But it doesn't work.
Is it possible to know without touching in user control and using Javascript?
Thank you
As described here How to check whether ASP.NET button is clicked or not on page load:
The method: Request.Params.Get("__EVENTTARGET"); will work for
CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work
for Button controls such as Buttons and ImageButtons
But you have a workaround, first of all you have to define a hidden field in the Parent Page. In this field you will store which button inside the user control was clicked using javascript/jquery. And then in your Parent Page Page_Load method you just read the hiddenField.Value property:
JQuery
1) Add listener to every input type submit button:
$(document).ready(function () {
$("input[type=\"submit\"]").on("click", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
2) [Better one] Add listener to some indentificable div inside the user control and delegate the event to child inputs like this:
$(document).ready(function () {
$("#someElementOfUserControl").on("click", "input[type=\"submit\"]", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
Javascript
Since everything done with JQuery can be done with Javascript you can do the following (i will not write both samples, just one):
function handleClick(event) {
alert(event.target.name);
document.getElementById("hiddenField1").value = event.target.name;
}
var inputsInUC = document.getElementsByTagName('input');
for (i = 0; i < inputsInUC.length; i++) {
inputsInUC[i].addEventListener('click', handleClick, false);
}
Remember to define this javascript after all your html elements.
EDIT:
Also, for the completeness of the answer let me tell you that the proper way in case you can change the user control behaviour is to use events as described here How do i raise an event in a usercontrol and catch it in mainpage?
I have an id of the button element like this: '#edit-field-project-dnr-und-0-remove-button'
I want to add an event in this button id for instance:
$('#edit-field-project-dnr-und-0-remove-button').click(function (){
calculateDonorSum();
});
This button is ajax button whenever this is clicked old id that is '#edit-field-project-dnr-und-0-remove-button' is replaced into '#edit-field-project-dnr-und-1-remove-button' and so on but no event is fired in the previous button id. Is there any way to fix this ?
When you do this:
$('#edit-field-project-dnr-und-0-remove-button').click(function (){
calculateDonorSum();
});
This searches the current DOM for any element that has an id="edit-field-project-dnr-und-0-remove-button" and attaches an event handler directly to that DOM element.
If you remove that DOM element and create some new DOM element or add a new DOM element, that new DOM element will NOT have this event handler attached to it unless you run some new code to attach an event handler to the new element.
For dynamic elements, it is also possible to use delegated event handling, but you haven't really described enough of what you're doing for us to know how to recommend that. I can't tell if you're adding a new button or changing the ID on the current button.
If you are adding a new button and want all new buttons of this type to have this event handler, then you can use delegated event handling. Delegated event handling works like this:
$("some static common parent selector").on("click", "some common child selector", fn);
So, if your buttons were all in a id="container" div and all had a common class name on them class="calcButton", then you could use:
$("#container").on("click", ".calcButton", function() {
calculateDonorSum();
});
And, all buttons in the container with that class would have this event handler, even if they are dynamically created after the event handler is defined.
Some other references on delegated event handling:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
Should all jquery events be bound to $(document)?
JQuery Event Handlers - What's the "Best" method
consider using jQueries attribute starts with, contains, or ends with selectors
//button id starts with 'edit-field-project-dnr-und-' and ends with '-remove-button'
$("[id^=edit-field-project-dnr-und-][id$=-remove-button]").click(function () {
calculateDonorSum();
});
if these buttons are created dynamically, use
$('#some-parent-container').on("click","[id^=edit-field-project-dnr-und-][id$=-remove-button]", function(){
calculateDonorSum();
})
instead of .click()
//button id starts with
$("[id^=button-]").click(function () {
calculateDonorSum();
});
//button id ends with
$("[id$=-remove]").click(function () {
calculateDonorSum();
});
//button id contains
$("[id*=-remove]").click(function () {
calculateDonorSum();
});
this works, here, made a fiddle
http://jsfiddle.net/MzPEg/1/
in general use this approach ONLY if you don't have control over the naming/creation of the original buttons. these selectors are not as fast as $('#id') and it's a bit sloppy. but it will work in a pinch.
It appears that the id of the field on which the onclick event is supposed to occur is changing, yet you only handle the first id. If you do not want to make all of these ids the same, you could put the click event handler on a parent wrapper div.
You can do as this:
$('#edit-field-project-dnr-und-0-remove-button').click(function (e){
e.preventDefault();
calculateDonorSum();
$(this).attr('id','edit-field-project-dnr-und-1-remove-button');
});
Using an advanced selector that matches the beginning part of the id AND the ending part:
$('[id^="edit-field-project-dnr-und"][id$="remove-button"]').on('click', function(){...});
Here is my code:
$(document).ready(function(){
$('.classOne').mouseover(function(e) {
alert($(e).attr('id'));
});
});
Now, I know that something is actually wrong with my code, what will be correct in order to get the result with the ID of the current asp:LinkButton that I hovered in the alert() message?
Thanks for all helpers!
e is your event, not your element. Your element is wrapped in this function.
$(document).ready(function() {
$('.classOne').mouseover(function(e) {
alert($(this).attr('id'));
});
});
You should do this instead:
$(document).ready(function(){
$('.classOne').mouseover(function() {
alert($(this).attr('id'));
});
});
Couple of assumptions:
The link button is rendered with the valid class 'classOne'
The button is not added to the page collection via an AJAX callback
the 'e' parameter actualy is an object of the event & not really the object of the HTML element
(document).ready(function(){
$('.classOne').bind('mouseover', function(){
alert($(this).attr('id'));
});
});
I have the following JQuery code in a external JS file linked into a
usercontrol in .Net 1.1 webapp.
The usercontrol is a timesheet.
When the page loads it calls MonthChange and works fine in one page.
But now I want to load the timesheet/usercontrol into aother
webpage that pops up a in a new browser window for printing.
Problem is my MonthChange is not firing.
Any ideas why???
$(function() {
MonthChange();
//TestData();
$('[class^=TSGridTB]').blur(function() {
var day = GetDay($(this).attr('id'));
var date = GetRowDate(day);
var bgcolor = GetInputFieldColor(date, false);
$(this).css("background-color", bgcolor);
$(this).parent().css("background-color", bgcolor);
//CalcHours($(this).get(0));
});
$('[class^=TSGridTB]').focus(function() {
var day = GetDay($(this).attr('id'));
var date = GetRowDate(day);
var bgcolor = GetInputFieldColor(date, true);
$(this).css("background-color", bgcolor);
$(this).parent().css("background-color", bgcolor);
});
$('[id$=lstMonth]').change(function() {
MonthChange();
});
});
without seeing further code, ensure that the selector is correct for the control in the new page.
The problem may be that the DOM has changed for the new page/window and JQuery does not yet know about it.
The change event
fires when a control loses the input
focus and its value has been modified
since gaining focus.
You might want to use the live event:
Binds a handler to an event (like
click) for all current - and future -
matched element.
When you bind a "live" event it will
bind to all current and future
elements on the page (using event
delegation). For example if you bound
a live click to all "li" elements on
the page then added another li at a
later time - that click event would
continue to work for the new element
(this is not the case with bind which
must be re-bound on all new elements).
Did you make sure that the new web page has jQuery script includes?
ensure you're using:
$(document).ready(
);
around your entire code block. The $ alone often does not do the trick.