Enable/Disable ASP.NET control with javascript - javascript

I'm building a page to upload an Excel file on the server for an import operation. So a found a javascript to check the file selected file extension void other file types. Now I'm trying to enable the upload ASP.NET button but javascript returns the error document.getElementById(...) is null.
Here the code:
<script type="text/javascript" language="javascript" defer="defer">
function enableControl() {
document.getElementById('button').disable = false;
}
function disableControl() {
document.getElementById('button').disable = true;
}
function checkExcelFileUpload(elem) {
var filePath = elem.value;
if (filePath.indexOf('.') == -1)
return false;
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
//Add valid extentions in this array
validExtensions[0] = 'xls';
//validExtensions[1] = 'pdf';
for (var i = 0; i < validExtensions.length; i++) {
if (ext == validExtensions[i])
return true;
}
elem.value = '';
alert('Sono ammessi solo file di Excel 97-2003');
return false;
}
</script>
<asp:FileUpload ID="fileupload" runat="server" size="50" onchange="javascript:try{if(checkExcelFileUpload(this) == true){enableControl();}else{disableControl();}}catch(err){alert(err);};" />
<asp:Button ID="button" runat="server" Text="Upload" Enabled="False" />
I serached on internet and I found other syntax for getElementById but I still have this problem.
Can you help me?
Thank you

Option 1
Since your button is a server side control, the rendered ID will be different that what you have specified. Use the following code to generate the ctl$body$button (something along these lines depending on the nesting of your controls).
document.getElementById('<%= button.ClientID %>')
Option 2
If you are using ASP.NET 4, you can use the Static client ID mode.
<asp:Button ID="button" runat="server" ClientIDMode="Static" Text="Upload" Enabled="False" />
See http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx

Instead of:
document.getElementById('button').disable = false;
You'll probably want:
document.getElementById('<%= this.button.ClientID %>').disabled = false;

Related

Validation for my ASP textboxes is not working using javascript and ASP.NET

I just want to ask why my form validation for my asp textboxes is not working. It should be like when the user does not input a text in the textbox, a description in the paragraph tag will display to please input a text. But it is not working.Please help me on solving this.
Here is the javascript code:
function checkForm() {
var errors = [];
if ($("#itemBrand").value == "") {
errors[0] = "Please input a text!";
}
if ($("#itemModel").value == "") {
errors[1] = "Please input a text!";
}
if (errors.length > 0) {
if (errors[0] != null) {
document.getElementById("itemBrandValidate").innerHTML = errors[0];
}
if (errors[1] != null) {
document.getElementById("itemModelValidate").innerHTML = errors[1];
}
return false;
}
return true;
}
And here is the aspx:
<asp:TextBox ID="itemBrand" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox><br />
<p id="itemBrandValidate"></p>
<asp:TextBox ID="itemModel" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox><br />
<p id="itemModelValidate"></p>
<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save
Item" OnClick="Button1_Click" OnClientClick="return checkForm()"/>
Add ClientIdMode = "Static" on your textboxes. Otherwise the .NET platform generates an Id which is not the same as the server ID property and your Jquery selector is not working as expected.
For example:
<asp:TextBox ID="itemBrand" ClientIDMode="static" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox>
Client side id of asp.net server controls is different from server side id.
You may use ClientIDMode = "Static" (introduced in .NET 4.0) or you might use ClientID as shown below , also I've tried to re-write your validation function a bit.
function checkForm() {
var success = true;
var itemBrandID = "<%= itemBrand.ClientID %>" ;
if ($("#" + itemBrandID).value == "") {
success = false;
document.getElementById("<%= itemBrandValidate.ClientID %>").innerHTML = "Please input a text!";
}
var itemModelID = "<%= itemModel.ClientID %>" ;
if ($("#" + itemModelID).value == "") {
success = false;
document.getElementById("<%= itemModelValidate.ClientID %>").innerHTML = "Please input a text!";
}
return success;
}
Also suggest you to read this excellent post by Rick Strahl on A generic way to find ASP.NET ClientIDs with jQuery
Hope this helps !

ASP.net C# enabling and disabling required field validator through javascript

