Disable textboxes depending on the value of another textbox - javascript

I got three textboxes in my Form. My goal is to disable the validate and evaluate textbox if the number in digit textbox is not equal to 0. How do i accomplish this?
Pseudo code
if(digit.Text != 0 )
{
validate.enable = false;
evaluate.enable = false;
}
else
{
validate.enable = true;
evaluate.enable = true;
}
My Attempt
function disableME()
{
var numberTextBox = document.getElementById('number'),
validateTextBox = document.getElementById('validate'),
evaluateTextBox = document.getElementById('evaluate');
if (numberTextBox.value != 0)
{
validateTextBox.disable = true;
evaluateTextBox.disable = true;
}
else
{
validateTextBox.disable = false;
evaluateTextBox.disable = false;
}
}
<form action="welcome.php" method="post" id="myForm">
Number: <input type="number" id="number" onchange="disableME()"><br>
Validate: <input type="text" id="validate" onchange="disableME()"><br>
Evaluate: <input type="text" id="evaluate" onchange="disableME()"><br>
</form>

You should use ELEMENT.disabled instead of ELEMENT.disable.
Here is the change to your code:
function disableME()
{
var numberTextBox = document.getElementById('number'),
validateTextBox = document.getElementById('validate'),
evaluateTextBox = document.getElementById('evaluate');
if (numberTextBox.value != 0)
{
validateTextBox.disabled = true;
evaluateTextBox.disabled = true;
}
else
{
validateTextBox.disabled = false;
evaluateTextBox.disabled = false;
}
}
<form action="welcome.php" method="post" id="myForm">
Number: <input type="number" id="number" onchange="disableME()"><br>
Validate: <input type="text" id="validate" onchange="disableME()"><br>
Evaluate: <input type="text" id="evaluate" onchange="disableME()"><br>
</form>

Related

Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.

How to remove class error from select field while validation

Below is a sample code. Whenever i validate i don't want to highlight the select field in red. But just want to show the error beside the select field in Red.
HTML after click submit
<select name="event" class="control-label error">
<option value="">Select</option>
<option value="1">Sample 1</option>
</select>
<label for="event" generated="true" class="error" style="display: inline-block;"><span style="padding:6px; "> Please select something </span></label>
UI
jQuery Validation
$("form").validate({
onkeyup:false,
async: false,
rules: {
event: {
required: true
}
},
messages: {
event: {
required: "<span style='padding:6px; '> Please select Something </span>"
}
}
});
if you are using jquery validate library.. Doc says just add valid class on elements where you don't want the border styling.
hope this will help..
Actually required is Html 5 that should show the error in red color only
while in validation use id to call or validate then use that id in style with your need color
ex
#errorBox1,
#errorBox2,
#errorBox3,
#errorBox4,
#errorBox5,
#errorBox6,
#errorBox7,
#errorBox8,
#errorBox9,
#errorBox10
{
color:blue;
}
This is my external stylesheet
function validate()
{
var status = true;
var a = document.form.Name.value;
var b = document.form.Password.value;
var c = document.form.Cpassword.value;
var d = document.form.Address.value;
var e = document.form.Email.value;
var f = document.form.Mobile.value;
if( a == "" )
{
document.getElementById("errorBox1").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox1").innerHTML = "";
}
if( b == "" )
{
document.getElementById("errorBox2").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox2").innerHTML = "";
}
if( c == "" )
{
document.getElementById("errorBox3").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox3").innerHTML = "";
}
if (b!=c)
{
document.getElementById("errorBox10").innerHTML = "*Password does not match";
status = false;
}
else
{
document.getElementById("errorBox10").innerHTML = "";
}
if( d == "" )
{
document.getElementById("errorBox4").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox4").innerHTML = "";
}
if(e == "" || e.indexOf("#", 0) < 0 || e.indexOf(".", 0) < 0 )
{
document.getElementById("errorBox5").innerHTML = "*Please fill your valid email id ";
status = false;
}
else
{
document.getElementById("errorBox5").innerHTML = "";
}
if(f == "" || f.length !=10 || f.charAt(0)!="9" )
{
document.getElementById("errorBox6").innerHTML = "*Mobile no must be 10 digits";
status = false;
}
else
{
document.getElementById("errorBox6").innerHTML = "";
}
if ((document.form.radio1[0].checked == false) && (document.form.radio1[1].checked == false))
{
document.getElementById("errorBox7").innerHTML = "*Select your Gender";
status = false;
}
else
{
document.getElementById("errorBox7").innerHTML = "";
}
if ((document.form.chk[0].checked == false) && (document.form.chk[1].checked == false))
{
document.getElementById("errorBox8").innerHTML = "*Please fill the checkbox";
status = false;
}
else
{
document.getElementById("errorBox8").innerHTML = "";
}
if (document.form.comment.value == "")
{
document.getElementById("errorBox9").innerHTML = "*Please share your feedback";
status = false;
}
else
{
document.getElementById("errorBox9").innerHTML = "";
}
return status;
}
</script>
</head>
<body>
<div class="rm">
<form name="form" method="post" onsubmit ="return validate();" action=" ">
Name : <input type="text" name="Name" onkeyup="validate();" /><div id="errorBox1"></div>
<br>
Password : <input type="password" name="Password" onkeyup="validate();" /><div id = "errorBox2"></div>
<br>
Confirm Password : <input type="password" name="Cpassword" onkeyup="validate();" /><div id = "errorBox3"></div> <div id = "errorBox10"></div>
<br>
Address : <input type="text" name="Address" onkeyup="validate();" /><div id = "errorBox4"></div>
<br>
Email : <input type="text" name="Email" onkeyup="validate();" /><div id = "errorBox5"></div>
<br>
Mobile No :<input type="text" name="Mobile" onkeyup="validate();" /><div id = "errorBox6"></div>
<br>
Gender : Male<input name="radio1" type="radio" value="Male" onclick="validate();"/>
Female<input name="radio1" type="radio" value="Female" onclick="validate();"/><div id = "errorBox7"></div>
<br>
Computer Courses: <input type="checkbox" name="chk" onclick="validate();" value="Php"/> Php
<input type="checkbox" name="chk" onclick="validate();" value="ccna"/> Ccna <div id = "errorBox8"></div>
<br>
CommentBox : <textarea cols = "25" name= "comment" onkeyup="validate();" /></textarea><div id = "errorBox9"></div>
<br>
<div class="submit">
<input type="submit" name="submit" value="Submit" >
<input type="reset" value="Reset"></submit>
Thanks everyone for the response. I just did the following in validate part. I just added a Highlight and it worked. I seriously don't know how it worked. But thanks to Sathvik Cheela for giving an idea about highlight and unhighlight.
$("form").validate({
onkeyup:false,
async: false,
rules: {
event: {
required: true
}
},
messages: {
event: {
required: "<span style='padding:6px; '> Please select Something </span>"
}
},
highlight: function(element, errorClass) {
}
});
UI (Now)

