Need to call a javascript function on checked changed property of checkbox - javascript

I was trying call a function on check change of checkbox, but the method I written in javascript doesn's calling. I am trying with following code
calling onchange on checkbox
<asp:CheckBox ID="CheckBox1" runat="server" onchange="fun();" />
function calling in javascript
function fun() { }
Debugger is not going thrue this function.
Also can we do it by jQuery easily?
Thanks,

jQuery:
$('#CheckBox1').on('change', fun);
plain JS
document.getElementById('CheckBox1').addEventListener('change', fun, false);
EDIT:
If the javascript code comes before the DOM element is created, you'll need some sort of DOM ready function, like window.onload in plain JS. jQuery uses document ready, and a shortcut for that is :
$(function() {
$('#CheckBox1').on('change', fun);
});

Related

issue with one custom ToggleClass() in jquery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
.bold {
font-weight: bold;
}
.blue {
color: blue;
}
</style>
Toggle class
<script type="text/javascript">
function ToggleClass()
{
if($(this).hasClass("bold"))
{
$(this).removeClass("bold");
}
else
{
$(this).addClass("bold");
}
}
</script>
Question:
I made one function: ToggleClass, but it does not work, what is the problem?
The reason why it doesn't work is two-fold:
No explicit binding
You're using inlined code:
Toggle class
Even though the code inside the onclick parameter is run in the right context, the function call gets invoked in the context of window, i.e. inside ToggleClass(), by default, this refers to window; it's as if ToggleClass.call(window) was written. You can bind the function to another object if you wish:
Toggle class
Using .call() you bind the current element to the function and it will work as expected.
Not enough jQuery
You're not doing things in the jQuery way.
Toggle class
...
<script>
jQuery(function($) {
$('.toggle-bold').on('click', function() {
$(this).toggleClass('bold');
return false; // prevent navigation to #
});
});
</script>
I've removed the href="javascript:void(0);" and the inlined code. Instead, I've added a class to target the anchor; if the link only occurs once inside the document, you may want to consider a unique identifier. The click handler is attached once the document is ready.
To prevent the browser from adding that pesky # at the end, I'm returning false from the click handler to stop event propagation.
Lastly. instead of hasClass(), addClass() and removeClass() I'm using toggleClass().
you need to send reference to the calling function
... onclick="ToggleClass(this);"...
<script type="text/javascript">
function ToggleClass(obj)
{
if($(obj).hasClass("bold"))
$(obj).removeClass("bold");
else
$(obj).addClass("bold");
}
however i always prefer using click function rather than inline javascript
Toggle class
<script>
$('#ToggleClass').click(function(){
if($(this).hasClass("bold"))
$(this).removeClass("bold");
else
$(this).addClass("bold");
});
</script>
Using jQuery the implementation should be as simple as using the .toggleClass() utility method:
Toggle class
<script type="text/javascript">
jQuery(function($)
{
$('#toggleme').click(function()
{
$(this).toggleClass('bold');
});
});
</script>
You're using an inline onclick handler. Your HTML:
onclick="ToggleClass();"
Is interpreted similarly to:
element.onclick = function(event) {
//`this` is available inside the onclick method
ToggleClass(); //but it is not passed to called functions automatically
}
You're just calling a function, hence the this reference is not set inside this ToggleClass execution. By "not set", I mean in the ES aspect: entering function code with an undefined this means that the this reference will point to the window object, or undefined when in strict mode.
One way to set the this reference for a function execution context is using Function.call or Function.apply:
onclick="ToggleClass.call(this, event);"
Read more about the this keyword here.
*event is not necessary with your code, but event handlers usually expect to receive an event object hence I'm passing it anyway.
However, you're already using jQuery, which sets the this reference inside event handlers and wraps the event object to make its methods cross-browser. Hence you can just add a JS hook to your element and attach listeners through jQuery:
Toggle class
<script>
$('.js-toggleClass').click(function(e) {
e.preventDefault();
$(this).toggleClass('bold');
});
</script>
Demo
I've replaced your href="javascript:void(0)" with the jQuery Event object's preventDefault() method as JavaScript does not belong inside href attributes, and used the jQuery .toggleClass() method to simplify your logic as well.
The pros of this is the separation between structure (HTML) and behavior (JS), thus keeping your code much more organized and modularized.
You are calling function ToggleClass(), but yoy are not passing parameter when calling ToggleClass() function , Pass Reference when calling ToggleClass(), otherwise buildin function exists in JQuery.
Send current object in toggleClass() function like this :
ToggleClass(this)
Toggle class
<script type="text/javascript">
function ToggleClass(abc)
{
if($(abc).hasClass("bold"))
$(abc).removeClass("bold");
else
$(abc).addClass("bold");
}
</script>
i hope it will help you

