I am trying to use JavaScript to set a textbox text equal to "" or NULL. I am using visual studio 2013 and have created an asp.net web application. I am also using telerik controls(not sure if that will affect anything). I currently have a combobox(ddlMaritalStatus) and a textbox(txtSpouseName). I currently have JavaScript that when ddlMaritalStatus selected text is set to single then txtSpouseName is disabled. I would also like to have txtSpouseName have its text erased when ddlMaritalStatus is changed back to single. I have been researching through Google and through stack overflow and have not come across an option that works. Every answer I have found says to use document.getElementById("txtSpouseName").value = ""; but my program is not reading the .value with JavaScript.
<telerik:RadComboBox ID="ddlMaritalStatus" runat="server" EmptyMessage="--Select--" OnClientSelectedIndexChanged="DisableBox" TabIndex="15" AutoPostBack="false"></telerik:RadComboBox>
<script type="text/javascript">
function DisableBox() {
var TextBox = $find("<%=txtSpouseName.ClientID %>");
var Location = $find("<%=ddlMaritalStatus.ClientID %>");
if (Location.get_text().length < 7) {
TextBox.disable();
document.getElementById("txtSpouseName").value = "";
}
else {
TextBox.enable();
}
}
</script>
<telerik:RadTextBox ID="txtSpouseName" runat="server" Enabled="false" AutoPostBack="false" TabIndex="16"></telerik:RadTextBox>
Here is the code that I have so far. Any help or suggestions would be great! Thanks!
EDIT
I am using IE 11.
Please try with the below code snippet.
<script type="text/javascript">
function ClientSelectedIndexChanged(sender, args) {
if (sender.get_selectedItem().get_value() == "Single") {
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).value = "";
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).disabled = "disabled";
}
else {
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).value = "";
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).disabled = "";
}
}
</script>
...........
...........
<asp:Panel ID="Panel1" runat="server">
<telerik:RadComboBox ID="ddlMaritalStatus" runat="server" OnClientSelectedIndexChanged="ClientSelectedIndexChanged">
<Items>
<telerik:RadComboBoxItem Value="Married" Text="Married" />
<telerik:RadComboBoxItem Value="Single" Text="Single" />
</Items>
</telerik:RadComboBox>
<asp:TextBox ID="txtSpouseName" runat="server"></asp:TextBox>
</asp:Panel>
Let me know if any concern.
This is the answer I found from another post. This disables the textbox when "Married" is selected and erases and disable the textbox when "Single" is selected. Thank you to everyone who tried to help me!
function DisableBox(sender, args) {
var TextBox = $find("<%=txtSpouseName.ClientID %>");
if (args.get_item().get_text() == "Married") {
TextBox.enable();
}
else {
TextBox.clear();
TextBox.disable();
}
}
Related
I have Parent repeater which contains another child repeater.
For simplicity let's say that the child repeater contains text box and Requiredvalidator.
Simple example of the markup:
<asp:Repeater ID="rpt1" runat="server">
<HeaderTemplate>
....
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl1" runat="server" CssClass=".."></asp:Label>
<div class="..">
<asp:Repeater ID="rpt2" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="...">
<asp:TextBox ID="txt21" runat="server" CssClass="..." MaxLength="7" CssClass="ErrorMessage" ErrorMessage="*" />
<asp:RequiredFieldValidator ID="rfv21" runat="server" CssClass="ErrorMessage" ErrorMessage="*" />
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
I create a method like this to get the second repeater's RequiredField id:
function getId(){
var myId = document.getElementById('<%= rfv21.ClientID %>');
}
but of course it didn't work and there was an exception:
The name control-name Does Not Exist in the Current Context
So how can i do this?
I want to mention that the business need for me is that when the onchange, onkeyup, onkeydown events fires for the txt21 it will get it's equivalent rfv21 and enbale it:
I create this method which fires for onchange, onkeyup, onkeydown events changed:
function txt21_onChange(txtbox) {
var newValue = this.value;
var oldValue = this.oldvalue;
var myRfv2 = document.getElementById('<%= rfv2.ClientID %>');
if (newValue != oldValue) {
ValidatorEnable(myRfv2, true);
}
}
and i update txt21 to be:
<asp:TextBox ID="txt21" runat="server" CssClass=".." MaxLength="7" onkeyup="javascript: txt21_onChange(this);this.oldvalue = this.value;" />
but this line want work:
var myRfv2 = document.getElementById('<%= rfv2.ClientID %>');
as i explained before.
I think Item.FindControl(..) may help but how can we use it in this case?
You can bind the javascript function call from Repeater Repeater.ItemDataBound event.
Code Bahind
void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox txt21 = (TextBox)e.Item.FindControl("txt21");
RequiredFieldValidator rfv21 = (RequiredFieldValidator)e.Item.FindControl("rfv21");
txt21.Attributes.Add("onclick", "txt21_onChange('" + txt21.ClientID + "','" + rfv21.ClientID + "'" )
}
}
Javascript
function txt21_onChange(txt21ID, rfv21ID)
{
txt21ID = document.getElementById(txt21ID);
rfv21ID = document.getElementById(rfv21ID);
//The above are TextBox and RequiredFieldValidator objects of row of TextBox that triggered change event.
//You can use these object
}
The problem here is that there going to be many such controls, one per each row of each child repeater. All will have slightly different generated IDs. So instead of querying them by id (impossible), you can use jQuery to quickly find them relatively to the txt that fired an event:
function txt21_onChange(txtbox) {
var rfv2 =
$(textbox) // gives you the jquery object representing the textbox
.closest("div") // the parent div
.find("id*='rfv2'"); // the element you are looking for, id contains rfv2
This answers the immediate question in this thread on how to get hold of the element. But I am not sure it will solve your bigger problem of enabling/disabling validation. You cannot easily do so with server side controls in javascript. Besides, validator is not disabled by default in your code. Although I believe all this is worth a separate question here on SO>
I have four text boxes in 4 different tabs of an ASP.NET Page. I need to provide same validation message to all the text boxes. Presently I am using four different functions with same functionality. Kindly suggest a way to identify which textbox is being used make that a single funtion
Code from Commend:
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd"
ControlToValidate="textBox1" ErrorMessage="message"
ClientValidationFunction="fname"></asp:CustomValidator>
--Javascript Fn--
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Edit
if you are using Asp.Net then you should use like this
Aspx page code
<div>
<asp:TextBox runat="server" ID="txt1" ClientIDMode="Static" onKeyPress="javascript:text_changed(this.id);"></asp:TextBox>
</div>
JS Code
<script type="text/javascript">
function text_changed(event)
{
var id = event;
alert(id);
}
</script>
You got the textbox id in id variable and now u can get value etc using this id you are applying your conditions.... i hope this will help u
I have a repeater control all asp.net based.
<div id="repeaterDiv">
<asp:TextBox ID ="txtAnswer" TextMode="MultiLine" Columns="50" Rows="4" runat="server" />
<asp:HiddenField ID="isHid" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "IsAnswerEssential") %>' />
</div>
I am attempting to access them using Javascript so that I can perform validation on them. So I am doing it like this which is fine to some degree. I am doing it using getelementsbytagname because of the id issue with a repeater control.
var myTxtBoxes = document.getElementsByTagName('textarea');
var myHiddenField = document.getElementsByTagName('input');
for (var i = 0; i < myTxtBoxes.length; i++) {
alert(myTxtBoxes[i].value);
alert(myHiddenField[i].value);
}
The problem is the way Iam doing the above pulls all of the inputs in my page which means i end up with the hidden stuff like the viewstate generator by asp.net. Does anyone know of a clean way to do this. Thank you for any helpful information you provide.
This is what I did for anyone else.
<asp:Label ID="isHid" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "IsAnswerEssential") %>' style="display:none;" CssClass="class2" />
Here is the javascript ...
function ValidateInput() {
var cntrls2 = $('.class2')
for (var i = 0; i < cntrls1.length; i++) {
alert(cntrls2[i].getAttribute("Value"));
}
}
It has resolved this issue I highlighted initially. Though it doesn't feel very good at all. I hope it is of use. Thank you for all your advice Mason, really appreciate you taking time out to assist me.
I moved forward further with this thanks to mason once again. So I went with the HTML5 data essential data attribute.
<asp:TextBox ID="txtAnswer" TextMode="MultiLine" Columns="50" Rows="4" runat="server" CssClass="class1" data-essential='<%# DataBinder.Eval(Container.DataItem,
"IsAnswerEssential") %>' />
The javascript to gain access to the value is ...
function ValidateInput() {
var cntrls1 = $('.class1')
for (var i = 0; i < cntrls1.length; i++) {
alert(cntrls1[i].getAttribute("data-essential"));
}
}
I have to say this is really useful information which I had no knowledge about. I found this link too which might be of use to people. http://html5doctor.com/html5-custom-data-attributes/
Hi, I have following java script function:
function EnableDisableTextBox(chkBoxId, txtBoxId) {
var isChk = document.getElementById(chkBoxId);
document.getElementById(txtBoxId).disabled = !(isChk.checked);
}
When I am trying to call above function, by clicking check box its not working as expected
<asp:CheckBox ID="chkBachelors"
onclick="javascript:EnableDisableTextBox('chkBachelors','txtFirstDegree');"
runat="server" Text='<%$Resources:Resource, FirstDegree %>' TextAlign="Left"/>
<asp:TextBox ID="txtFirstDegree" CssClass="form-text" runat="server"
MaxLength="250"></asp:TextBox>
Expected Result (When user click chkBachelors check box):
if "chkBachelors" check box is checked
then enable "txtFirstDegree" text box
else
disable "txtFirstDegree" text box
What is the problem and how to solve it?
<asp:CheckBox ID="chkBachelors"
onclick="EnableDisableTextBox(this);"
runat="server" Text='' TextAlign="Left"/>
<asp:TextBox ID="txtFirstDegree" CssClass="form-text" runat="server"
MaxLength="250"></asp:TextBox>
<script language ="javascript" type="text/javascript">
function EnableDisableTextBox(checkbox)
{
var txtBoxId= "<%=txtFirstDegree.ClientID%>";
document.getElementById(txtBoxId).disabled = !(checkbox.checked);
}
</script>
<%=chkBachelors.ClientID%> and <%=txtFirstDegree.ClientID%> will give the client side ID of the Asp.Net controls .You don't need to pass them explicitly
function EnableDisableTextBox() {
var isChk = document.getElementById(<%=chkBachelors.ClientID%> );
document.getElementById(<%=txtFirstDegree.ClientID%>).disabled = !(isChk.checked);
}
I have a problem that is making me crazy. On my page I have one Javascript validation and two ASP.NET validators. The validation outcome depends just on the result of the Javascript. That means if the Javascript returns true the ASP.NET validators are not checked.
The Javascript code is:
<script type="text/javascript">
function Validate() {
var ddlObj = document.getElementById('<%=ddStatus.ClientID%>');
var txtObj = document.getElementById('<%=txtComment.ClientID%>');
if (ddlObj.selectedIndex != 0) {
if (txtObj.value == "") {
alert("Any change of Status requires a comment!");
txtObj.focus();
return false;
}
}
}
</script>
Instead the two ASP.NET validators are:
<td><asp:TextBox runat="server" ID="txtSerialNr" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="txtSerialNr" ErrorMessage="***" />
</td>
<td><asp:TextBox runat="server" ID="txtProdName" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv1" ControlToValidate="txtProdName" ErrorMessage="***"></asp:RequiredFieldValidator></td>
Anybody might help? Thanks
UPDATE:
I call the Javascript from a button:
<asp:Button runat="server" ID="btnSubmit" Text="Save New Product"
style="cursor:hand" OnClick="btnSubmit_Click" />
But I register the attribute from the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("OnClientClick", "return Validate()");
}
You can fire the client side validation from within the Validate() function:
validate = function(){
bool isValid = Page_ClientValidate(""); //triggers validation
if (isValid){
var ddlObj = document.getElementById("<%=ddStatus.ClientID%>");
var txtObj = document.getElementById("<%=txtComment.ClientID%>");
if (ddlObj.selectedIndex != 0) {
if (txtObj.value == "") {
alert("Any change of Status requires a comment!");
txtObj.focus();
isValid = false;
}
}
}
return isValid;
}
Markup:
<asp:Button runat="server" OnClientClick="return validate();" ... />
OK, there's a couple of things wrong here.
If you are concerned enough to do validation, you must ALWAYS do server-side validation in addition to client-side. Client-side validation is very user-friendly and fast to respond, but it can be bypassed simply by setting JavaScript to 'off'!
I don't see where you've told your controls which JavaScript function to call when they validate? You use RequiredFieldValidators which don't require an external function - but then attempt custom validation using your Validate() function.
If you do end up using a CustomValidator, then you'll need to change the 'signature' of your function. It needs to be of the form
function validateIt(sender, args){
var testResult = //your validation test here
args.IsValid = testResult;
}