Using Javascript to flip flop a textbox's readonly flag - asp.net

I have a frame with several radio buttons where the user is supposed to select the "Category" that his Occupation falls into and then unconditionally also specify his occupation.
If the user selects "Retired", the requirement is to prefill "Retired" in the "Specify Occupation" text box and to disable it to prevent it from being changed. The Specify Occupation text box should also no longer be a tab stop. If the user selects a radio button other than Retired the Specify Occupation text box should be enabled and once again and the Specify Occupation text box should once again be in the normal tab sequence.
Originally, I was setting and clearing the disabled property on the Specify occupation textbox, then I found out that, upon submitting the form, disabled fields are excluded from the submit and the REQUIRED validator on the Specify Occupation textbox was being raised because the textbox was being blanked out.
What is the best way to solve this? My approach below was to mimic a disabled text box by setting/resetting the readonly attribute on the text box and changing the background color to make it appear disabled. (I suppose I should be changing the forecolor instead of teh background color). Nevertheless, my code to make the textbox readonly and to reset it doesn't appear to be working.
function OccupationOnClick(sender) {
debugger;
var optOccupationRetired = document.getElementById("<%= optOccupationRetired.ClientId %>");
var txtSpecifyOccupation = document.getElementById("<%= txtSpecifyOccupation.ClientId %>");
var optOccupationOther = document.getElementById("<%= optOccupationOther.ClientId %>");
if (sender == optOccupationRetired) {
txtSpecifyOccupation.value = "Retired"
txtSpecifyOccupation.readonly = "readonly";
txtSpecifyOccupation.style.backgroundColor = "#E0E0E0";
txtSpecifyOccupation.tabIndex = -1;
}
else {
if (txtSpecifyOccupation.value == "Retired")
txtSpecifyOccupation.value = "";
txtSpecifyOccupation.style.backgroundColor = "#FFFFFF";
txtSpecifyOccupation.readonly = "";
txtSpecifyOccupation.tabIndex = 0;
}
}
Can someone provide a suggestion to me on the best way to handle this scenario and provide a tweek to the code above to fix the setting/resetting on the readonly property?

I would use jQuery instead it's super easy to implement...
To set the textbox as readonly...
$("#myTxtID").attr('readonly', 'readonly');
To set the textbox as not readonly
$("#myTxtID").removeAttr('readonly');

I recently had to do the same thing. Here's how I solved it.
go back to using the disabled property rather than readonly.
replace the RequiredFieldValidator with a CustomValidator. in your client and server validation functions, determine if you need to check the text input based on the condition of the Retired radio button. then check for input in the text box if you need to. (on the js side you can check the disabled property on the textbox itself to save yourself a step).
on the server side you should double check the radio button selection, and if "Retired" is selected, you should make sure that "Occupation" value is actually "Retired". this gets you around the issue of not getting a value from a disabled field, and you should be doing it anyway (never trust the user and all that).

Related

C# winforms DGV Add a button to a datagrid with variable text

I know how to add a button to a datagridview. What I am having a problem with is changing the text displayed based on whether a associated record exists in another table. I would like to change the text on the button to "View SR" or "Add SR" depending on if a service request exists for the record. if it even possible, how I would go about this ?
You just need to capture the exact cell and cast it in a Grid View Button Cell to adjust the value displayed. Following is a tried solution:
if (SomeTrueValue)
{
((DataGridViewButtonCell)dataGridView1.Rows[0].Cells[0]).Value = "Hello";
}
else
{
((DataGridViewButtonCell)dataGridView1.Rows[0].Cells[0]).Value = "World";
}

Validation for Kendo AutoComplete when user does not select the value

I want the validation for kendo AutoComplete when user does not select any value from AutoComplete Value that is populated.
For Little Bit background say I do have two controls one as Kendo AutoComplete and other is Input box if user types something in the AutoComplete the values is populated and he does not select any value and switch to next control it must give a validation message that please select the value from the AutoComplete.
and Also if the user type any string in the AutoComplete and Switch to next control it must also give the validation that "hey,this value is not in the AutoComplete" so that it must not save any other data other than AutoComplete datas that is being Populated.
Heres how your auto complete is defined
#(Html.Kendo().AutoComplete()
.Name("countries")
// etc.
On submit button click event
<script>
$("#btnSubmit").click(function(){
var autoCompleteValue = $("#countries").val();
if (autoCompleteValue == "" || autoCompleteValue == null){
return false; //cancels submit action
}
// else let submit go through
});
</script>
The null check is probably useless, cuz if it doesn't have a value it's usually equal to ""
The .val() solution did not work for me, because the .val() value of the control is still the text I entered (custom text, not any of the AutoComplete values), and that's wrong.
Solution is in preventing the custom input of Kendo AutoComplete. See this link:
Kendo UI - Prevent Custom User Input in the AutoComplete

RequiredFieldValidator still validates when hidden