What is the jQuery or javaScript syntax to make functions work only on the active/focused input/button/text area?

I am a beginner & self interested web coder.
I have been testing, asking, retesting, trying, reading up on different functionality solutions in javaScript to an online form which will consist of a multitude of <textarea>'s once I am done.
I am fairly ok, with the current state of functions, which are based upon several js events. Example code would be (written funny so it is easier to read in the forum, actual code is one line obviously):
<textarea
data-id="0"
class="classOne classTwo"
id="dataInput_0"
name="xInput_row_1"
onFocus="functionOne();"
onBlur="functionTwo();"
onKeyUp="functionThree();">
</textarea>
I built and tested all the functions to work specifically on the id="dataInput_0" using getElementById. Example:
var d = document.getElementById("dataInput_0");
So my question is how to I make the functions trigger for other "dataInput" id's?
In other words:
var d = document.getElementById('whichever dataInput that is active/focused');
Thanks!
The simplest way to work with your current code would be to do this:
onFocus="functionOne(this);"
...and then define your function:
function functionOne(el) {
// el is the element in question, used e.g.:
alert(el.name);
}
Within the onFocus=... the browser sets this to the element in question, so you can then pass it as a parameter to your function. Your function then just uses it directly rather than having to go via getElementById().
But since you mentioned jQuery, you could remove the inline onFocus and other onXYZ handlers from your html and just do it all in your JS as follows:
$("textarea").focus(function() {
// here this is the element in question, e.g.:
alert(this.value);
});
That defines a focus handler for all textareas on the page - to narrow it down to just textareas with class "classOne" do $("textarea.classOne"). Within the function this refers to the focused element. You could use the .blur() and keyup() methods to assign handlers for the other events shown in your code.
My suggestion is to use attribute selector $('input[id^="dataInput_"]') for this and use the jQuery's .on() handler this way:
$('input[id^="dataInput_"]').on({
focus: function{
functionOne($(this));
},
blur: function(){
functionTwo($(this));
},
keyup: function(){
functionThree($(this));
}
});
and the functions:
functionOne(obj){
console.log(obj.val());
}
functionTwo(obj){
console.log(obj.val());
}
functionThree(obj){
console.log(obj.val());
}

How to call a javascript function using asp.net dropdown list

I need to call a javascript function when the dropdown list is changed.
How can I implement that in asp.net?
Use onchange event to excecute function whenever the dropdown list clicked.
<select id="mylist" onchange = "go()">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<script>
function go()
{
var x = document.getElementById("mylist").value;
console.log(x);
}
</script>
<asp:DropDownList runat="server" ID="DDList" onclick="alert(1)"></asp:DropDownList>
If you want to get function executed when element clicked, you can use above code to define a function that should be executed 'onclick'.
But it is better to use something like addEventListener, just search for cross-browser function (for instance, like addListener function here):
document.getElementById("<%=DDList.ClientID %>").addEventListener("click", fucntionToExecuteName, false)
Remember, than in this case you must take DDList.ClientID and use it as id of an element, because it will be different from ID you have set in your aspx code
But if you need some function to be executed when actual value is changed, you should use onchange event.
Use Jquery :
$(document).ready(function(){
$("#DropDownID").change(function () {
// Your requirment
});
});
Also it's always better to write it inside the document.ready
Use something like this (uses jQuery):
$(document).ready(function() {
$("#dropdownId").change(function(e)) {
do something...
});
});
Add this script to your mark-up and be sure to also include a script reference to jquery:
$(document).ready(function()
{
$("#yourDropdownId").change(function(){
//Todo: write your javascript code here.
});
});
Make sure that the control with "yourDropdownId" as ID has the property: "ClientIDMode" set to static or the "all-knowing" ASP.NET engine will auto-generate an element name for the resulting html with parent element names appended to the control by default.
Use JQuery
$(document).ready(function(){
$('select[name$=DrpGoingTo]').change(function () {
//Code here
});
});
You can use an onchange event and call it from itself:
<asp:DropDownList ID="DropdownList" runat="server" onchange="javascript:MyFunction();" >
</asp:DropDownList>

Need to add another onClick event

