button event with jQuery - button

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(){...});

Related

Ready event for templates

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

How to know which button of User Control is clicked from parent form Asp.net?

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?

OnClick event for whole page except a div

I'm working on an own combobox control for ASP.Net which should behave like a selectbox, I'm using a textbox, a button and a div as a selectbox replacement. It works fine and looks like this Image:
My problem now is the Selectbox close behaviour: when clicking anywhere outside the opened selectbox it should close.
So I need something like an onClick event for the whole page which should only fire when my div is open. Any suggest how to do that?
Add a click event handler to document. In the event handler, examine its target (or srcElement in IE) property to check that it isn't your open div or any of its descendants.
Set a click event handler on the document that "closes" the pseudo-combobox. In addition, set a click event handler on the pseudo-combobox's container (the div, in this case) which cancels bubbling of the event. Then any clicks in the div will bubble up only as far as the div before being halted, while clicks anywhere else will bubble all the way up to the document.
This is a much easier option than mucking around traversing the DOM from the event's target upwards to work out where the click came from.
EDIT: if you are setting the div's style to display: none; (or something similar) to hide it, then it doesn't matter if you leave the event handler on the document - hiding it when it's already hidden will have no effect. If you want to be very tidy, then add the event listeners when the div is shown, and remove them when it is hidden; but there's probably no need to bother.
document.onclick = function() {
if(clickedOutsideElement('divTest'))
alert('Outside the element!');
else
alert('Inside the element!');
}
function clickedOutsideElement(elemId) {
var theElem = getEventTarget(window.event);
while(theElem = theElem.offsetParent) {
if(theElem.id == elemId)
return false;
}
return true;
}
function getEventTarget(evt) {
var targ = (evt.target) ? evt.target : evt.srcElement;
if(targ && targ.nodeType == 3)
targ = targ.parentNode;
return targ;
}
Put a transparent div that covers whole the page and lies under your dropdown. At that div's click event hiğde your dropdown.

Jquery code on load not firing

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.

Prototype button onClick

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>
});
});

Resources