jQuery file upload refreshing page - javascript

I saw this question, "Show Open Dialog on a Button click":
'I have to show a Open Dialog box on a button click. Basically I have to upload a file, for this I am using FileUpload control, but I don’t want to show it to user instead I want to show a Button'
And the answer was :
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function() {
$("#FileUpload1").click();
return false;
});
});
</script>
<style type="text/css">
.Class { visibility:hidden;}
</style> </head> <body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btn" runat="server" Text="Send File"/>
<asp:FileUpload ID="FileUpload1" CssClass="Class" runat="server" />
But i tried it and all it does is refreshing the page, anyone know what the problem is?

Because "FileUpload1" is not the ClientID. Just look at the generated HTML source of your page and you will see that.
You should use something like :
<script type="text/javascript">
$(document).ready(function() {
$("#<%= btn.ClientID %>").click(function() {
$("#<%= FileUpload1.ClientID %>").click();
return false;
});
});
</script>

That sounds like a security risk, and I wouldn't be surprised if security prevented that from working.
Take a look at this jQuery Ajax Upload plugin.

I would suggest you to not go that route. If you want to avoid showing FileUpload control to user.. use this.

make the client mode static to be able to access you controls like this
<asp:FileUpload ID="FileUpload1" ClientIDMode="Static" CssClass="Class" runat="server" />
<asp:Button ID="btn" ClientIDMode="Static" runat="server" Text="Send File"/>

All server-side controls (those with runat="server" attributes) have their IDs re-written by ASP.NET. Your IDs will actually look something like ctl00_MainContent_btn.
You can get around this by using <%= btn.ClientID %> server tags or by assigning a CSS class to your controls and referencing that class in JavaScript/jQuery.
Edit: You probably also need to make sure that your ASP button is not a submit button, which would cause the generated page to submit the form.

Your page refreshes because the target of your form is implicitly the current page. You need to set the target of your form to be (for example) a hidden iframe:
<form id="my-form" action="url" target="form-target" method="post">
<!-- your form here -->
</form>
<iframe id="form-target" name="form-target" style="display:none;"></iframe>
<script>
// Assuming you are using jquery
var form = $('#my-form'),
iframe = $('#form-target');
// create a function to be called each time the iframe loads
iframe.load(function () {
var responseText, iframeBody;
// Get the response from the server. It will be in the body tag of your iframe
iframeBody = $(this).contents().find('body');
responseText = iframeBody.text().trim();
// Don't continue until we actually have a response
if (!responseText) return;
// Clear the iframe's html so this function won't be called again for the same content
iframeBody.html('');
// do whatever you want with the response, for example JSON decode it
response = JSON.parse(responseText);
});
</script>

Related

jQuery hide doesn't hide any content in vb.net/asp.net webform

I am trying to hide my content by clicking the button. But when the page is loading, content is hiding but after finishing page load content is showed. This content doesn't hide. I am using Visual Studio 2017 community and asp.net/vb.net framework. But the same JQuery code is working on my text editor and my browser.
Here is my sample code:
<p id="justp" class="testcls">Hi Hide me!</p>
<asp:Button ID="testbtn" runat="server" Text="hide me" />
<script>
$(function () {
$('#testbtn').click(function () {
$('.testcls').hide();
});
});
</script>
I am try to passing alert inside hide() and it is run successfully :
$('.testcls').hide(alert("Hello"));
What is the problem?
How can I solve this?
In case your are just using this button to hide/show your content on the client side (no server side calculation or something like that) use a normal input / button tag:
Replace this:
<asp:Button ID="testbtn" runat="server" Text="hide me" />
With this line:
<button type="button" id="testbtn">Hide me!</button>
As mentioned above this solution will only work if you don't need to submit any data.
What is the problem?
The button submits your form after the click so the page will be refreshed and the view will return to the default status.
How can I solve this?
You've several ways to change this behavior :
if you have got a control on the asp code you could remove the runat="server" to prevent the button from submitting :
<asp:Button ID="testbtn" Text="hide me" />
You could simply add the return false; statement at the end of the event.
Another way is preventing the default behavior using preventDefault() like :
$('#testbtn').click(function (e) {
e.preventDefault();
$('.testcls').hide();
});
The one that I recommend to you is using UseSubmitBehavior:
<asp:Button ID="testbtn" runat="server" UseSubmitBehavior="false" Text="hide me" />
Last choice is using the plain HTML code like :
<button type="button" id="testbtn">Hide me!</button>

How to keep JQuery slideToggle down on ASP postback

I have a very simple slideToggle. Opens and closes just fine. I have some tools, a few drop downs that cause a Post Back. When the post back executes, it causes the slideToggle to go back up. How do I keep that from happening? Is there a default value setting I missed or don't know?
I have searched high and low for this answer and nothing works. I have tried so many different options and all lead to nothing. All the answers given here on the site don't work. Any other suggestions? Thanks again for the help
Here is the slideToggle code.
<script type="text/javascript">
$(document).ready(function () {
$(".Flip").click(function () {
$(".FlipPanel").slideToggle("slow");
});
}); `enter code here`
</script>
Here is the markup I use to open and expand.. With some CSS to style it.
<div class="Flip" id="testFlip" runat="server">Preferred Cargo</div>
<div class="FlipPanel">
</div>
Here a very basic example. The value of state will be loaded from the TextBox, incremented and then stored again. You will find that the value increments on every PostBack without server side code. Adapt this to store the open state of your panel.
I uses a TextBox to visualize the process, but normally you would use a HiddenField.
<script type="text/javascript">
$(document).ready(function () {
var state = $("#<%= TextBox1.ClientID %>").val();
state++;
$("#<%= TextBox1.ClientID %>").val(state);
});
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br>
<asp:Button ID="Button1" runat="server" Text="Button" />