I am using an input type "file" control in asp.net C# web page. The scenario is, when I try to browse any file using this file upload control, a textbox becomes visible and the required field validator gets enabled that controls this textbox. Also there is an input type button that reset the file in the control and text in the textbox to null. I also want to disable this required field validator on reset button click, but I am unable to do so.
I could have used aspx button control to reset the data and disable the required field validator, but this is causing loss of other information on the page. That is why I tried doing this using javascript.
I tried using a code from internet for the same. Here is my design and code:
<input ID="FileUploadDownload" type="file" name="file" runat="server" class="cssfileupload" />
<input type="button" value="Reset" id="btnClearAttachment" onclick="clearFileUploadDownload()" class="resetMe"/>
<asp:TextBox ID="TextBoxDownloadText" runat="server" placeholder="Type Download File Text" ontextchanged="TextBoxDownloadText_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTextBoxDownloadText" ValidationGroup="A" ControlToValidate="TextBoxDownloadText" runat="server" CssClass="validator" ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>
The onchange event of fileupload control is as follows:
<script type="text/javascript">
function checkFile(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if ((sFileExtension === "pdf" || sFileExtension === "png" || sFileExtension === "jpg" || sFileExtension === "gif"))
{
//...............Enable validator..................
var validatorObject = document.getElementById('<%=RequiredFieldValidatorTextBoxDownloadText.ClientID%>');
validatorObject.enabled = true;
validatorObject.isvalid = true;
ValidatorUpdateDisplay(validatorObject);
document.getElementById("TextBoxDownloadText").style.border = '1px solid red';
}
}
}
function clearFileUploadDownload() {
$("#FileUploadDownload").val("");
$('#<%=TextBoxDownloadText.ClientID%>').val("");
//...............disable validator..................
var validatorObject = document.getElementById('<%=RequiredFieldValidatorTextBoxDownloadText.ClientID%>');
validatorObject.enabled = false;
validatorObject.isvalid = false;
ValidatorUpdateDisplay(validatorObject);
document.getElementById("TextBoxDownloadText").style.border = '1px solid green';
}
</script>
In the page load event, I have disabled the required field validator:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RequiredFieldValidatorTextBoxDownloadText.Enabled = false;
}
}
Onchange event of file upload control enables required validator but on click event of reset button, the validator is not getting disbaled.
Kindly help. Thank you in advance!
Try
var valName = document.getElementById("<%=RequiredFieldValidatorTextBoxDownloadText.ClientID%>");
ValidatorEnable(valName, true);
to enable and
var valName = document.getElementById("<%=RequiredFieldValidatorTextBoxDownloadText.ClientID%>");
ValidatorEnable(valName, false);
to disable

unable to set asp.net textbox value in javascript

I'm trying to create a simple counter box next to an ASP.NET multi-line textbox. I'm using JavaScript to do this ClientSide.
<script type="text/javascript">
function textCounter(maxlimit) {
var txtField = document.getElementById('<%=txtWhatCompanyDoes.ClientId%>')
var cntCounter = document.getElementById('<%=txtWhatCompDoesChrsRem%>')
if (txtField.value.length > maxlimit) {
txtField.value = txtField.value.substring(0, maxlimit);
}
else
{
var chrsleft = maxlimit - txtField.value.length;
cntCounter.value = chrsleft;
}
}
</script>
My page code is;
<asp:TextBox ID="txtWhatCompanyDoes" onKeyUp="textCounter('txtWhatCompanyDoes', 'txtWhatCompDoesChrsRem',2000);" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
<asp:TextBox ID="txtWhatCompDoesChrsRem" runat="server"></asp:TextBox>
The problem is that it works right up to the last line of the JavaScript as I can use an alert to tell me the number of characters left, but's just not writing the value to the textbox. Am I doing something wrong?
Try adding client id on line 4 at the end of txtWhatCompDoesChrsRem
function textCounter(maxlimit) {
var txtField = document.getElementById('<%=txtWhatCompanyDoes.ClientId%>')
var cntCounter = document.getElementById('<%=txtWhatCompDoesChrsRem.ClientId%>')
if (txtField.value.length > maxlimit) {
txtField.value = txtField.value.substring(0, maxlimit);
}
else
{
var chrsleft = maxlimit - txtField.value.length;
cntCounter.value = chrsleft;
}
}
</script>
Wow, how emabarassing. I can't believe I missed that. Can I be cheeky and ask how this can be made dynamic for multiple counter boxes on one page e.g.
<script type="text/javascript">
function textCounter(field, cntField, maxlimit) {
var txtField = document.getElementById(field)
var cntCounter = document.getElementById('<%=txtWhatCompDoesChrsRem.Clientid%>')
if (txtField.value.length > maxlimit) {
txtField.value = txtField.value.substring(0, maxlimit);
}
else
{
var chrsleft = maxlimit - txtField.value.length;
cntCounter.value = chrsleft;
}
}
</script>
<asp:TextBox ID="txtWhatCompanyDoes" onKeyUp="textCounter(this.id, txtWhatCompDoesChrsRem',2000);" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
<asp:TextBox ID="txtWhatCompDoesChrsRem" runat="server"></asp:TextBox>
I can pass the first control id using "this.id" but how can I pass the counter box as a variable?
This only way I could solve this was to set the counter box as an rather than an ASP textbox.
<asp:TextBox ID="txtWhatCompanyDoes" onKeyUp="textCounter(this.id, this.form.txtWhatCompDoesChrsRem, 2000);" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
<input name="txtWhatCompDoesChrsRem" type="text" value="2000" />
every element in asp.net have inherit id like "txtWhatCompDoesChrsRem.Clientid"
so when u want to use some element in java script u can simply add one line to the element :
<asp:TextBox id="txt1" ClientID="static" ...
thats mean u can use the element directly by his name
java script :
var txtField = document.getElementById("txt1")

Disable file upload control using JavaScript

