Is it possible to fire an OnClick event upon clicking the asp:FileUpload button?
you can use flash code it will file uploader as button which is clickable. but for this you need to download swfupload.swf file.
<input type="file" id="uplaodExcel" name="uplaodExcel" />
following is the javascript code:
Sys.Application.add_init(function () {
HideError();
$("#uplaodExcel").makeAsyncUploader({
upload_url: 'EventName',//Event you want to occur on click
flash_url: '../Scripts/swfupload.swf',//flash file path that you download
button_image_url: '#Url.Content("~/Content/blankButton.png")',// for button style
file_size_limit: "10MB",
file_types: "*.XLS; *.xlsx", //File extension you can provide any
disableDuringUpload: 'INPUT[type="submit"]',
upload_success_handler: function (file, server_data, receivedResponse) {
var data = "";
try {
// you can add your code here
} catch (e) { }
}
});
});
according to w3schools an input of type file can support all standard events.
so what you can do is wirte to your control a javascript event for the click:
YOURCONTROL.Attributes.Add("onclick","YourLogic");
Related
I have an anchor tag with the href set as:
; Click Here
When I click on Click here, it redirects to http://mywebsite/$myfunction(1234).
This page obviously does not exist. How do I ensure that clicking on the above link does not map to the root? I would like it to call the javascript function.
Note: I cannot do this:
Click Here.
The reason is that we have a 3rd party crawler (no source code available) that searches for anchor tags on our page and picks up the href part for the link and fails if not found in the exact format $myfunction(param)$
HTML anchor link specification does not support adding a javascript function as the value of the href attribute. Per https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a you should add an URL or an URL fragment.
If you need to add it this way you can add the onclick event to anchor like this:
; Click Here
Then you just need to make sure you function returns false and/or calls event.preventDefault this is to avoid redirection.
You can use the onClick event handler to call the function and prevent the default action of the link with event.preventDefault().
Click Here
<br/>
Link that does NOT have its default action prevented
<script>
function myfunction(e){
e.preventDefault();
console.log("Function myfunction() called");
}
function function2(){
console.log("Function function2() called");
}
</script>
have you tried to invoke the onClick handler?
; Click Here
Another approach is the following
function MyFunction(param){
alert(param);
}
(function() {
var aElements = document.getElementsByTagName("a");
var aList = Array.prototype.slice.call(aElements);
aList.forEach(function(elem) {
var regex = /\$(.*?)\$/g;
var result =regex.exec(elem.href);
if (result != undefined && result.length > 0) {
elem.onclick= function(){
//executes function
eval(result[result.length-1]);
//prevents href action;
return false;
}
}
});
})();
I have a function
<br/>
I have a normal link
<br/>
I have another function
You can use the 'onclick' attribute of the link tag instead of href,
For example "Click Here"
The issue I am facing now is a button click event is automatically being fired when enter key is pressed in Html.TextBoxFor(). I am having a main view. In this view there are 3 buttons. On each of 2 button click a partial view is opened and during 3rd button click, a new view is opened. Please see the code below :
<script>
$(document).ready(function () {
SetUpDatePickers();
});
$('#button1').click(function (event) {
$('#divdefinetraj').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
GetTrajectories();
});
$('#button2').click(function (event) {
$('#divRequestTT').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
});
$('#button3').click(function (event) {
window.location.href = '/UserManagement/UsersList/';
event.preventDefault();
});
</script>
I clicked button1 and the first partial view is opened :
The partial view has below code :
#Html.TextBoxFor(u => u.TrajName, new { #class = "txtboxclass", #id = "TrajName" })
My issue is when I press "Enter" key inside this text box, the code for button1 in main view is being executed :
$('#button1').click(function (event) {
$('#divdefinetraj').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
GetTrajectories();
});
This results in all the buttons being hidden and the view becomes useless unless user reloads the view forcefully.
I tried to handle the onchange() event of the textboxfor and redirected to below function, but it doesn't handle.
function EnterKeyFilter() {
if (window.event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
}
}
Even I tried the same function for div - click() .. It doesn't work.
When I press the enter key the exact button1 click is being handled with this information event = j…y.Event {originalEvent: MouseEvent, type: "click", timeStamp: 7055.025000000001, jQuery110208686809991100928: true, toElement: button#button1.
But I am not clicking it either. The partial view is not part of a form also and form submission is not the issue. I am new to ASP.NET MVC and confused with this strange behavior. Please help. Thanks in advance.
If you want to disable your press enter in your keyboard, try this:
$(function () {
//On your document ready function, add this:
$('html').bind('keypress', function (e) {
if (e.keyCode == 13) {
return false;
}
});
}
Try to keep all three buttons in different form tags and made them submit button.
So in this case, whenever you hit enter in a form input, respective button will be clicked. To prevent full page postback, use e.preventDefault() in button click event.
HTML:
<form id="frm1">
-------------
-------------
<input id="btnSubmit" type="submit" value="submit" />
</form>
jQuery
$("#btnSubmit").click(function(e){
e.preventDefault();
-- rest of code
});
I am registering java script to my Asp.net code behind file, which is working fine. Now, I have some update panels on the same page and problem is whenever there is any change in any of the update panel, this script is automatically getting called. Is there any way that I can stop this happening. I can't remove update panels from my page and this script is also a very essential part of the application. In this situation I am just calling a alert (rad alert with set time out functionality) when Save Button is clicked or an Update routine is called while I have few other buttons in update panels and whenver any of the button which is registered to the update panels clicked, the following script is called un-willingly. Anyone's help will really be appreciated.
following is my Page.ClientScript
string radalertscript = "<script language='javascript'> Sys.Application.add_load(function(sender, e) {var oWnd = radalert('dialogMessage', 400, 140, 'Saved');window.setTimeout(function () { oWnd.Close(); }, 3000);});</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);
You can assign empty string to same key radalert to remove the script.
if(some_condition)
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", "");
Edit: Based on comments, you can make it simple without using RegisterStartupScript
In code behind
btnSave.Attributes.Add("", "saveButtonFunction();");
In Javascript
<script language='javascript'>
Sys.Application.add_load(function(sender, e) {
if(btnSaveClicked){
var oWnd = radalert('dialogMessage', 400,140, 'Saved');
window.setTimeout(function () { oWnd.Close(); }, 3000);
btnSaveClicked = false;
}
});
btnSaveClicked = false;
function saveButtonFunction(){
btnSaveClicked = true;
};
</script>
Thank you very much for your answer Adil. I already have followed the same approach with little difference. I have taken JavaScript out from my code behind file and have registered Sys.Application.add_load event as follow
Sys.Application.add_load(DisplayRadAlertHandler);
function DisplayRadAlertHandler() {
var getMessage = document.getElementById('<%=radAlertDialogHidden.ClientID%>').value;
if (getMessage != "") {
document.getElementById('<%=radAlertDialogHidden.ClientID%>').value = "";
var oWnd = radalert(getMessage, 400, 140, 'Saved');
window.setTimeout(function () { oWnd.Close(); }, 3000);
}
}
Here I am setting my alert message in a hidden input field from code behind file and in the above event handler I am just checking if message is there than reset the hidden field and display the message. Your approach is also right and I have marked your answer but as I am displaying my message from multiple locations (Save button, Update routine etc.) so by assigning value to hidden input field and than resetting in above event handler looks more appropriate. Thanks once again for your help.
On some links on my HTML page I have a special CSS class, that when clicked, I make a ajax call to a click.aspx page and track the click.
blah-1
$(".click").bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
So what is happening is the value of source, after clicking a few links (that open in a new window) becomes:
source=blah1
then it becomes
source=blah1,blah2
Maybe you need to change it to:
$(".click")each(function(i) {
$(this).bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
});
so that each is processed separately...
I am validating a zip code using Javascript that is generated server-side, and injected when a LinkButton is clicked. Then, I retrieve the return value by calling a server-side function when the page loads.
This works nicely, but the problem is that the ViewState is completely lost after PostBack. Below is the code, starting with the page_load event, the button click event, and then the callback called from the page_load event.
Is there a way I can somehow save the ViewState, maybe easily in a session variable? Or is there a workaround I can use?
// In Page_Load
if (Request.Form["__EVENTTARGET"] == "CallFunction") {
GetValidateZipCodeScriptReturnValue(Boolean.Parse(Request.Form["__EVENTARGUMENT"].ToString()));
}
// OnClick for LinkButton
private bool ValidateZipCode(string zip) {
StringBuilder script = new StringBuilder();
script.Append("<script language='javascript' type='text/javascript'>");
script.Append(#"var regex = /^\d{5}$|^\d{5}-\d{4}$/;");
script.Append("__doPostBack('CallFunction', regex.test(" + zip + "));");
script.Append("</script>");
Type t = GetType();
if (!ClientScript.IsClientScriptBlockRegistered(t, "ValidateZipCodeScript")) {
ClientScript.RegisterClientScriptBlock(t, "ValidateZipCodeScript", script.ToString());
}
return false;
}
// Method called on PostBack to get the return value of the javascript
private void GetValidateZipCodeScriptReturnValue(bool valid) {
m_ZipCode = uxZip.Text;
if (valid) {
Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
ProductCode, ZipCode));
}
else {
Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
SetupPostBackViewState();
ScrollToZipCode();
}
}
Why not just use the OnClick event of the LinkButton? Or, better yet, look into the CustomValidator control, since it looks like all you're trying to do is validate a zip code and that's exactly what a CustomValidator can do (you'll need to look at the ClientValidationFunction, which is where you want to put your regex test).