AJAX Control Toolkit Control Editor Javascript Access

In my aspx, I have the following snippet of code, which correctly renders the Editor Control from the AjaxToolkit
<div>
<ajaxToolkit:Editor ID="Editor" runat = "server" />
</div>
In C#, to access the content of the Editor is simply:
Editor.Content = "some text here"
However in JavaScript, I am unsure how to access this. So far, I have tried:
var st =$find('<%=Editor.ClientID%>').get_content();
However the $find statement is returning a null value.
It should work. I tried the following code and editor component was found successfully.
<asp:ScriptManager runat="server" ID="ScriptManager" EnablePartialRendering="true">
<Scripts>
<asp:ScriptReference Path="Scripts/jquery-1.4.1.js" />
</Scripts>
</asp:ScriptManager>
<div>
<ajax:Editor runat="server" ID="Editor"></ajax:Editor>
</div>
<script type="text/javascript">
Sys.Application.add_load(function() {
Sys.Debug.traceDump($find('<%= Editor.ClientID %>'), "editor");
});
</script>
So, try to access you editor in Sys.Application.add_load event handler. If this will help you then the cause of the problem is that you tries to find component before page completes component initialization.
After playing around with this feature, I noticed that the HTML looks like this:
<iframe id = "Some iFrameId">
#document
<html>
<head>...</head>
<body>The text of the editor</body>
</html>
</iframe>
In the ASPX, I did the following to make my life a litle bit easier:
<div id ="myDiv" ClientIDMode="Static">
<ajaxToolkit:Editor ID="Editor" runat = "server" />
</div>
By doing this, I have simplified my problem to become find the iFrame enclosed in myDiv, which contains the HTML of the editor.
To do that in the JS
//get the iFrame
var myIframe = $("#myDiv, iframe") //this returns an array and myIframe[1] is the iFrame, which contains the text.
//get the HTML from the iFrame
var content = myIFrame[1].contentWindow.document.body.innerHTML;
Now content contains, what I was looking for. This is kind of long, and there might be an easier way, but after searching for a solution, I found most of them to be:
do a .get_content or some function call, which didn't work for my case.

Enabling Disabling button asp .net - using javascript

Currently in my application I am having a button and a text box. The user types something in the textbox and then presses the button. What I want is that:
The search button should should stay disabled when the page loads for the first time. I can achieve that by setting it to disabled in the code behind file.
Now I want it to remain disabled when the user types upto 2 characters. The moment the user types third character the button should get enabled automatically.
The important thing is that it has to be done without asp .net AJAX since this website will be run from old mobile phones. So only pretty basic javascript or jquery is supported.
Any help will be appreciated.
Thanks
Varun
in order to use the document.getElementById in asp.net and not have to use the full name, you should let asp.net provide it. Instead of:
document.getElementById("ctl00_ctl00_phContent_phPageContent_btnSearch")
Try:
document.getElementById('<%= btnName.ClientID %>')
Where btnName is the asp:Button Id. The <%= code will generate the actual button id, fully qualified, so you don't have to worry about things changing with the hard coded id.
I got this to work with a HTML text box, I don't think you can do it with a asp.net text box:
<head>
<script type="text/javascript">
function TextChange() {
var t = document.getElementById("Text1");
var b = document.getElementById("Button1");
if (t.value.length > 2) {
b.disabled = false;
}
else {
b.disabled = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" onkeyup="TextChange();" />
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="False" />
</div>
</form>
</body>
If you're using jQuery, use
$(<selector>).val().length
to get the size, then you can set the button's disabled attribute with
$(<button selector>).attr('disabled',false).

How to fire a button click event from JavaScript in ASP.NET

How do I fire a server side button click event from JavaScript?
I tried like this:
document.getElementById("<%= ButtonID.ClientID %>").click();
But no use. How can I do it?
You can just place this line in a JavaScript function:
__doPostBack('btnSubmit','OnClick');
Or do something like this:
$('#btnSubmit').trigger('click');
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
None of the solutions posted here would work for me, this was my eventual solution to the problem.
// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
Page.GetPostBackEventReference(hiddenButton);
}
// Javascript
function SetSaved() {
__doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}
// ASP
<asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>
I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...
I mean ->
I have an html submit button and an asp button like these:
<input type="submit" value="Siparişi Gönder" onclick="SendEmail()" />
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
SendToEmail() is a server side method in Default.aspx
SendEmail() is a javascript method like this:
<script type="text/javascript" lang="javascript">
function SendEmail() {
document.getElementById('<%= sendEmailButton.UniqueID %>').click();
alert("Your message is sending...");
}
</script>
And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.
Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.
Then suddenly I changed html submit button --> just html button like this and now it is working:
<input type="button" value="Siparişi Gönder" onclick="SendEmail()" />
Have a nice days...
I can make things work this way:
inside javascript junction that is executed by the html button:
document.getElementById("<%= Button2.ClientID %>").click();
ASP button inside div:
<div id="submitBtn" style="display: none;">
<asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>
Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
cmd2.CommandText = insertSuperRoster;
cmd2.Connection = con;
cmd2.ExecuteNonQuery();
string url = "VaccineRefusal.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
}
Any ideas why these lines won't execute?
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
document.FormName.btnSubmit.click();
works for me. Enjoy.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
The issue I had was the validation group that was not specified.
I added ValidationGroup="none" as per below and it worked.
<asp:Button ID="BtnQuickSearch" runat="server" Text="Search"
OnClick="BtnQuickSearch_Click" ValidationGroup="none" />
I must mention that I had 2 other forms with buttons on the page, both had their own validation groups specified. This button had did not have a validation group specified and the onclick event simply did not fire.

Categories

Resources