How can i disable or enable File upload control of .NET framework using Javascript??
Does any one have idea, please help.
Thanks in advance.
Try doing this:
<script type = "text/javascript">
function EnableDisable(rbl) {
var rb = rbl.getElementsByTagName("input");
document.getElementById("<%=FileUpload1.ClientID %>").disabled = true;
for (var i = 0; i < rb.length; i++) {
if (rb[i].value == 1 && rb[i].checked) {
document.getElementById("<%=FileUpload1.ClientID %>").disabled = false;
}
}
}
</script>
<form runat = "server">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" onclick = "EnableDisable(this)">
<asp:ListItem Text = "Yes" Value = "1"></asp:ListItem>
<asp:ListItem Text = "No" Value = "2"></asp:ListItem>
</asp:RadioButtonList>
<asp:FileUpload ID="FileUpload1" runat="server" disabled = "disabled"/>
</form>
Use
document.getElementById(FileUploadControlID).disabled = true;

User Control with Client + Server Side CustomValidation; Wrong Client side validator is picked

I have a user control which contains a CustomValidator which is used according to whether a RadioButton is checked or not (there are several RadioButtons, I'm only showing the relevant one)
<asp:RadioButton runat="Server" ID="RadioBetween" GroupName="DateGroup" CssClass="date_group_options_control_radio" />
<asp:TextBox ID="FromDate" runat="server" Columns="8"></asp:TextBox>
<asp:TextBox ID="ToDate" runat="server" Columns="8"></asp:TextBox>
<asp:CustomValidator ID="DateValidator" runat="server" Display="Dynamic" ClientValidationFunction="ValidateDateFields_Client" OnServerValidate="ValidateDateFields"></asp:CustomValidator>
There is some client + server side validation code (the server side code does exactly the same thing and is skipped for brevity)
<script type="text/javascript">
function ValidateDateFields_Client(source, args)
{
if ("<%=EnableValidation%>" == "True")
{
var bRadioBetweenSelected = false;
var oRadio = document.getElementById('<%=RadioBetween.ClientID%>');
if (oRadio != null && (oRadio.checked == true || oRadio["checked"] == true))
{
bRadioBetweenSelected = true;
}
if (bRadioBetweenSelected)
{
var oFromDate = document.getElementById('<%=FromDate.ClientID%>');
var oToDate = document.getElementById('<%=ToDate.ClientID%>');
if (oFromDate != null && oToDate != null)
{
var sFromDate = oFromDate.value;
var sToDate = oToDate.value;
source.innerHTML = ValidateFromToDate(sFromDate, sToDate, args);
if (!args.IsValid)
{
return;
}
}
else
{
args.IsValid = true;
}
}
else
{
args.IsValid = true;
}
}
}
</script>
There are two instances of this control in the page. When running the client side version it hits the wrong one (the version of the control which is disabled). You can see from the generated HTML both are correctly specified. I'm not sure how .NET works out which clientside function to call given they both have the same name.
<script type="text/javascript">
//<![CDATA[
var ctl00_MCPH1_QueryTextValidator = document.all ? document.all["ctl00_MCPH1_QueryTextValidator"] : document.getElementById("ctl00_MCPH1_QueryTextValidator");
ctl00_MCPH1_QueryTextValidator.controltovalidate = "ctl00_MCPH1_SearchTextBox";
ctl00_MCPH1_QueryTextValidator.focusOnError = "t";
ctl00_MCPH1_QueryTextValidator.display = "Dynamic";
ctl00_MCPH1_QueryTextValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_QueryTextValidator.clientvalidationfunction = "ValidateQueryText_Client";
ctl00_MCPH1_QueryTextValidator.validateemptytext = "true";
var ctl00_MCPH1_DisplayOptionsControl1_DateValidator = document.all ? document.all["ctl00_MCPH1_DisplayOptionsControl1_DateValidator"] : document.getElementById("ctl00_MCPH1_DisplayOptionsControl1_DateValidator");
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.display = "Dynamic";
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.clientvalidationfunction = "ValidateDateFields_Client";
var ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator = document.all ? document.all["ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator"] : document.getElementById("ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator");
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.display = "Dynamic";
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.clientvalidationfunction = "ValidateDateFields_Client";
//]]>
</script>
Do i need to add something in to scope it? What's the best way to achieve this? If I disable the loading of the second control everything works fine.
Your client validation function is generated with the same name for both your user controls. There will be two ValidateDateFields_Client() functions in your page, and of course the interpreter will only call one of them.
One way to work around that problem would be to generate unique function names:
<script type="text/javascript">
function ValidateDateFields_Client_<%=RadioBetween.ClientID%>(source, args)
{
// ...
}
</script>
<asp:CustomValidator ID="DateValidator" runat="server" Display="Dynamic"
ClientValidationFunction="ValidateDateFields_Client_"
OnServerValidate="ValidateDateFields"></asp:CustomValidator>
protected void Page_PreRender(object sender, EventArgs e)
{
DateValidator.ClientValidationFunction += RadioBetween.ClientID;
}

Categories

Resources