Enabling Disabling button asp .net - using javascript - 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).

Related

Extracting user entry from text box and storing it in a variable in javascript

// text Box
<asp:TextBox ID="TextBox3" runat="server" BackColor="Silver"
BorderColor="Silver" ontextchanged="TextBox3_TextChanged"
style="margin-left: 6px" Width="154px"></asp:TextBox>
// Submit button
<asp:Button ID="Button6" runat="server" BackColor="Silver"
onClientclick='store_memID()' style="margin-left: 20px" Text="Submit"
Width="102px" Font-Bold="True" Height="28px" />
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
When I run the code and enter a value into the text box and then press the submit button:-
"Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined".
Else, if I remove the '.value' :-
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3');
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
and then run the program, enter value in text box and press submit then i get :-
"TimeLine is displayed for: Null"
I have been looking into solving this problem. not sure whats going wrong...
Edit (fix):- Server Side ID for my text box is 'TextBox3' but this doesn't necessarily match up with the client side ID.
to get Client Side ID:- '<%=TextBox3.ClientID%>'
It's been a while since I wrote asp forms but it is likely that the id on the client side (in your browser) is not what you think it is. This is/was one of the major pitfalls of web forms in my mind (This may have been made simpler in version 4.0, you'll have to check that). You could use a css class (and use jQuery or similar to find your element) or inject the client side id into the java script e.g.;
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('<%=TextBox3.ClientID%>').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
UPDATE: fixed case error in ClientID as pointed out in comments
You are using asp Text Boxes which are mostly used for server side code. The ID you place in the tag is not guaranteed to match the ID of the element rendered.
You will need to inspect your html in the browser to find the rendered ids. (Likely will look something like: ct100_TextBox3) and use that instead. Or, if you are not doing any server side coding, it would probably be best to convert your text boxes to <input /> fields, or <textarea />.

ie javascript form submit with file input

