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.
Related
I am working on a web forms project. I have many phone number fields. I have added both a RequiredFieldValidator and a RegularExpressionValidator to each phone field as well as a PhoneNumberFormatter() javascript function to the oninput event for each asp:Textbox.
The main way to express my problem is that the RegualrExpressionValidator will still allow the asp:Button to submit the page even when there is an incomplete phone number in those boxes.
I have added a DoPost() function to the buttons OnClientClick event that cycles through all the validators and turns all the inputs red that have not met their validator's parameters. But still the RegularExpressionValidator is still allowing incomplete phone numbers to pass through when the button is pressed.
The only way that I have found to overcome this is by adding a function to agressively validate the phone length as needed, and use the setCustomValidity javascript function, which works to keep the page from submitting with incomplete numbers, but for some reason that undoes all the other boxes that I turned red for not passing their validation.
For some reason, if I click submit twice, THEN the boxes that are supposed to turn red will finally turn red. This was not a problem until I added the setCustomValidity to the phone inputs that were incomplete, otherwise the fields would turn red when expected on the first click, BUT incomplete partial phone numbers were passing through.
Basically, I want to know what I can do with basic validators and javascript to ensure the phone number is the length I need and wont interfere with the other function of turning the other required fields red when they need to.
Markup for phone input
<div class="form-group">
<label>School Contact Administrator Phone:</label>
<asp:TextBox runat="server" ID="MainContactPhone" CssClass="form-control" TextMode="Phone"
oninput="PhoneNumberFormatter(ContentPlaceHolder1_MainContactPhone); ReValidateText(ContentPlaceHolder1_MainContactPhone)"/>
<asp:RegularExpressionValidator ID="MainContactRegVal" runat="server" CssClass="text-danger"
ErrorMessage="Not a valid phone number" ControlToValidate="MainContactPhone"
ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" />
<asp:RequiredFieldValidator runat="server" ValidationGroup="ValGro" ID="MainContactVal"
ControlToValidate="MainContactPhone" InitialValue=""
Text="Required Field" CssClass="text-danger" />
</div>
Markup for Submit Button
<asp:Button runat="server" ID="IntakeTypeSubmit" Text="Next"
OnClick="IntakeTypeSubmit_Click"
CssClass="btn btn-info" ValidationGroup="ValGro" OnClientClick="DoPostIntro()" />
JS for DoPostIntro()
function DoPostIntro() {
try {
//DoPost(); //I have tried changing the order of when I do the base DoPost()
var phone = document.getElementById('ContentPlaceHolder1_MainContactPhone');
var reqVal = document.getElementById('ContentPlaceHolder1_MainContactVal');
var regVal = document.getElementById('ContentPlaceHolder1_MainContactRegVal');
ValidatePhone(phone, reqVal, regVal);
DoPost();
} catch (Error) {
alert(Error);
}
}
JS for base DoPost()
function DoPost() {
try {
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var ctrl = document.getElementById(val.controltovalidate);
if (ctrl != null && ctrl.style != null) {
if (!val.isvalid) {
ctrl.style.backgroundColor = '#FFAAAA';
}
else {
ctrl.style.backgroundColor = '';
}
}
}
document.getElementById('Warning').style.visibility = 'visible';
} catch (Error) {
alert(Error);
}
}
JS for ValidatePhone
function ValidatePhone(input, reqVal, regVal) {
if (input.value == '' && (reqVal.enabled == true || reqVal.enabled === undefined)) {
input.style.backgroundColor = '#FFAAAA';
ValidatorEnable(reqVal, true);
reqVal.style.visibility = 'visible';
}
if (input.value.length < 14 && (regVal.enabled == true || regVal.enabled === undefined)) {
input.style.backgroundColor = '#FFAAAA';
ValidatorEnable(regVal, true);
input.setCustomValidity("Invalid Phone Number");
regVal.style.visibility = 'visible';
} else {
input.setCustomValidity("");
regVal.style.visibility = 'hidden';
}
}
C# that registers the DoPostIntro()
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "DoPostIntro();");
My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {
var n = document.getElementById('text1');
var m = document.getElementById('text2');
if(n.value.trim() != "" || n.value == undefined)
{
if (n.value.trim() != "" && m.value.trim() == "")
{
alert("text1 should have some value");
return false;
}
}
if(m.value.trim() != "" || m.value == undefined)
{
if (m.value.trim() != "" && n.value.trim() == "")
{
alert("text2 should have some values");
return false;
}
}
});
As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
var _domArray = [$("#textbox1"),$("#textbox2")]
var chk = $x('textbox2').disabled = false;
$( "buttonid" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" );
this.browserEvent.preventDefault();
this.browserEvent.stopImmediatePropagation();
return false;
}
})
});
Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').
Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" )
}
})
});
Using jquery since you have tagged this with jquery
jsfiddle
I am facing very strange problem with below javascript. Compiler throw the error on line 39 of textbox code but it is very correct don’t know why this happen?.
<script type="text/javascript">
function WaterMark(txtName, event) {
var defaultText = "Enter Username Here";
// Condition to check textbox length and event type
if (txtName.value.length == 0 & event.type == "Load") {
//if condition true then setting text color and default text in textbox
txtName.style.color = "Gray";
txtName.value = defaultText;
}
// Condition to check textbox value and event type
if (txtName.value == defaultText & event.type == "TextChanged") {
txtName.style.color = "black";
txtName.value = "";
}
}
<table id="Search"><tr><td>
<cc1:ToolkitScriptManager ID="TKit" runat="server"></cc1:ToolkitScriptManager>
<asp:TextBox ID="Tbox" runat="server" Width="300" OnLoad="WaterMark(this,event);" OnTextChanged ="WaterMark(this,event);" ></asp:TextBox>
<cc1:AutoCompleteExtender
ID="Atx"
TargetControlID="Tbox"
runat="server"
UseContextKey="True"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="location"
CompletionListCssClass ="MM">
</cc1:AutoCompleteExtender>
</td></tr><tr><td>
How to overcome what is the solution for this?.!
Error Display
asp:TextBox is a server side control. It have a few server side events.
When in aspx markup attribute name match with name this events then asp try find function for this event.
In your case, i think you want add client side event handler, but asp think that you mean server side.
first: client side event on text change for input - is onchange
second: as for load event - you can't add this for input with type=text, so you can use window.onload in which check needed textbox, or see this link
So in finish your markup will be like
<asp:TextBox ID="Tbox" runat="server" Width="300" onchange ="WaterMark(this,event);" ></asp:TextBox>
and script,for example, like
<script type="text/javascript">
function WaterMark(txtName, event) {
var defaultText = "Enter Username Here";
// Condition to check textbox length and event type
if (txtName.value.length == 0 & event.type == "Load") {
//if condition true then setting text color and default text in textbox
txtName.style.color = "Gray";
txtName.value = defaultText;
}
// Condition to check textbox value and event type
if (txtName.value == defaultText & event.type == "change") {
txtName.style.color = "black";
txtName.value = "";
}
}
window.onload = function () {
var defaultText = "Enter Username Here";
var txtName = document.getElementById('<%: Tbox.ClientID %>');
// Condition to check textbox length and event type
if (txtName.value.length == 0) {
//if condition true then setting text color and default text in textbox
txtName.style.color = "Gray";
txtName.value = defaultText;
}
}
</script>
UPDATE
I think, you need use onclick event instead of onchange for your function, i.e.
<asp:TextBox ID="Tbox" runat="server" Width="300" onclick ="WaterMark(this,event);" ></asp:TextBox>
<script type="text/javascript">
function WaterMark(txtName, event) {
var defaultText = "Enter Username Here";
// Condition to check textbox value and event type
if (txtName.value == defaultText & event.type == "click") {
txtName.style.color = "black";
txtName.value = "";
}
}
window.onload = function () {
var defaultText = "Enter Username Here";
var txtName = document.getElementById('<%: Tbox.ClientID %>');
// Condition to check textbox length and event type
if (txtName.value.length == 0) {
//if condition true then setting text color and default text in textbox
txtName.style.color = "Gray";
txtName.value = defaultText;
}
}
</script>
I have some problem: I have Rad Combo Box that calls User Types and once I populate all the info I want to create JS function everytime the user click on something else in the Rad Combo Box it will pop up some message
I know that I need to use The OnSelectedIndexChange event but maybe I'm using it on the wrong way please help me
This is my Code: JS
function OnSelectedIndexChange(sender,args) {
var retValRCB = false
var l_UserType = $find("<%=rcbUserType.ClientID %>");
var l_UserTypeInd = l_UserType.get_selectedIndex();
if (!(l_UserTypeInd == null))
retValRCB = true;
else {
alert("Please select rule type");
retValRCB = false;
}
return retValRCB;
}
This is My Code in Asp:
User Type:
ID="rcbUserType" OnClientSelectedIndexChanged="OnSelectedIndexChange" EmptyMessage="Select User Type" runat="server">
function OnSelectedIndexChange(sender, args) {
var l_UserType = $find("ctl00_MainContent_rcbUserType");
var l_UserTypeInd = l_UserType.get_selectedIndex();
if (!(l_UserTypeInd == null)){
alert((l_UserTypeInd+1)+" has been selected");
}
}
I am developing a website using asp.net and C#.
I am using a RadioButtonList control. The code snippet for RadioButtonList is shown below
<asp:RadioButtonList ID="RLCompareParameter" runat="server"
RepeatDirection="Horizontal" meta:resourcekey="rsKey_RLCompareParameter"
AutoPostBack="True"
onselectedindexchanged="RLCompareParameter_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="Forms" meta:resourcekey="rsKey_RLCompareParameterListItemForms" Text="Forms"></asp:ListItem>
<asp:ListItem Value="Segments" meta:resourcekey="rsKey_RLCompareParameterListItemSegments" Text="Segments"></asp:ListItem>
<asp:ListItem Value="Questions" meta:resourcekey="rsKey_RLCompareParameterListItemQuestions" Text="Questions"></asp:ListItem>
</asp:RadioButtonList>
There is a button in the same page. While clicking on that button i want to display an alert message based on the selected radio list item using javascript. Some part of my javascript function is shown below
var RLCompareParameter = this.document.getElementById("<%= RLCompareParameter.ClientID %>");
if (RLCompareParameter.SelectedValue == "Forms") {
if (document.getElementById("<%= lbAvailableForms.ClientID %>").value == "") {
alert("Please select a form from Available Evaluation Forms ");
return false;
}
} else if (RLCompareParameter.SelectedValue == "Segments") {
if (document.getElementById("<%= lbAvailableSegments.ClientID %>").value == "") {
alert("Please select a segment from the available segments ");
return false;
}
} else if (RLCompareParameter.SelectedValue == "Questions") {
if (document.getElementById("<%= lbAvailableQuestions.ClientID %>").value == "") {
alert("Please select a Question from the available questions");
return false;
}
}
But the if(RLCompareParameter.SelectedValue == "some value") always false. i think there is no attribute like selected value for RadioButtonList control. I hope someone help me
In html, there is no such thing as a RadioButtonList. Your RLCompareParameter variable will be a reference to the table or span that is containing the three input elements (thats what the ASP.NET control outputs into your page). SelectedValue is only for ASP.NET code, not javascript.
You will have to get a reference to the specific input element itself and look at its checked property in your if statements to see whether that radio button is selected or not. There are several ways to do this. Here's one that might work:
var RLCompareParameter = document.getElementById("<%= RLCompareParameter.ClientID %>");
var radioButtons = RLCompareParameter.getElementsByTagName('input');
if (radioButtons[0].checked) {
if (document.getElementById("<%= lbAvailableForms.ClientID %>").value == "") {
alert("Please select a form from Available Evaluation Forms ");
return false;
}
} else if (radioButtons[1].checked) {
if (document.getElementById("<%= lbAvailableSegments.ClientID %>").value == "") {
alert("Please select a segment from the available segments ");
return false;
}
} else if (radioButtons[2].checked) {
if (document.getElementById("<%= lbAvailableQuestions.ClientID %>").value == "") {
alert("Please select a Question from the available questions");
return false;
}
}