Div Click Event not firing - asp.net

I have a page where i have a div element as below,
`<div id="Dailymain" runat="server" class=" sidebar" onclick="ClickDaily">
<div runat="server" id="Daily" class="sidebar_item" onclick="ClickDaily" >
<h2><a id="Daily" href="Productivity.aspx">Daily</a></h2>
<p> </p>
</div><!--close sidebar_item-->
</div>`
and in my page_load code i have this,
Weekly.Attributes["onclick"] = this.ClientScript.GetPostBackEventReference(this, "ClickWeekly");
and in IPost Back EventHandler Members interface i have this..
'if (eventArgument == "ClickWeekly")
{
Weekly_Click();
}'
but when that div element is clicked the click event function is not firing..where am i missing here.please help me...

You are trying to add the click handler to an object called Weekly - but in the markup you posted there is no element with that id.
You also have multiple elements with the same id "Daily" - id attributes should be unique.
As mentioned above, the onclick() function calls javascript - you will need to define a javascript function which causes a postback and invokes the server side function you need. Or could you implement the server side function as javascript instead?

Write a code like this
Step 1: In Page Load event
Dailymain.Attributes.Add("onclick", "return ClickDaily()")
Step 2: Define javascript event
function ClickDaily()
{
alert("call daily");
return false;
}

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 Attach Events to Table Checkboxes in Material Design Lite

When you create a MDL table, one of the options is to apply the class 'mdl-data-table--selectable'. When MDL renders the table an extra column is inserted to the left of your specified columns which contains checkboxes which allow you to select specific rows for actions. For my application, I need to be able to process some JavaScript when a person checks or unchecks a box. So far I have been unable to do this.
The problem is that you don't directly specify the checkbox controls, they are inserted when MDL upgrades the entire table. With other MDL components, for instance a button, I can put an onclick event on the button itself as I'm specifying it with an HTML button tag.
Attempts to put the onclick on the various container objects and spans created to render the checkboxes has been unsuccessful. The events I attach don't seem to fire. The closest I've come is attaching events to the TR and then iterating through the checkboxes to assess their state.
Here's the markup generated by MDL for a single checkbox cell:
<td>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select mdl-js-ripple-effect--ignore-events is-upgraded" data-upgraded=",MaterialCheckbox">
<input type="checkbox" class="mdl-checkbox__input">
<span class="mdl-checkbox__focus-helper"></span>
<span class="mdl-checkbox__box-outline">
<span class="mdl-checkbox__tick-outline"></span>
</span>
<span class="mdl-checkbox__ripple-container mdl-js-ripple-effect mdl-ripple--center">
<span class="mdl-ripple"></span>
</span>
</label>
</td>
None of this markup was specified by me, thus I can't simply add an onclick attribute to a tag.
If there an event chain I can hook into? I want to do it the way the coders intended.
It's not the nicest piece of code, but then again, MDL is not the nicest library out there. Actually, it's pretty ugly.
That aside, about my code now: the code will bind on a click event on document root that originated from an element with class mdl-checkbox.
The first problem: the event triggers twice. For that I used a piece of code from Underscore.js / David Walsh that will debounce the function call on click (if the function executes more than once in a 250ms interval, it will only be called once).
The second problem: the click events happens before the MDL updates the is-checked class of the select box, but we can asume the click changed the state of the checkbox since last time, so negating the hasClass on click is a pretty safe bet in determining the checked state in most cases.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
$(document).on("click", ".mdl-checkbox", debounce(function (e) {
var isChecked = !$(this).hasClass("is-checked");
console.log(isChecked);
}, 250, true));
Hope it helps ;)
We currently don't have a way directly to figure this out. We are looking into adding events with V1.1 which can be subscribed to at Issue 1210. Remember, just subscribe to the issue using the button on the right hand column. We don't need a bunch of +1's and other unproductive comments flying around.
One way to hack it is to bind an event to the table itself listening to any "change" events. Then you can go up the chain from the event's target to get the table row and then grab the data you need from there.
You could delegate the change event from the containing form.
For example
var form = document.querySelector('form');
form.addEventListener('change', function(e) {
if (!e.target.tagName === 'input' ||
e.target.getAttribute('type') !== 'checkbox') {
return;
}
console.log("checked?" + e.target.checked);
});

Add a class to parent element when clicked with Knockout.js

I have a div with a close button on it. The close button has a function fired via Knockout.js that I would like to add a class to the parent of this button, i.e. the encapsulating div. However, in my JS file (see below) the function firing is linked to an object in an array.
HTML
<div>
<button data-bind="click: $parent.myFunc">
</div>
JS file
this.myFunc = function(e) {
// this.addClass('boo'); does not work
}
I can fire a console.log off in this function, but can't seem to manipulate this element through standard jQuery.
Knockout way of doing it would be to add a css binding to the parent and then manipulate it within your function fired by click event:
<div data-bind="css: someClass">
<button data-bind="click: myFunc">
</div>
And within your JS file:
this.someClass = ko.observable("");
this.myFunc = function(e) {
this.someClass("boo");
}
since you tagged jQuery, I assume you can use it, so:
$('button').click(function(){
$(this).parent().addClass('boo');
});
This is my first answer on here but how about looking into jQuery's .parent() api? http://api.jquery.com/parent/
I'm not familiar with Knockout.js but perhaps something like this could work..
$('button').data('bind','click: $parent.myFunc').click(function(){
$(this).parent().addClass('boo');
});

button event with jQuery

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

Jquery validation not working after clearing a form

I have applied validation through JQuery Validation Plugin on my page. The validation works fine but once the Clear button is hit to clear out all the fields on the form, and then the save button is clicked again, the validation doesn't fire and the form gets submitted. I have called the following javascript function on click of Clear button to clear out all the form fields :-
function ResetForm() {
jQuery(':input', '#form1')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
return false;
}
The Clear button is on a ChildPage and ResetForm function is on the MasterPage. Anybody have any guess why its getting submitted after clearing the fields ?
input is an element and not a attribute or a pseudo selectable, the main issue I see in your code is the : within the :input
Try changing to jQuery('#form1 input') to fetch the list of inputs
Also change the not() command to select filter the inputs by type
.not('[type="button"], [type="submit"], [type="reset"], [type="hidden"]')
also as for :hidden there's several factors you should know about this.
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
In light of your comment please try this tested version:
function resetForm()
{
$("#form1").find(':input').each(function()
{
var jelem = $(this);
switch(this.type)
{
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
jelem.val('');
break;
case 'checkbox':
case 'radio':
jelem.attr('checked',false);
}
});
}
#source: http://www.electrictoolbox.com/jquery-clear-form/
Another way to do this is to create a hidden input in your form but set the type as reset like so:
<input type="reset" style="display:none" />
and then do:
function resetForm()
{
$("#form1[type='reset']").click();
}
Actually the error was something else, the code provided by RobertPitt is correct for clearing of form fields and my code was also correct for clearing of form fields. But the problem is that, on the clear button I had applied a class="cancel" so that the form should not get submitted because it was an aspx:button.
But according to what is written in JQuery docs, clicking of a button whose class is cancel should skip the validation, but after that if I click on a normal submit button validation should fire which was not firing in my case.
I just removed the cancel class and it worked.
Does this help?
Reseting the form when usering the jquery validations plugin

Resources