I have a html form, with a custom file upload field. And by that I mean that I have moved the actual file field beyond the borders of the page with css, that I have a custom input field and button in place, and that I have a jquery click event attached to that custom button to trigger the file input dialog.
It all works fine, in every browser.
But I need to submit the form through javascript. And I got somewhere that IE remembers my actions with javascript as a malicious manipulation of the file input field and blocks my access with an error "access denied" when I invoke document.formName.submit().
Is there a way around this, because I have gone completely mad by trying to search for a solution. I seriously don't want to use the default file input field, as every browsers renders it differently and messes up my design..
code:
<form name="thisForm" onsubmit="return false;" enctype="multipart/form-data" method="post" action="index.cfm/somepage">
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="text" name="shown" id="shown" />
<button id="button">browse..</button>
<input type="submit" id="submitForm" />
</form>
<script>
$('button').click(function(){
$('#shown').val($('#hidden').val());
});
$('submitForm').click(function(){
validateForm();
});
function validateForm()
{
//regular expression validation against all other input fields in the form
//not the file input field
validateVAT();
}
function validateVAT()
{
//connect to external service to check VAT
submitForm();
}
function submitForm()
{
document.thisForm.submit();
}
</script>
UPDATE:
I just tried to first upload the file, before submitting the form, through ajax, but that also gave me the acces denied error.. >_>
I was having the same problem, and I solved it by using a styled <label> tag with a slight workaround in Firefox.
http://jsfiddle.net/djibouti33/uP7A9/
The Goals:
allow user to upload a file by using standard html file input control
hide standard html file input control and apply own styling
after user selects file to upload, automatically submit the form
The Browsers:
Firefox, Chrome, IE8/9, Safari
IE7 didn't work, but it might if you add it to the workaround detailed below.
The Initial Solution:
Hide the file input by positioning it offscreen. Important not to display:none as some browsers won't like this.
Add another styled element to the page (link, button).
Listen for a click on that element, then programmatically send a click to the file input to trigger the native 'file explorer'
Listen for the file input's onchange event (occurs after a user chooses their file)
Submit the form
The Problem:
IE: if you programmatically send a click to a file input in order to activate it (2), programmatically submitting the form (5) will throw a security error
The Workaround Solution:
Same as above
Take advantage of the accessibility features built in to the label tag (clicking on a label will activate it's associated control) by styling
a label tag instead of a link/button
Listen for the file input's onchange event
Submit the form
For some reason Mozilla browsers won't activate a file input by clicking on it's label.
For Mozilla, listen for the click on the label and send a click event to the file input to activate it.
Hope this helps! Check out the jsfiddle for details on the html/js/css used to make it all work.
I found the answer myself, After 2 days of crazy trial&error. I hope I can help somebody with this..
I removed the hidden file input field from my coldfusion page and replaced it by an iframe tag. That iframe tag linked to another coldfusion page, containing another form with the removed file input field.
Now when I use javascript to click the file input field, which is still hidden from view, it still gives the browse file dialog without a hitch. But when I use javascript to submit the form, through the iframe, miraculously, it submits the form in the iframe, making it possible to upload the file in some serverside scripting of your preference.
iframe code:
<form id="formFileUpload" class="formFileUpload" name="formFileUpload" method="post" action="../actions/act_upload_file.cfm" autocomplete="off" enctype="multipart/form-data">
<input type="file" class="buttonFileHidden" id="inputFile" name="partnersLogo" />
</form>
iframe itself:
<iframe src="admin/dsp_file_upload.cfm" id="ifu" name="ifu" class="buttonFileHidden">
</iframe>
javascript click & submit:
ifu.document.formFileUpload.partnersLogo.click();
ifu.document.formFileUpload.submit();
If you're like me, and you don't want to use an iframe, and you weren't too keen on the label solution mentioned above, you can just position the original button above the styled button with an opacity of 0.
Using the example above, you would still have:
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="button" name="shown" id="shown" value="Add File" />
But .hidden would be defined like so:
.hidden {
position: absolute;
left: -150px;
opacity: 0;
filter: alpha(opacity=0);
}
Config: Set the opacity to 0.5 (or =50) to see the transparent element and tweak the left positioning.
Arguably just as hacky as the answers above, but a bootstrap-friendly solution, and in my case, the only one that worked.
I found a weird solution to solve this problem.
It thought about the js click thread. If it goes out of this thread, there no more security issues.
I chose to use window.setTimeout. see sample below:
<script type="text/javascript">
$(function () {
$("#<%= this.fuDoc.ClientID %>").bind('change', uploadFile);
$("#<%= this.btnUpload.ClientID %>").click(chooseFile);
});
function chooseFile() {
$("#<%= this.fuDoc.ClientID %>").click();
}
function uploadFile() {
var fu = $("#<%= this.fuDoc.ClientID %>");
if (fu.val() != "") {
window.setTimeout(function () {
<%= this.ClientScript.GetPostBackEventReference(this.btnUpload, "") %>;
}, 100);
}
}
</script>
<asp:FileUpload ID="fuDoc" runat="server" style="display: none;" />
<asp:Button runat="server" ID="btnUpload" Text="upload" OnClick="btnUpload_Click" />
<asp:Label ID="lbltext" Text="" runat="server" />`
then, no more acces denied!
This is an old post but the problem still arises. This may not be working because jQuery kindly fails silently. I was having this problem and wondering why my hidden form would not submit and the file get uploaded. I started off by using jQuery, but then I went vanilla. It still didn't work but looked as though an exception was being thrown in my .click() function.
Running
try {
document.getElementById('formid').submit();
} catch (e) {
alert(e);
}
showed that we indeed were throwing an error, and quick research showed that this was because IE DOES NOT SUPPORT SIMULATED CLICKS ON A FILE INPUT. This means that when the form went to be posted, IE would refuse to post the form
Excuse the bold caps, but I know many people will see text and not read it
Have you tried
$('button').click(function(){
$('form[name=thisForm]').submit()
});
You need to change onsumbit='return false;' to onsubmit='return validateForm()'.
Then have validateForm() return true if the form passes your validation checks, or false if it does not.
The onsubmit='return false' is preventing the form from submitting via document.thisForm.submit(); as well as when the user clicks the submit button.
I commented these lines in j query.form.js then every thing works fine for me. Don't ask me the reason even i don't have the solution for that but it works for sure.
if (io.contentWindow.document.execCommand) {
try { // #214
io.contentWindow.document.execCommand('Stop');
} catch(ignore) {}
}

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>

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