help me understand JS execution on onclick event of button - asp.net

<input type="button" name="reset"
onclick="return ValidateValue(); __doPostBack('ApplyBtn','')" />
The above is the code generated for asp server button button control on browser.
Now my query is that irrespective of ValidateValue() returning true/false __doPostBack('ApplyBtn','') function is not showing any effect for me.
My understanding is that string passed to onclick acts like function body, and return will from first function will return control preventing second function from execution.
Is that correct ?
Please provide helpful inputs.

Your understanding is correct...and it's easily fixed :), instead of this:
return ValidateValue();
Do this:
if(!ValidateValue()) return false;
This way you only abort early if there is a reason to abort, otherwise you continue executing the rest.

Related

How to call a function inside a data-bind?

How to call the getStatus() function again inside this view code snippet after clicking a button?
The only thing that works form me is if I refresh the whole page.
<div id="statusContainter"data-bind="css:$data.getStatus('Rendered Approval')"> </div>
Basically, I want the getStatus('Rendered Approval') to fire if I click a button. The function is firing during initial rendering of the page. But I don't want to refresh the whole page to fire the function
Assuming getStatus is a knockout observable the code you have there sets the value, but only once. To get the value of an observable you call the function with no argument.
It sounds like you meant to do this:
<div id="statusContainter"data-bind="css:$data.getStatus()"> </div>
<button data-bind="click: $data.getStatus.bind($data, 'Rendered Approval')">Click to Refresh</button>
Update:
As #Brother Woodrow mentioned, the click binding expects a function for the handler. Passing parameters to the handler can be accomplished by wrapping it in a function literal or by using the this function as described in Note 2 here.

Checkbox click event not firing

My ASP .Net page has a repeater that is loaded from AJAX. This AJAX page repeater has a column of checkboxes. The repeater is inside a html table.
<input id="chkOptionSelected" runat="server" enableviewstate="false"
type="checkbox" data-bind="click: Add" />
On the main page, I have a label whose value is computed by a JavaScript function. My view model:
function VM() {
var self = this;
self.totalSqft = ko.observable(TotalSqFt);
self.Add = function () {
self.totalSqft(TotalSqFt);
return true;
};
}
ko.applyBindings(new VM());
TotalSqFt is a global variable. The label is:
<asp:Label ID="lblTotalSqFt" runat="server" ClientIDMode="Static" data-bind="text: totalSqft"></asp:Label>
The click event computes the new total in a javascript function. All the view model needs to do is update the label with the new value.
What am I doing wrong? Is it because the checkbox is inside of AJAX content? I can see it all in the view source.
like #Jeroen said, asp:Lable will processed by server and render differently at client side.
so instead you can use normal html label and use runat="server" if you want to access it at server
check this working demo http://jsfiddle.net/91mek1tk/
The direct cause of your issue is most likely that data-bind on an asp:Label is not rendered. You would need to call Attributes.Add or something similar to add it.
Having said that, you're mixing Webforms and client-side heavy tech like KnockoutJS in a way that will probably negate the advantages you'd get from using KO, or worse cause lots of inconvenient cases like the one you're having now. I suggest either moving away from asp controls to more html-oriented controls (like you did with the first input tag), or dropping KO in favor of other, simpler client side technology (which seems more appropriate anyways, since you're currently using KO merely to handle clicks, whereas it excels mostly at two-way data-binding tasks).
Try this for your javascript function:
function VM() {
var self = this;
self.totalSqft = ko.observable("totalSqft");
self.Add = function () {
self.totalSqft("totalSqft");
return true;
};
}
ko.applyBindings(new VM());
Thank you, JAG. I tweaked the demo and got it working. I had val instead of text for my label in one of the lines and hence was not seeing the reflected value. It's working now. Thanks, everyone.

Using button control in google maps API

I am using the following code to cause events based upon button clicks. When I click the button,the page reloads but no change occurs in the map
form action="#" onsubmit="animate(); return false" p inputtype="submit"value="Zoom!" / /p /form function animate() { map.setZoom(10); }
Can anyone help me out with this?
Thank you
If you've got return false, and the page reloads, that usually implies to me that there's a javascript error. Check the javascript error logs, or use Firebug, to see if there are errors happening. e.g. is map defined as a global variable?

jquery dropdown selector AutoPostback