I have 2 fields that I need to validate, if they are displayed on the screen. When the Form initially loads, they are hidden and they will stay hidden unless an item is selected from a DropDown box. Once the value is selected, the 2 fields appear and then the validation is working correctly. However, if another value is selected that doesn't make these 2 fields appear, they are still being validated and not allowing the page to submit. Any ideas on how I can achieve this?
function DisplayOutageDates() {
if ($('#ddImpact').val() == "Service Affecting") {
$('#outageDates').css('display','');
document.getElementById('txtOutageStartDate').Visible = true;
document.getElementById('RFVOutageStartDate').Visible = true;
} else {
$('#outageDates').css('display','none');
document.getElementById('txtOutageStartDate').Visible = false;
document.getElementById('RFVOutageStartDate').Visible = false;
}
}
<asp:RequiredFieldValidator ID="RFVOutageStartDate" runat="server"
ControlToValidate="txtOutageStartDate" SetFocusOnError="true"
ErrorMessage="Please enter the Outage Start Date" />
You can use :
ValidatorEnable(val, enable):
Takes a client-validator and a Boolean value.
Enables or disables a client validator.
Being disabled will stop it from evaluating and it will always appear valid.
Found on msdn.
Using Javascript this would look like:
ValidatorEnable(document.getElementById('<%=Validator1.ClientID%>'), state);
//where state would be a boolean
In JQuery this would look like:
ValidatorEnable($("#<%= Validator1.ClientID %>")[0], state);
As found here:
http://codeclimber.net.nz/archive/2008/05/14/how-to-manage-asp.net-validation-from-javascript-with-jquery.aspx
I guess you need to show and hide the Validator controls as showing and hiding the input controls.
Update
If you hide the Validator controls using display:none; They still get rendered and involved in the validation process. You need to hide them by setting the Visible property to false. This way they won't get rendered neither involved in the validation process.

Clear data after submit button from text box and labels

i have a web form that asks for the mobile number and id, if the id or mobile are incorrect. the web page will display an error label, after this error label if i entered a correct information this form will be not visible anymore and a new div will be visible with another display. so here the problem is when the customer enters the new info after a wrong info, if he clicks back the label is still appearing and text box 2, i have set these elements to:
lblfailedresponce.Text = "" // 1rsst text box
txtMobilePhone.Text = "" //2nd text box
TransactionID.Text = "" // label
but it didn't work and they still appear. so what is the code in the submit button that i have to do to clear the cache or the fields from the invisible form?
Use the following code
txtMobilePhone.Text = String.Empty;
lblfailedresponce.Text = String.Empty;
<script>
$(document).ready(function() {
// clear error label if the user clicks on the text box.
$('#txtMobilePhone').click(function(){
if('#lblfailedresponce').val()!=null)
{
$('#lblfailedresponce').val()='';
}
$('#txtMobilePhone').val()='';
$('#TransactionID').val()='';
});
$('#TransactionID').click(function(){
if('#lblfailedresponce').val()!=null)
{
$('#lblfailedresponce').val()='';
}
$('#txtMobilePhone').val()='';
$('#TransactionID').val()='';
});
});
</script>
This is a script that will serve the purpose. Kindly use this at the page bottom and see how it works.Hope this will help you.
I assume the element Id of the text boxes and its name are same. Kindly change it if its otherwise.
If it is a caching issue then you could add Response.Cache.SetCacheability(HttpCacheability.NoCache) to your page load. That will make it so the browser will not cache the page.
Another option is that you could set your error label to visible=false and then make it visible in the code that checks your error. But then the next load after that the error label will not show as visible.

How can I get value from radio-button inserted into innerHtml

I have sort of a table with a radio-button column. I managed to make radio-button column work dynamically inserting into a cell (div if matter). But, on postback innerHtml hasn't been updated with "checked" attribute.
Could you give me an idea how can I find out (on the server) if radio-button has been checked?
More info: This is on user control inside update panel.
This would be good post on my topic, still doesn't help
Any reason you cannot use a standard asp:RadioButton and use javascript to ensure it is mutually exclusive. I have done this before by adding a custom attribute to the radiobutton and then using a js function to uncheck all items with that attribute and then check the selected one. This works around the IE issue which prevents the groupname attribute from working on radioboxes that are in different containers.
radioButton.InputAttributes.Add("ClientGroupName", "grpRadioList");
radioButton.InputAttributes.Add("onclick",
string.Format(
"javascript:radiobuttonToggle('{0}','ClientGroupName','grpRadioList');"
,radioButton.ClientID));
and use the following JS to uncheck all radios and then check the one you want.
Note i used InputAttributes instead of Attributes as the radiobutton is wrapped inside a span tag so InputAttributes is for items added to the actual input control rather than the span.
function radiobuttonToggle(selectedRB, attribName, attribValue)
{
var objRadio = document.getElementById(selectedRB);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i];
if (elm.type == 'radio')
{
if(elm.getAttribute(attribName) == attribValue)
elm.checked = false;
}
}
objRadio.checked = true;
}
You can then expose radioButton.Checked as a property in your CS file and reuse this as a control.
Check Form.Request("radio-name") != null
You only get a non-null value when it's been checked.
Make sure your page elements are being rebuilt correctly on postback. Any binding process that inserted the radio buttons the first time around will have to be re-run before you can access them the second time.
Here is a working example, first I add radios to my webform by the method you linked :
function addRadio()
{
try{
rdo = document.createElement('<input type="radio" name="fldID" />');
}catch(err){
rdo = document.createElement('input');
}
rdo.setAttribute('type','radio');
rdo.setAttribute('name','fldID');
document.getElementById('container').appendChild(rdo);
}
Then at code behind I used only the code below to get the radio's value :
string value = Request["fldID"];
So, be sure you're trying to get the name of the radio buttons at server side. You should use name attribute at server side, not id.

Resources