Use JavaScript to disable fields in a HTML form - javascript

I have two fields in a HTML form:
<input type="text" name="name1"/>
<input type="text" name="name2"/>
Is there a way using JavaScript that if the user user has entered text into the first test box, the second textbox is disabled and vice-versa?

You could do it with jQuery by disabling the input that wasn't being typed in using the keyup() event in conjunction with the not() method. That would look like this:
$(function() {
var textLength;
$('input').keyup(function() {
textLength = $(this).val().length;
if (textLength > 0) {
$('input').not(this).attr('disabled','disabled');
} else {
$('input').removeAttr('disabled');
}
});
});
input[type="text"]:disabled {
background: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name1"/>
<input type="text" name="name2"/>

Here is an very simple example(jsfiddle link below):
<input type="text" name="name1" id="name1" placeholder="Name 1"/>
<input type="text" name="name2"id="name2" placeholder="Name 2"/>
var name1 = document.getElementById('name1'),
name2 =document.getElementById('name2');
name1.onkeyup = function(e) {
if (name1.value.length > 0) {
name2.setAttribute('disabled', 'disabled');
} else {
name2.removeAttribute('disabled');
}
}
name2.onkeyup = function(e) {
if (name2.value.length > 0) {
name1.setAttribute('disabled', 'disabled');
} else {
name1.removeAttribute('disabled');
}
}
https://jsfiddle.net/Neviton/81zzjabk/

jQuery way:
At first you have to create CSS class 'disabled'.
<style>
.disabled {
opacity: 0.5;
pointer-events: none;
}
</style>
Then you add event listener 'change' to your inputs.
$( "input[value='name1']" ).change(function() {
$("input[value='name2']" ).addClass('disabled');
});
and
$( "input[value='name2']" ).change(function() {
$("input[value='name1']" ).addClass('disabled');
});
That will do the trick. When user changes value of input it adds class 'disabled' to another input.

This is an answer in clear JavaScript. The advantage of using the disabled property is, that even with tabulating it is not possible to put an input into the other field.
In the snippet the disabling is also reset if both input fields are empty.
var in1 = document.getElementById("input1"),
in2 = document.getElementById("input2");
function doOnChange() {
if (in1.value != "") {
in1.disabled = false;
in2.disabled = true;
} else if (in2.value != "") {
in1.disabled = true;
in2.disabled = false;
} if (in1.value == "" && in2.value == "") {
in1.disabled = false;
in2.disabled = false;
}
}
in1.addEventListener("keyup", doOnChange);
in2.addEventListener("keyup", doOnChange);
<input id="input1" />
<input id="input2" />

function myFunction() {
var a = document.getElementById('input1');
var b = document.getElementById('input2');
if (a.value.length == 0 && b.value.length == 0) {
a.disabled = false;
b.disabled = false;
} else if (a.value.length == 0) {
a.disabled = true;
} else if (b.value.length == 0) {
b.disabled = true;
}
}
<input type="text" id="input1" onkeyup="myFunction()" />
<input type="text" id="input2" onkeyup="myFunction()" />

Related

How to disable "Save" until fields have passed validation. NO <form> tags

On the client-side, I would like to somehow disable the "Save" button in case the validation has not passed. The solution is validating individual fields like so:
//checking if null
$("#editAccountName").blur(function () {
var editAccountName = $("#editAccountName").val();
if (editAccountName == "" || editAccountName == null) {
$("#editAccountNameError").html('<font color="#cc0000">The account name is required</font>');
$("#editAccountName").css("background-color", "#cc0000");
}
else {
$("#editAccountNameError").html('<font color="#cc0000"></font>');
$("#editAccountName").css("background-color", "transparent");
}
});
//checking if null
$("#editAddress").blur(function () {
var editaddress = $("#editAddress").val();
if (editaddress == "" || editaddress == null) {
$("#editAddressError").html('<font color="#cc0000">The address is required</font>');
$("#editAddress").css("background-color", "#cc0000");
}
else {
$("#editAddressError").html('<font color="#cc0000"></font>');
$("#editAddress").css("background-color", "transparent");
}
});
//checking if null
$("#editCity").blur(function () {
var editCity = $("#editCity").val();
if (editCity == "" || editCity == null) {
$("#editCityError").html('<font color="#cc0000">The city is required</font>');
$("#editCity").css("background-color", "#cc0000");
}
else {
$("#editCityError").html('<font color="#cc0000"></font>');
$("#editCity").css("background-color", "transparent");
}
});
//checking if null
$("#editState").blur(function () {
var editState = $("#editState").val();
if (editState == "" || editState == null) {
$("#editStateError").html('<font color="#cc0000">The city is required</font>');
$("#editState").css("background-color", "#cc0000");
}
else {
$("#editStateError").html('<font color="#cc0000"></font>');
$("#editState").css("background-color", "transparent");
}
});
//no nulls or letters
$("#editZip").blur(function () {
var regexnumbers = /\d+-?/;
var editzip = $("#editZip").val();
if (!regexnumbers.test(editzip) == true || editzip == '' || editzip == null) {
$("#editZipError").html('<font color="#cc0000">The numeric zip code is required</font>');
$("#editZip").css("background-color", "#cc0000");
}
else {
$("#editZipError").html('<font color="#cc0000"></font>');
$("#editZip").css("background-color", "transparent");
}
});
//*optional*
//needs to be exactly 10 digits in case anything is entered in any of the boxes
$("#editArea,#editPrefix,#editSuffix").blur(function () {
var phone = $("#editArea").val() + $("#editSuffix").val() + $("#editPrefix").val();
if (phone.length > 0 && phone.length < 10) {
$("#editPhoneError").html('<font color="#cc0000">The phone number must be 10 digits</font>');
$("#editArea").css("background-color", "#cc0000");
$("#editPrefix").css("background-color", "#cc0000");
$("#editSuffix").css("background-color", "#cc0000");
}
else {
$("#editPhoneError").html('<font color="#cc0000"></font>');
$("#editArea").css("background-color", "transparent");
$("#editPrefix").css("background-color", "transparent");
$("#editSuffix").css("background-color", "transparent");
}
});
I know this is not the cleanest solution but I can't make use of the Jquery plugin since that requires me to place the fields between <form> tags (which conflicts with other functionality). The markup looks like this:
<label>Clinic Name</label>
<input id="editAccountName" name="editAccountName" class="accountEdit" type="text" value="#Model.Pharmacy.AccountName" /><span id="editAccountNameError" value="0"></span>
<label>Address</label>
<input id="editAddress" name="editAddress" class="accountEdit" type="text" value="#Model.Pharmacy.Address" /><span id="editAddressError" value="0"></span>
<label>City</label>
<input id="editCity" name="editCity" class="accountEdit" type="text" value="#Model.Pharmacy.City" /><span id="editCityError" value="0"></span>
<label>State</label>
<input id="editState" name="editState" class="accountEdit" type="text" value="#Model.Pharmacy.State" maxlength="2"/><span id="editStateError" value="0"></span>
<label>Zip</label>
<input id="editZip" name="editZip" maxlength="5" class="accountEdit" type="text" value="#Model.Pharmacy.ZipCode" /><span id="editZipError" value="0"></span>
<label>Phone Number (optional)</label>
<div>
<input id="editArea" maxlength="3" onkeyup="tabout(this,'editPrefix')" name="editArea" style="float:left; width:70px;" type="text" value="#Model.Pharmacy.Area" depends />
</div>
<div>
<input id="editPrefix" maxlength="3" onkeyup="tabout(this,'editSuffix')" name="editPrefix" style="float:left; width:70px;" type="text" value="#Model.Pharmacy.Prefix" depends />
</div>
<div>
<input id="editSuffix" maxlength="4" onkeyup="tabout(this,'editPrefix')" name="editSuffix" style="float:left; width:70px;" type="text" value="#Model.Pharmacy.Suffix" depends />
</div>
<span style="margin-left:-208px; margin-top:50px;" id="editPhoneError" value="0"></span>
</div>
<input id="btnCancel" type="button" value="Cancel" />
<input id="btnSave" type="button" value="Save" />
Any suggestions?
So first, instead of setting the background-color on each field when it fails validation, I'd use a special css class - like "error" - that itself defines the look of each field. Then something like this:
if (editaddress == "" || editaddress == null) {
$("#editAddressError").html('<font color="#cc0000">The address is required</font>');
$("#editAddress").css("background-color", "#cc0000");
}
else {
$("#editAddressError").html('<font color="#cc0000"></font>');
$("#editAddress").css("background-color", "transparent");
}
becomes this:
if (editaddress == "" || editaddress == null) {
$("#editAddressError").html('<font color="#cc0000">The address is required</font>');
$("#editAddress").addClass("error");
}
else {
$("#editAddressError").html('<font color="#cc0000"></font>');
$("#editAddress").removeClass("error");
}
(Note that I'd use something similar for the field error spans, but I'll eave that up to you)
Then, you could use the presence of that class ("error") at the end of your validation to enable/disable the save button:
$("#btnSave").prop("disabled", ($(":input.error").length > 0));
Basically, if there's at least one input field with the class "error", disable the save button. Otherwise, enable it.
Hope this helps!
This is a little crazy, but in basic terms you could keep a boolean for each validation rule like so:
$("#editAccountName").blur(function () {
var editAccountName = $("#editAccountName").val();
if (editAccountName == "" || editAccountName == null) {
$("#editAccountNameError").html('<font color="#cc0000">The account name is required</font>');
$("#editAccountName").css("background-color", "#cc0000");
accountNameValid = false;
}
else {
$("#editAccountNameError").html('<font color="#cc0000"></font>');
$("#editAccountName").css("background-color", "transparent");
accountNameValid = true;
}
});
And later check if the button should be clickable:
if(accountNameValid && addressValid && ...){
// process form
}

Displaying range validator error message on html input

I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

Clearing value on input not working when two classes present

Ok im using this code to clear the inputs, it works great!! as long as the input dont have two classes...
This is working
<input class="textBox" name="textBox" value="some value" >
$(document).ready(function() {
var default_val = '';
$('input[class^="textBox"]').focus(function() {
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input[class^="textBox"]').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
});
This is not working
But if the input changes to this
<input class="text_box textBox" name="textBox" value="some value" >
This is not working even if i change my code to
$(document).ready(function() {
var default_val = '';
$('input[class^="text_box textBox"]').focus(function() {
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input[class^="text_box textBox"]').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
});
This is the input where its not working
<input class="text_box textBox" type="text" name="email" id="email" value="Su Correo electrónico" size="22">
Use a class selector:
$(document).ready(function() {
var default_val = '';
$('input.textBox').focus(function() {
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input.textBox').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
});

validation of input text field in html using javascript

<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.

Categories

Resources