In jQuery is there any way to distinguish between postbacking dropdowns and non-postbacking ones(ASP.NET 3.5):
$('select').change(function(e)
{
//something like this
if ($(this).attr('AutoPostback') == true)
{
//do something here
}
else
{
//do something else
}
Think have to call server side function from script here to determine AutoPostback.
Typically, a dropdown that is going to postback will have an onchange attribute that contains something like "__doPostBack(" though there will also be some other stuff in there.
So you could do something like the below, which I didn't test so hopefully there is no typos
$('select[onchange*="__doPostBack("]').change(...your handler for postbacking control...);
$('select:not([onchange*="__doPostBack("])').change(...your handler for non-postbacking control...);
The AutoPostBack attribute, IIRC, is server-side. In otherwords, it's parsed by the server and never actually makes it to the browser.
It'd be a bit redundant code-wise, but you could give it a cssClass="AutoPostback" and then check for that via jQuery
I came upon this thread a little late but perhaps someone else along the way will find this useful.
I also was having issues getting the jquery ui selectmenu to do a postback. the previous comments got me pretty close but errors came up when i ran it. This may be due to the different version i am using but my final fix was to attach the postback to the change event a little differently. I had to pass strings to the postback call instead of the actual element. First parameter is the ID of the select element and the second perameter is the name of the server side function that is supposed be called.
$("#cboStateFilter").selectmenu({
change: function (event, ui) { __doPostBack("cboStateFilter", 'cboStateFilter_SelectedIndexChanged'); }
});

JavaScript puzzle to solve : window.confirm = divConfirm(strMessage)

Scenario is : old site which has lots of JS code already written. If user want to change all the alert messages to new age jazzy Div based alert which are very common using JQuery, YUI, Prototype... etc.
There are mainly tree JS dialogs
1. alert
To changes this its simple we just have to write new function which will show the div popup and show the message, after that override the window.alert
function showDivAlert(strMessage){
//div popup logic and code
}
window.alert = showDivAlert;
2. prompt
This too look easy to write function to accept the string and show the text box for input value. Now as return action is based on the click of "OK" button life is easy here.
function shoDivPromp(strMessage){
//div pop up to show the text box and accept input from the user
}
window.prompt = shoDivPromp;
3. confirm
Now above two were easy to override and modify the default dialogs but there is complication with the confirm.
However default JS confirm dialog stops JS execution and when user click OK or Cancel execution is resumed by determining the return value (true/false). But if we user div popup the execution is not stopped which is problem. We can still implement the confirm but in that case we have to bind methods for OK and CANCEL case which will be attached to OK and CANCEL button. With this function signature will be like.
function newConfirm(msg, fun OkAction(), fun CancelAction)
Now this is problem that this cant help me change the confirm dialog across the site as we did with alert();
Question
I am not sure whether its possible or not to achieve but i think can be using some JS pattern. So let me know if its possible.
Now this is problem that this cant help me change the confirm dialog across the site as we did with alert();
That's correct. It's not possible to reproduce the synchronous nature of the alert/confirm/prompt functions in native JavaScript. There is the non-standard method showModalDialog which can do it using a separate pop-up document, but it's not supported by all browsers and it's generally considered highly undesirable.
So the plug-in-replacement strategy isn't going to work. You are going to have to change every place you called these methods in the rest of the script.
The usual pattern is to do it using inline anonymous functions, to preserve the local variables using a closure, eg. replace:
function buttonclick() {
var id= this.id;
if (confirm('Are you sure you want to frob '+id+'?'))
frob(id);
wipe(id);
}
with:
function buttonclick() {
var id= this.id;
myConfirm('Are you sure you want to frob '+id+'?', function(confirmed) {
if (confirmed)
frob(id);
wipe(id);
});
}
If you need this to be preserved you would need to look at a further nested closure or function.bind to do it. If you have your call to confirm in a loop things get considerably more difficult.
Obviously you also have to ensure that critical global state doesn't change whilst the confirm box is up. Usually this risk is minimised by greying out the rest of the page with an overlay to stop clicks getting through. However if you have timeouts they can still fire.
All 3 methods actually stop js execution, not just the confirm, because they're all modal dialogs. Personally, I would try to keep everything as asynchronous as possible as modal dialogs prevent interaction with the current document.
Your best bet is to use callback functions from the new confirm popup as you suggested yourself.
I'm having a hard time understanding exactly what you want to achieve. It sounds like you want to do something like the following:
Run some javascript code
Display a "confirm" box
Wait until the ok button or cancel button is clicked
Continue code when user clicks ok, return when user clicks cancel.
The reason you want to do this is that overriding the function with something that makes use of callbacks would require rewriting each section of code that uses the confirm function. If you want my advice, I would go ahead and rewrite the code so that it performs asynchronously. There's no way you can delay script execution without locking up the document which includes the OK and Cancel actions of your dialog.
if you changed the roles Alert / Prompt / Confirm. slows the execution pending user interaction to run the following code.
Overriding these functions, the code continues its execution.
To achieve this you have to modify each part of the code and work as if you were with asynchronous functions.
Then you can use any plugin for windows as sexy-alert-box, and overwrite Alert / Prompt / Confirm
The function signature would simply be:
function newConfirm(msg, okAction, cancelAction);
and would be used as:
function newConfirm(msg, okAction, cancelAction){
var ok = doWhateverPromptIsNecessary();
if (ok) {
okAction();
} else {
cancelAction();
}
}
That is, to pass function "pointers" in to a function as arguments, simply pass in the function name without the (). The function signature is the same.

Resources