How to keep JQuery slideToggle down on ASP postback - javascript

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" />

Related

Control is not declared. It may be inaccessible due to its protection level

I'm really stuck and I've tried all the other examples but nothing works. I'm fairly new to ASP.NET but learning fast!
I want to use the jQuery datepicker and I am inserting this script
<script>
$(document).ready(function () {
$(function () {
$("#" + '<%=txtDOB.ClientID%>').datepicker();
});
});
</script>
and my control on the aspx page is
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>
As soon as I close the the server tag %> the red line appears under the txtDOB control and says:
txtDOB is not declared. It may be inaccessible due to its protection level.
I've made the class public in the code behind but doesn't make any difference. I've also moved the script to the bottom of the page. If I change the asp textbox to a HTML input it works fine.
It will work fine with an ASP.NET TextBox as you have used. Therefore it must be to do with where your control is located. For example, if it's inside a Repeater or Grid, you will not be able to use its ID directly like that, since the framework will generate unique ids for each row at runtime.
Create a simple webform with no other controls on the page, and you will find it works just as you have it.
Try using static ID mode instead:
<script>
$(document).ready(function () {
$("#txtDOB").datepicker();
});
</script>
It makes the client script easier (especially when you move it to an external .js file to take advantage of caching), and is an easy change to the ASP control:
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server" ClientIDMode="Static"/>
You could use a different type of jQuery selector to select for that ID as follows:
<script>
$(document).ready(function () {
$("input[id$=_txtDOB]").datepicker();
});
</script>
That selector will account for the text that is being appended to the beginning of your ID due to the use of your CreateUserWizard control. It is cleaner than the way you are currently doing it, and you can use your original HTML.
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>

jQuery file upload refreshing page

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>

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.

whats wrong in this asp.net webusercontrol code?

I have updated my code but it still not working ...
after i run my asp.net webpage and click on button the following error occurs everytime ...
Microsoft JScript runtime error: Exception thrown and not caught
<%# Control Language="VB" AutoEventWireup="false" CodeFile="WebUserControl.ascx.vb" Inherits="WebUserControl" %>
<script src="./scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#chkAll').click(
function() {
$("INPUT[type='button']").attr('click', $('#chkAll').is(':click'));
});
});
</script>
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<br />
<br />
<br />
<input id="chkAll" type="button" value="button" />
</asp:Panel>
</div>
Microsoft JScript runtime error: Exception thrown and not caught
You don't need #<%=chkAll.ClientID %> for controls that don't have runat="server"
Just use the ID.
It looks like you're trying to do exactly what's being demonstrated here. From that demo:
$(document).ready(function()
{
$("#paradigm_all").click(function()
{
var checked_status = this.checked;
$("input[#name=paradigm]").each(function()
{
this.checked = checked_status;
});
});
});
Note the key differences between what this is doing and what your code is doing. You are selecting inputs of type button and trying to change a property on them called click. That... won't work. This demo is instead selecting some inputs of type checkbox by name and setting their checked status. Additionally, it's doing it by use of a checkbox rather than a button (which appears to be your stated intention).
You can read up on jQuery selectors here. There's a lot you can use for selecting elements. In the demo, the elements have the same name attribute and can be selected as such. You should be able to set name properties in your .NET server controls for use on client-side code just as easily. Without name attributes, you could alternatively select them child elements of your Panel, or your div, etc. You may want to give some names or ids in there just to make it easy on yourself.
Edit: Based on your comment, you can just change the logic a little bit. You'd still bind to the click event as before. However, you wouldn't be able to use the elements own checked status, since a button doesn't have one. Something like this, for example:
$(document).ready(function()
{
$("#paradigm_all").click(function()
{
$(":checkbox").each(function()
{
this.checked = true;
});
});
});
This modifies the logic of the previous example (assuming you've changed the target checkbox to a button in the markup). The main differences are:
The selector for the other checkboxes now selects all checkboxes on the page. You'll probably want to target a more specific selector than this, but it works for the purpose of the demo.
The button only sets all checkboxes to checked. With this example, clicking the button again doesn't un-check them. To accomplish that you'd have to define a bit more logic. For example, if some of them are checked and the button is clicked, do they all check or all un-check? Or do they toggle? What if the user uses the button to check all and then un-checks one? Upon clicking the button again, does the one get re-checked or do the rest get un-checked? Lots of UX questions :)

Categories

Resources