ASP.net C# enabling and disabling required field validator through javascript - 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

Related

Call javascript from textbox clear 'x' event

I have two fields where the user can only write in one or the other, we validate the client side using the javascript below. The problem that I have is that the textboxes by default have a clear 'x' that when used doesn't trigger the javascript leaving one of the fields disabled.
How can I call the javascript function when the user clicks the clear 'x' of the textbox in order to get both fields enabled?
<asp:TextBox ID="txtFIELD1Val" runat="server" onKeyup="javascript:clearFields();" TabIndex="1" CssClass="cssTextbox"></asp:TextBox>
<asp:TextBox ID="txtFIELD2Val" runat="server" onKeyup="javascript:clearFields();" TabIndex="2" CssClass="cssTextbox"></asp:TextBox>
function clearFields() {
var txtFIELD1 = document.getElementById('<%= txtFIELD1Val.ClientID %>');
var txtFIELD2 = document.getElementById('<%= txtFIELD2Val.ClientID %>');
//Enable/Disable FIELD1 and FIELD2 fields based on text.
if (txtFIELD1.value == "" && txtFIELD2.value == "") {
txtFIELD1.disabled = false;
txtFIELD2.disabled = false;
}
else if (txtFIELD1.value == "" || txtFIELD2.value != "") {
txtFIELD1.disabled = true;
txtFIELD2.disabled = false;
}
else if (txtFIELD1.value != "" || txtFIELD2.value == "") {
txtFIELD1.disabled = false;
txtFIELD2.disabled = true;
}
}
Remove IE10's "clear field" X button on certain inputs?
See the second answer, seems to be the best approach to getting rid of the 'X' and the problems it's causing.

Ajax autocomplete Extender prevent to type invalid value in text box

am using Ajax AutoCompleteExtender in asp textbox as below.
it's working fine but,
Problem: when user type text which is invalid or not match from the database value, it should show a message to user like "keyword not matched..."
Code
<asp:HiddenField id ="hdnFieldValue" runat="server"/>
<asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="2"
CompletionInterval="100" OnClientItemSelected="ClientItemSelected" UseContextKey="true" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
Java Script Code
<script type="text/javascript">
function ClientItemSelected(sender, e) {
$get(e.get_value());
$get("<%=hdnFieldValue.ClientID %>").value = e.get_value();
}
</script>
I am get value using above javascript method into asp hidden field. But I want to set Empty into hidden field when user type invalid text
Please give me suggestions.
Thanks.
ADD IN YOUR AUTOEXTENDER :
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" OnClientPopulated="ClientPopulated"
</cc1:AutoCompleteExtender>
JS : From below you can highlight your Text with result,same way you can check for text
<script type="text/javascript">
function ClientPopulated(source, args) {
if (source._currentPrefix != null) {
var list = source.get_completionList();
var search = source._currentPrefix.toLowerCase();
for (var i = 0; i < list.childNodes.length; i++) {
var text = list.childNodes[i].innerHTML;
var index = text.toLowerCase().indexOf(search);
if (index != -1) {
var value = text.substring(0, index);
</script>

Enable/Disable ASP.NET control with 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;

how to capture javascript var value into asp.net page

I have an asp.net page on which at a click on Button (btn1), i want to show message box asking user a question "Do you want to overwrite ?" with button "Ok/Overwrite" and "Cancel" , and based on user response , i will have to update my database.
So i was trying to accomplish it using Javascript Confirm function
var r = Confirm('Do you want to overwrite ?)
but now i have to capture this Var r into my page so that i can update my database accordingly
any help how can i do it ?
On this scenario, you don't need to pass in the value of r to the server; you simply don't postback.
Just have something like this:
<asp:button id="btn1" runat="server" OnClientClick="return confirm('Overwrite?');" OnClick="btn1_Click" Text="Submit" />
If the users clicks "OK" then the page will post back and you will update the DB. If the user clicks cancel, the page won't postback at all and you won't have to do anything.
Here is your code:-
Add a hidden field in Net(.aspx) page
<form id="form10" runat="server">
<asp:HiddenField ID="hdnField" runat="server" Value="false" />
</form>
The hidden field should be added under Form Tag.The value of this hidden field is initially "false".
Here is what you need to do in Code Behind file (.cs file)
protected void btnSubmits_Click(object sender, EventArgs e)
{
if (hdnField.Value == "false")
{
AddJavascriptCode(itemValue);
}
else if (hdnField.Value == "true")
{
lblMsg.Text = string.Format("You have entered {0}", itemValue);
hdnField.Value = "false";
}
}
Here is the code to capture the response from OK/Confirm or Cancel button.
private void AddJavascriptCode(string itemValue)
{
string script = #"<script language=""JavaScript"" type=""text/javascript"">
window.onload=function()
{
var IsConfirm = 1;
objField = document.getElementById('" + hdnField.ClientID + #"');
objSubmit = document.getElementById('" + btnSubmit.ClientID + #"');
IsConfirm = newConfirm('Test','You have entered " + itemValue + #" value. Do you want to overwrite ?',1,1,0);
if(IsConfirm == true)
{
objField.value = 'true';
objSubmit.click();
}
else
{
objField.value = 'false';
}
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
}
}
Hope this helps you :).

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