I have a checkbox, that is styled using onclick handler.
The issue I have is , I also want to fire a div simultaneously.. to display hidden message.
Kind of like: checkbox ( tick to go featured )
If ticked show featured div, else hide.
Code I have is:
<span id="checkboxWrap" class="styledCheckboxWrap"><input name="include" type="checkbox" id="checkbox" onclick="setCheckboxDisplay(this)" class="styledCheckbox" /></span>
Wanted to also fire the div like...:
onClick="toggle('feature');"
Can I chain onClick events to one click handler?
ie..
onclick="setCheckboxDisplay(this);toggle('feature');"
Or am I going round in circles.
Use event listeners. They're better anyway. :)
var check = document.getElementById('checkbox');
check.addEventListener('click', function () {
setCheckboxDisplay(this);
});
check.addEventListener('click', function () {
toggle('feature');
});
Ideally, you should try to start using unobstrusive javascript which basically means you separate the structure from function by moving your javascript inside a <script> tag or into a separate file. So your code would look like this and make it easier to read.
HTML
<span id="checkboxWrap" class="styledCheckboxWrap">
<input name="include" type="checkbox" id="checkbox" class="styledCheckbox" />
</span>
Script
<script>
$(function(){
$('.styledCheckbox').click(function(){
setCheckboxDisplay(this);
toggle('feature');
});
});
</script>
Yes, you can call multiple statements in the onclick attribute as long as they are semicolon-delimited. That gets unweildy though, so I'll usually define a new function to wrap the two into one call.
Just delegate this to a function that does all your work...
// Somewhere in the head of the file...
function doOnClickStuff(target) {
toggle('feature');
setCheckboxDisplay(target);
}
And then just have the onClick handler invoke that...
onClick="doOnClickStuff(target);"

jQuery $(document).ready and UpdatePanels?