Disable textbox when two textbox is equal

How can i disable textbox when selected (textbox name) and quantity (textbox name) is equal. i used this codes its working but when selected (textbox name) is equal to 3 the txtCombo (textbox name) is not disabled but when equal to 4 it became disabled how should i work on this ? thank you in advance.
// disable button if equal
// $('#button').click(function(){
$('#button').click(function() {
var firstValue = $("#quantitytotransfer").val();
var secondValue = $("#selected").val();
if ((firstValue == secondValue)) {
$("#txtCombo").prop("disabled", true);
}
});
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value.trim();
option.value = textb.value.trim();
option.selected = true;
if ($('#combo option[value="' + textb.value.trim() + '"]').text() == textb.value.trim()) {
alert("Duplicate found or you entered empty value");
return false;
}
try {
combo.add(option, null); //Standard
} catch (error) {
combo.add(option); // IE only
}
textb.value = "";
}
$("#txtCombo").on("keydown", function(e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$(document).ready(function() {
$('#button').click(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function() {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
var previousOption;
$('select[name=combo] option').each(function() {
if (this.text == previousOption) $(this).remove();
previousOption = this.text;
});
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BODY style="font-family: sans-serif">
<fieldset>
<legend>Combo box</legend>
Add to Combo:
<input type="text" name="txtCombo" id="txtCombo" />Selected:
<input type="text" name="selected" id="selected" />IMEI Selected:
<input type="text" name="imei" id="imei" />Quantity:
<input type="text" name="quantity" value="3" id="quantitytotransfer" />
<br>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>Combobox:
<select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
You can achieve this easily :
function checkIfEqual(){
if($("#selected").val() === $("#quantitytotransfer").val())
$("#txtCombo").prop("disabled", true);
else
$("#txtCombo").prop("disabled", false);
}
$("#button").click(function(){
$("#selected").val($("#combo option:selected").length);
checkIfEqual();
});
demo here
Have you tried this:
function addCombo() {
var txtSelected = $('#selected').val();
var qty = $('#quantitytotransfer').val();
if(parseInt(txtSelected) == parseInt(qty)) {
alert('Equal');
document.getElementById('txtCombo').disabled = true;
} else {
alert('Not equal');
document.getElementById('txtCombo').disabled = false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BODY style="font-family: sans-serif">
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/><br>
Selected: <input type="text" name="selected" id="selected" class="toggle"/><br>
IMEI Selected: <input type="text" name="imei" id="imei"/><br>
Quantity: <input type="text" name="quantity" value="3" id="quantitytotransfer" class="toggle"/><br>
<input type="button" id="button" value="Add" onclick="addCombo()"><br>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>

Check,reset buttons active after all inputs were completed

how can i make check and reset buttons active after 6 inputs were completed? I have tryed:
if($('.input') == ""){
checkBtn.disabled = true;
resetBtn.disabled = true;
}
else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
EDIT 2 with fiddle : http://jsfiddle.net/usPMd/88/
Edit : Your Jsfiddle return error 404... So I developed a basic example (it is not perfect).
Jsfiddle
Javascript solution :
<body>
<form>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input id="send" type="submit" disabled/>
<input id="reset" type="reset" disabled/>
</form>
<script type="text/javascript">
var checkBtn = document.getElementById("send");
var resetBtn = document.getElementById("reset");
var inputTag, lengthInputTag, nbCompleted;
function forEach( a, fn ) {
return [].forEach.call(a, fn);
};
function checkInput(){
inputTag = document.getElementsByTagName("input");
lengthInputTag = inputTag.length;
nbCompleted = 0;
console.log(inputTag);
forEach(inputTag, function(el) {
if(el.value != ""){
nbCompleted++;
}
});
if(nbCompleted < 6){
checkBtn.disabled = true;
resetBtn.disabled = true;
}else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
};
</script>
</body>
if($('.input').length == 6){
checkBtn.disabled = false;
resetBtn.disabled = false;
}else{
checkBtn.disabled = true;
resetBtn.disabled = true;
}
So, use length then:
if($('.input').length == 7){ //after 6 is 7th input
checkBtn.disabled = true;
resetBtn.disabled = true;
}
And also there might be a typo .input should be input but not 100% sure because this might also be class.
Ok, Here you go:
Workign demo: JSFiddle
HTML (partial):
<button id="validateButton" class="validateButton" type="button" disabled="disabled">Check</button>
<button id="resetButton" class="resetButton" type="button" disabled="disabled">Reset</button>
JS:
$(document).on('change blur', '.input', function(){
var count = 0;
$('.input').each(function(){
var elem_v = $.trim ( $(this).val() );
if (elem_v != "") {
count++;
}
})
$('button').prop('disabled', true);
if (count===6){
$('button').prop('disabled', false);
}
});

placeholder works for text but not password box in IE/Firefox using this javascript

Js File
//Modified from http://www.beyondstandards.com/archives/input-placeholders/
function activatePlaceholders()
{
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++)
{
if (inputs[i].getAttribute("type") == "text")
{
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0)
{
inputs[i].value = placeholder;
inputs[i].onclick = function()
{
if (this.value == this.getAttribute("placeholder"))
{
this.value = "";
}
return false;
}
inputs[i].onblur = function()
{
if (this.value.length < 1)
{
this.value = this.getAttribute("placeholder");
}
}
}
}
else if (inputs[i].getAttribute("type") == "password")
{
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0)
{
inputs[i].value = placeholder;
inputs[i].onclick = function()
{
if (this.value == this.getAttribute("placeholder"))
{
this.value = "";
}
return false;
}
inputs[i].onblur = function()
{
if (this.value.length < 1)
{
this.value = this.getAttribute("placeholder");
}
}
}
}
}
}
window.onload = function()
{
activatePlaceholders();
}
Html part
<form name="input" action="login.php" method="post">
<table width="*" border="0">
<tr>
<td align="left"><input type="text" name="username" placeholder="Username" /> <input type="password" name="pass" placeholder="Password" /><input type="submit" value="Login" /></td>
</tr>
<tr>
<td colspan="2" align="right">Stay logged in: <input type="checkbox" name="remember" value="1"> Sign Up | Forgot Password </td>
</tr>
</table>
</form>
This works for the input box. Not working for the password box. It wants to star out the place holder text on the password. I want to users password to be started out but not the place holder. Not sure how to fix that so it works in IE and Firefox.
var passwords = document.getElementsByTagName("password");
Should be:
var passwords = document.getElementsByTagName("input");
As it's <input type="password"> not <password...>. However, I don't think that will help you in this case, because when you set the value of the password, all you'll see are the black dots/asterisks.

Categories

Resources