I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in $(document).ready . For example:
$(function() {
$('div._Foo').bind("mouseover", function(e) {
// Do something exciting
});
});
Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel.
What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of $(document).ready?
An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.
What I've done to work around this is re-subscribe to the events I need after every update. I use $(document).ready() for the initial load, then use Microsoft's PageRequestManager (available if you have an update panel on your page) to re-subscribe every update.
$(document).ready(function() {
// bind your jQuery events here initially
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// re-bind your jQuery events here
});
The PageRequestManager is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.
If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs) so you can see what raised the event and only re-bind if needed.
Here is the latest version of the documentation from Microsoft: msdn.microsoft.com/.../bb383810.aspx
A better option you may have, depending on your needs, is to use jQuery's .on(). These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use .delegate() or .on(), so in those cases, you're better off re-subscribing.
<script type="text/javascript">
function BindEvents() {
$(document).ready(function() {
$(".tr-base").mouseover(function() {
$(this).toggleClass("trHover");
}).mouseout(function() {
$(this).removeClass("trHover");
});
}
</script>
The area which is going to be updated.
<asp:UpdatePanel...
<ContentTemplate
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
*// Staff*
</ContentTemplate>
</asp:UpdatePanel>
User Control with jQuery Inside an UpdatePanel
This isn't a direct answer to the question, but I did put this solution together by reading the answers that I found here, and I thought someone might find it useful.
I was trying to use a jQuery textarea limiter inside of a User Control. This was tricky, because the User Control runs inside of an UpdatePanel, and it was losing its bindings on callback.
If this was just a page, the answers here would have applied directly. However, User Controls do not have direct access to the head tag, nor did they have direct access to the UpdatePanel as some of the answers assume.
I ended up putting this script block right into the top of my User Control's markup. For the initial bind, it uses $(document).ready, and then it uses prm.add_endRequest from there:
<script type="text/javascript">
function BindControlEvents() {
//jQuery is wrapped in BindEvents function so it can be re-bound after each callback.
//Your code would replace the following line:
$('#<%= TextProtocolDrugInstructions.ClientID %>').limit('100', '#charsLeft_Instructions');
}
//Initial bind
$(document).ready(function () {
BindControlEvents();
});
//Re-bind for callbacks
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
BindControlEvents();
});
</script>
So... Just thought someone might like to know that this works.
Upgrade to jQuery 1.3 and use:
$(function() {
$('div._Foo').live("mouseover", function(e) {
// Do something exciting
});
});
Note: live works with most events, but not all. There is a complete list in the documentation.
You could also try:
<asp:UpdatePanel runat="server" ID="myUpdatePanel">
<ContentTemplate>
<script type="text/javascript" language="javascript">
function pageLoad() {
$('div._Foo').bind("mouseover", function(e) {
// Do something exciting
});
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
,since pageLoad() is an ASP.NET ajax event which is executed each time the page is loaded at client side.
My answer?
function pageLoad() {
$(document).ready(function(){
etc.
Worked like a charm, where a number of other solutions failed miserably.
I would use one of the following approaches:
Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.
Use the livequery plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.
function pageLoad() is very dangerous to use in this situation. You could have events become wired multiple times. I would also stay away from .live() as it attaches to the document element and has to traverse the entire page (slow and crappy).
The best solution I have seen so far is to use jQuery .delegate() function on a wrapper outside the update panel and make use of bubbling. Other then that, you could always wire up the handlers using Microsoft's Ajax library which was designed to work with UpdatePanels.
When $(document).ready(function (){...}) not work after page post back then use JavaScript function pageLoad in Asp.page as follow:
<script type="text/javascript" language="javascript">
function pageLoad() {
// Initialization code here, meant to run once.
}
</script>
I had a similar problem and found the way that worked best was to rely on Event Bubbling and event delegation to handle it. The nice thing about event delegation is that once setup, you don't have to rebind events after an AJAX update.
What I do in my code is setup a delegate on the parent element of the update panel. This parent element is not replaced on an update and therefore the event binding is unaffected.
There are a number of good articles and plugins to handle event delegation in jQuery and the feature will likely be baked into the 1.3 release. The article/plugin I use for reference is:
http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery
Once you understand what it happening, I think you'll find this a much more elegant solution that is more reliable than remembering to re-bind events after every update. This also has the added benefit of giving you one event to unbind when the page is unloaded.
FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {...
Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.
Cheers
pageLoad = function () {
$('#div').unbind();
//jquery here
}
The pageLoad function is perfect for this case since it runs on the initial page load and every updatepanel async postback. I just had to add the unbind method to make the jquery work on updatepanel postbacks.
http://encosia.com/document-ready-and-pageload-are-not-the-same/
My answer is based on all the expert comments above, but below is the following code that anyone can use to make sure on each postback and on each asynchronous postback the JavaScript code will still be executed.
In my case, I had a user control within a page. Just paste the below code in your user control.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
UPDATEPANELFUNCTION();
}
}
function UPDATEPANELFUNCTION() {
jQuery(document).ready(function ($) {
/* Insert all your jQuery events and function calls */
});
}
UPDATEPANELFUNCTION();
</script>
Update Panel always replaces your Jquery with its inbuilt Scriptmanager's scripts after every load. Its better if you use pageRequestManager's instance methods like this...
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest)
function onEndRequest(sender, args) {
// your jquery code here
});
it will work fine ...
Use below script and change the body of the script accordingly.
<script>
//Re-Create for on page postbacks
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
//your codes here!
});
</script>
In response to Brian MacKay's answer:
I inject the JavaScript into my page via the ScriptManager instead of putting it directly into the HTML of the UserControl. In my case, I need to scroll to a form that is made visible after the UpdatePanel has finished and returned. This goes in the code behind file. In my sample, I've already created the prm variable on the main content page.
private void ShowForm(bool pShowForm) {
//other code here...
if (pShowForm) {
FocusOnControl(GetFocusOnFormScript(yourControl.ClientID), yourControl.ClientID);
}
}
private void FocusOnControl(string pScript, string pControlId) {
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "focusControl_" + pControlId, pScript, true);
}
/// <summary>
/// Scrolls to the form that is made visible
/// </summary>
/// <param name="pControlId">The ClientID of the control to focus on after the form is made visible</param>
/// <returns></returns>
private string GetFocusOnFormScript(string pControlId) {
string script = #"
function FocusOnForm() {
var scrollToForm = $('#" + pControlId + #"').offset().top;
$('html, body').animate({
scrollTop: scrollToForm},
'slow'
);
/* This removes the event from the PageRequestManager immediately after the desired functionality is completed so that multiple events are not added */
prm.remove_endRequest(ScrollFocusToFormCaller);
}
prm.add_endRequest(ScrollFocusToFormCaller);
function ScrollFocusToFormCaller(sender, args) {
if (args.get_error() == undefined) {
FocusOnForm();
}
}";
return script;
}
Sys.Application.add_load(LoadHandler); //This load handler solved update panel did not bind control after partial postback
function LoadHandler() {
$(document).ready(function () {
//rebind any events here for controls under update panel
});
}
For anyone else in my situation, I was trying to get jquery document ready function to work for a DevExpress ASPxCallbackPanel and nothing above (to-date) worked. This is what did work for me.
<script>
function myDocReadyFunction(){ /* do stuff */ }
</script>
<dx:ASPxCallbackPanel ID="myCallbackPanel" ... >
<ClientSideEvents EndCallback="function(){ myDocReadyFunction();}">
</ClientSideEvents>
<PanelCollection ...>
</dx:ASPxCallbackPanel>

Categories