jQuery Dynamic form input validation - javascript

This question is based off of another StackOverflow question found here.
My goal is to build simple validation that ensures input fields are filled in sequential order based on their index (natural flow).
» The main complexity is that I'm trying to consolidate validation across different types of input.
» Specifically, radio button groups should be validated as one entity. When using the .prev() and .next() methods, the gender radio group should move to essay or age respectively, not male or female.
» The next bug is that I cannot get the age row to properly disable if the content in any previous row is undone/removed. It does not work consistently and I cannot figure out why.
» The validate button should make items that are filled in green, otherwise highlight them in red color.
If there is a more refined approach to this please feel free to elaborate. If there are easier selectors that I could be utilizes to build up the arrays for more streamlined manipulation and validation, please also enlighten me and share.
Almost Working Example
//StackOverflow Question - https://stackoverflow.com/q/37618826/5076162 [06-03-2016]
//Step 1: Declare the collection of all inputs that should be manipulated.
var $inputFields = $('textarea, input[type="text"], input[type="number"], input[type="radio"]');
//Step 2: Insert the collection into a single array using the .push() method.
var arr = [];
$inputFields.each(function() {
arr.push($(this));
});
//Step 3: Iterate through the newly created array and perform certain functions.
//Source - https://stackoverflow.com/a/5437904/5076162
$.each(arr, function(i) {
if (i > 0) {
$(this).attr('readonly', 'readonly').addClass('disabled');
$(':radio[readonly]:not(:checked)').attr('disabled', true);
//console.log("Iteration number: " + i);
}
});
var $justRadio = $('input[type="radio"]:disabled');
//Step 4: Detect input and apply logic for each situation. Note that different input types require different syntax.
$inputFields.on("propertychange input change focus blur", function(i) {
var index = $inputFields.index(this);
var next = $inputFields.eq(index + 1);
var $checkedRadio = $('input[type="radio"]:checked').length;
var radioCounter = $justRadio.length;
if ($(this).val() === "") {
$inputFields.filter(function() {
return $inputFields.index(this) > index;
}).attr("readonly", true).attr('disabled', true).addClass('disabled');
//console.log('disable Fired');
} else {
next.attr("readonly", false).attr('disabled', false).removeClass('disabled');
$justRadio = $('input[type="radio"]:disabled');
//console.log(radioCounter);
if (radioCounter < 2) {
$justRadio.closest('tr').find($justRadio).attr("readonly", false).attr('disabled', false).removeClass('disabled');
}
}
if ($checkedRadio > 0 && $justRadio.length === 0) {
$inputFields.last().attr("readonly", false).attr('disabled', false).removeClass('disabled');
//console.log("This fired: lastRow");
}
//Step 5: Implement a user interface button so they know they have filled in all fields.
var emptyCount = 0;
$inputFields.not($('input[type="radio"]')).each(function() {
if ($(this).val() === "") {
emptyCount = +1;
}
//console.log("Empty Count: " + emptyCount);
});
var vRCount = 0;
$inputFields.not($('input[type="text"], input[type="number"], textarea')).each(function() {
if ($(this).is(":checked")) {
vRCount = +1;
}
//console.log("Empty Count: " + emptyCount);
});
$('input.validateCheck').on("click", function() {
if (emptyCount === 0 && vRCount > 0) {
$inputFields.closest('tr').find('td').css("color", "green");
$('input.validateCheck').text("Success!").attr("value", "Success!");
}
});
});
table {
border-collapse: collapse;
}
td {
vertical-align: top;
border: solid 1px #ACE;
padding: 2px;
font-family: arial;
}
input {
width: 450px;
text-align: center;
}
textarea {
margin: 0;
width: 448px;
text-align: left;
}
input[type="radio"] {
width: 15px;
}
div.gender {
display: inline-block;
clear: none;
width: 219px;
}
.disabled {
background-color: #f1f1f1;
}
input[type="button"] {
width: 546px;
margin-top: 5px;
color: #FFF;
background-color: red;
border: solid 1px #ACE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form>
<table>
<tr>
<td>First name:</td>
<td>
<input type="text" name="firstname">
</td>
</tr>
<tr>
<td>Last name:</td>
<td>
<input type="text" name="lastname">
</td>
</tr>
<tr>
<td>Essay:</td>
<td>
<textarea rows="4" cols=""></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<div class='gender'>
<input type="radio" name="gender" value="male">Male</div>
<div class='gender'>
<input type="radio" name="gender" value="female">Female</div>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" name="age" min="18" max="99">
</td>
</tr>
</table>
<input class='validateCheck' type="button" value="Validate" />
</form>

Use HTML5 form validations. It is a lot easier and faster. Hope this helps...
<style>
form{font-size:100%;min-width:560px;max-width:620px;width:590px;margin:0 auto;padding:0}
form fieldset{clear:both;font-size:100%;border-color:#000;border-style:solid none none;border-width:1px 0 0;margin:0;padding:10px}
form fieldset legend{font-size:150%;font-weight:400;color:#000;margin:0;padding:0 5px}
label{font-size:100%}
label u{font-style:normal;text-decoration:underline}
input,select,textarea{font-family:Tahoma, Arial, sans-serif;font-size:100%;color:#000}
input:required ,select:required, textarea:required, radio:required{
font-family:Tahoma, Arial, sans-serif;
font-size:100%;
color:#000;
border-color:red;
background: #fff url(images/red-asterisk.png) no-repeat 98% center;
}
input:focus ,select:focus, textarea:focus, radio:focus{
background: #fff url(invalid.png) no-repeat 98% center;
box-shadow: 0 0 5px #d45252;
border-color: #b03535
}
input:valid ,select:valid, textarea:valid, radio:valid{
background: #fff url(valid.png) no-repeat 98% center;
box-shadow: 0 0 5px #5cd053;
border-color: #28921f;
}
:valid {box-shadow: 0 0 5px green}
:-moz-submit-invalid {box-shadow: 0 0 5px pink}
</style>
<form>
<table>
<tr>
<td>First name:</td>
<td>
<input type="text" id="firstname" name="firstname" required>
</td>
</tr>
<tr>
<td>Last name:</td>
<td>
<input type="text" name="lastname" required>
</td>
</tr>
<tr>
<td>Essay:</td>
<td>
<textarea rows="4" cols="20" required></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<div class='gender'>
<input type="radio" name="gender" value="male" required> Male</div>
<div class='gender'>
<input type="radio" name="gender" value="female" required> Female</div>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" name="age" min="18" max="99" required>
</td>
</tr>
</table>
<input class='validateCheck' type="submit" value="Validate" />
</form>

Related

How to unhide a div based on two Boolean function outputs

I am trying to use an input box to check if the input begins with a letter A-M, and secondly if the number of characters is odd or even, then unhide a div if these conditions are met. I am getting one error:
Uncaught TypeError: Cannot read property 'value' of null
at org.html:89
Code below.
Thanks.
I am trying to change the display style with my if statement at the end of the functions.
However, because of the null type error nothing happens.
If I can get the first one to work, I intend to duplicate the method for the other tables.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITP-03</title>
<meta name="description" content="A calculator">
<style>
.title{
border: 10px;
margin-bottom: 10px;
text-align:center;
width: 210px;
color:black;
border: solid black 1px;
font-family: sans-serif;
}
input[type="button"]
{
border: 10px;
background-color:#46eb34;
color: black;
border-color:#46eb34 ;
width:100%;
}
input[type="text"]
{
border: 10px;
text-align: right;
background-color:white;
border-color: black ;
width:100%
}
input[type="username"]
{
border: 10px;
margin-bottom: 10px;
text-align: left;
color: black;
border: solid #46eb34 1px;
background-color:white;
border-color: black ;
width:20%
}
</style>
<script>
//function for displaying values
function dis(val)
{
document.getElementById("calc").value+=val;
}
//function for evaluation
function solve()
{
let x = document.getElementById("calc").value;
let y = eval(x);
document.getElementById("calc").value = y;
}
//function for clearing the display
function clr()
{
document.getElementById("calc").value = "";
}
function isEven()
{
var value = document.getElementById("username").value.length;
if (value%2 == 0) {
document.getElementById("check2").innerHTML = "even";
return true;
}
if (value%2 !=0) {
document.getElementById("check2").innerHTML = "odd";
return false;
}
}
function beforeN(value) {
var firstletter = document.getElementById("username").value.substring(0,1);
var str = "abcdefghijklm.";
if (str.includes(firstletter)){
document.getElementById("check1").innerHTML = "a-m";
return true;
}
else {
document.getElementById("check1").innerHTML = "n-z";
return false;
}
}
if(beforeN(document.getElementById("username").value) && (isEven(document.getElementById("username").value))){
document.getElementById("amodd").style.display= "block";
}
</script>
</head>
<body>
<p id="check1">a</p>
<p id="check2">a</p>
<p class = title>Enter your iu username</p>
<input type="username" id="username" name="iu username"/>
<br>
<button onclick=beforeN(document.getElementById("username").value) type ="button">Submit</button>
<div id ="amodd" style=display:none>
<div class = title >ITP-03 Calculator A-M ODD</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()"/> </td>
<td colspan="3"><input type="text" id="calc"/></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="dis('+')"/> </td>
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/)"/> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')"/> </td>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
<td><input type="button" value="=" onclick="solve()"/> </td>
</tr>
</table>
</div>
</body>
Few things to note here.
You are missing the quotes for the onclick attribute value. Others have already pointed that out.
The error that you were seeing is because your if condition resides outside a function. So, it will be executed on page load in the order in which you have written it. If you have it before the body, it will be executed before the DOM loads. In such cases, you should put it within the body at the end.
Also, the if condition will only be executed when your page loads. Since your button has an onclick attribute, it will execute only that function that you invoke. That will not help you update the page(hide and unhide divs) every time the button is clicked. I would suggest you put the if-condition within a function and invoke the function on the button click.
Also note that I have changed your if condition to remove all the parameters you were passing, since you were not using it. You were fetching the values again in your function.
Also, since you want both beforeN and isEven functions to be executed every time the button is clicked, I have changed it to execute the functions and store the result in a variable. Otherwise, it will only execute the isEven method if beforeN evaluates to true. Also included an else condition to hide the div when the conditions are not met.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITP-03</title>
<meta name="description" content="A calculator">
<style>
.title {
border: 10px;
margin-bottom: 10px;
text-align: center;
width: 210px;
color: black;
border: solid black 1px;
font-family: sans-serif;
}
input[type="button"] {
border: 10px;
background-color: #46eb34;
color: black;
border-color: #46eb34;
width: 100%;
}
input[type="text"] {
border: 10px;
text-align: right;
background-color: white;
border-color: black;
width: 100%
}
input[type="username"] {
border: 10px;
margin-bottom: 10px;
text-align: left;
color: black;
border: solid #46eb34 1px;
background-color: white;
border-color: black;
width: 20%
}
</style>
</head>
<body>
<p id="check1">a</p>
<p id="check2">a</p>
<p class=title>Enter your iu username</p>
<input type="username" id="username" name="iu username" />
<br>
<button onclick="exFun()" type="button">Submit</button>
<div id="amodd" style=display:none>
<div class=title>ITP-03 Calculator A-M ODD</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()" /> </td>
<td colspan="3"><input type="text" id="calc" /></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="dis('+')" /> </td>
<td><input type="button" value="1" onclick="dis('1')" /> </td>
<td><input type="button" value="3" onclick="dis('3')" /> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/)" /> </td>
<td><input type="button" value="5" onclick="dis('5')" /> </td>
<td><input type="button" value="7" onclick="dis('7')" /> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')" /> </td>
<td><input type="button" value="9" onclick="dis('9')" /> </td>
<td><input type="button" value="=" onclick="solve()" /> </td>
</tr>
</table>
</div>
<script>
//function for displaying values
function dis(val) {
document.getElementById("calc").value += val;
}
//function for evaluation
function solve() {
let x = document.getElementById("calc").value;
let y = eval(x);
document.getElementById("calc").value = y;
}
//function for clearing the display
function clr() {
document.getElementById("calc").value = "";
}
function isEven() {
var value = document.getElementById("username").value.length;
if (value % 2 == 0) {
document.getElementById("check2").innerHTML = "even";
return true;
}
if (value % 2 != 0) {
document.getElementById("check2").innerHTML = "odd";
return false;
}
}
function beforeN(value) {
var firstletter = document.getElementById("username").value.substring(0, 1);
var str = "abcdefghijklm.";
if (str.includes(firstletter)) {
document.getElementById("check1").innerHTML = "a-m";
return true;
}
else {
document.getElementById("check1").innerHTML = "n-z";
return false;
}
}
function exFun() {
var beforeNResult = beforeN();
var isEvenResult = isEven();
if (beforeNResult && isEvenResult) {
document.getElementById("amodd").style.display = "block";
}else{
document.getElementById("amodd").style.display = "none";
}
}
</script>
</body>
you should put script after element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITP-03</title>
<meta name="description" content="A calculator">
<style>
.title{
border: 10px;
margin-bottom: 10px;
text-align:center;
width: 210px;
color:black;
border: solid black 1px;
font-family: sans-serif;
}
input[type="button"]
{
border: 10px;
background-color:#46eb34;
color: black;
border-color:#46eb34 ;
width:100%;
}
input[type="text"]
{
border: 10px;
text-align: right;
background-color:white;
border-color: black ;
width:100%
}
input[type="username"]
{
border: 10px;
margin-bottom: 10px;
text-align: left;
color: black;
border: solid #46eb34 1px;
background-color:white;
border-color: black ;
width:20%
}
</style>
</head>
<body>
<p id="check1">a</p>
<p id="check2">a</p>
<p class = title>Enter your iu username</p>
<input type="username" id="username" name="iu username"/>
<br>
<button onclick='beforeN(document.getElementById("username").value)' type ="button">Submit</button>
<div id ="amodd" style=display:none>
<div class = title >ITP-03 Calculator A-M ODD</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()"/> </td>
<td colspan="3"><input type="text" id="calc"/></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="dis('+')"/> </td>
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/')"> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')"/> </td>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
<td><input type="button" value="=" onclick="solve()"/> </td>
</tr>
</table>
</div>
<script>
//function for displaying values
function dis(val)
{
document.getElementById("calc").value+=val;
}
//function for evaluation
function solve()
{
let x = document.getElementById("calc").value;
let y = eval(x);
document.getElementById("calc").value = y;
}
//function for clearing the display
function clr()
{
document.getElementById("calc").value = "";
}
function isEven()
{
var value = document.getElementById("username").value.length;
if (value%2 == 0) {
document.getElementById("check2").innerHTML = "even";
return true;
}
if (value%2 !=0) {
document.getElementById("check2").innerHTML = "odd";
return false;
}
}
function beforeN(value) {
var firstletter = document.getElementById("username").value.substring(0,1);
var str = "abcdefghijklm.";
if (str.includes(firstletter)){
document.getElementById("check1").innerHTML = "a-m";
return true;
}
else {
document.getElementById("check1").innerHTML = "n-z";
return false;
}
}
if(beforeN(document.getElementById("username").value) && (isEven(document.getElementById("username").value))){
document.getElementById("amodd").style.display= "block";
}
</script>
</body>
and in this line
<button onclick='beforeN(document.getElementById("username").value)' type ="button">Submit</button>
you missed '

Complete form based on drop down selection

I have a simple form that requires employees to input phone numbers, employee ID, etc. I would like to save them some time (and prevent data entry errors) by allowing them to select their name form a drop down and have the text input fields for phone and ID number autofill based on the name selected.
I have an HTML table that contains all the employee information, but do not know how to pass that information to the proper fields. Code snippet follows:
#emp_data_tbl {
width: 90%
}
#emp_data_tbl td,
#emp_data_tbl th {
border: 1px solid #ddd;
padding: 8px;
}
#emp_data_tbl tr:nth-child(even) {
background-color: #f2f2f2;
}
#emp_data_tbl tr:hover {
background-color: #ddd;
}
#emp_data_tbl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<p>Name</p>
<select required>
<option value="" disabled selected hidden>Choose Name...
</option>
<option value="Adam Jackson">Adam Jackson
</option>
<option value="Bill Smith">Bill Smith
</option>
<option value="Chris Clinton">Chris Clinton
</option>
<option value="David Billings">David Billings
</option>
<option value="Eamon Lampsen">Eamon Lampsen
</option>
</select>
<p>Phone</p>
<input type="text" id="phone">
<p>ID</p>
<input type="text" id="IdNum">
<br><br>
<hr><br><br>
<table id="emp_data_tbl">
<caption>In reality, this data table is hidden with CSS display: none but viewable here in this mock up</caption>
<col>
<col>
<col>
<tr>
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tr>
<td>Adam Jackson</td>
<td>111-111-1111</td>
<td>#1111</td>
</tr>
<tr>
<td>Bill Smith</td>
<td>222-222-2222</td>
<td>#2222</td>
</tr>
<tr>
<td>Chris Clinton</td>
<td>333-333-3333</td>
<td>#3333</td>
</tr>
<tr>
<td>David Billings</td>
<td>444-444-4444</td>
<td>#4444</td>
</tr>
<tr>
<td>Eamon Lampsen</td>
<td>555-555-5555</td>
<td>#5555</td>
</tr>
</table>
This will get you started.
#emp_data_tbl {
width: 90%
}
#emp_data_tbl td,
#emp_data_tbl th {
border: 1px solid #ddd;
padding: 8px;
}
#emp_data_tbl tr:nth-child(even) {
background-color: #f2f2f2;
}
#emp_data_tbl tr:hover {
background-color: #ddd;
}
#emp_data_tbl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<form action="#">
<label for="name">Name</label><br>
<select id="name" name="name"></select><br><br>
<!--<label for="female">Phone</label><br>
<input type="text" name="phone" id="phone"><br><br>
<label for="id">ID</label><br>
<input type="text" name="id" id="id"><br><br>-->
<input type="submit" value="Submit">
</form>
<br><br>
<hr><br><br>
<table id="emp_data_tbl">
<tr>
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tr>
<td>Adam Jackson</td>
<td>111-111-1111</td>
<td>#1111</td>
</tr>
<tr>
<td>Bill Smith</td>
<td>222-222-2222</td>
<td>#2222</td>
</tr>
<tr>
<td>Chris Clinton</td>
<td>333-333-3333</td>
<td>#3333</td>
</tr>
<tr>
<td>David Billings</td>
<td>444-444-4444</td>
<td>#4444</td>
</tr>
<tr>
<td>Eamon Lampsen</td>
<td>555-555-5555</td>
<td>#5555</td>
</tr>
</table>
<script>
var rows = document.getElementById("emp_data_tbl").rows;
var users = [];
var phonenrs = [];
var ids = [];
//start at i = 1 to skip the header row
for(var i = 1; i < rows.length; i++)
{
users.push(rows[i].cells[0].innerHTML);
phonenrs.push(rows[i].cells[1].innerHTML);
ids.push(rows[i].cells[2].innerHTML);
}
var nameList = document.getElementById("name");
for(var i = 0; i < users.length; i++)
{
nameList.add(new Option(users[i], users[i] + " - " + phonenrs[i] + " - " + ids[i]));
}
</script>
After this, you will need to do something when your user chooses his name.
You can do this by adding an onChange to the selectbox, which holds a function that will be executed the moment the user chooses an option of the selectbox. For example:
<select id="name" name="name" onchange="fillData();"></select>
After this, you can create a Javascript function fillData(), that get's the telephone number and id, belonging to the user and fill in the values with javascript. Something like:
function fillData(){
document.getElementById("phone").value = "";
//get and set your id and phone values here
}

How to do validation and display message before form submit?

I have multiple rows of HTML input elements with type number. Each row has four input fields and I want to add validation so that any input field should not allow a value lesser than the field on it's left side (in the same row).
I want to add this same validation for every row.
I want to do this validation before form submission and display error message. (before form submission/submit button is clicked)
The leftmost row should not allow a value less than zero (as it doesn't have any input field on it's left).
Can you please suggest me how I can do this using the sample jsfiddle: Error message when text field has a value out of range
(I tried to do this using "min" option in "input" tag but works only after submit button is clicked.)
Same code as in fiddle:
<html>
<head>
<title>TestPage</title>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
addPlusSign();
$(".btn1").click(function(){
$(".expand1").toggle();
var btn1Text = $(".btn1").text();
if(btn1Text.indexOf("+") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '-');
$(".btn1").text(temp);
} else if (btn1Text.indexOf("-") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '+');
$(".btn1").text(temp);
}
});
})
function addPlusSign(){
if($(".expand1")){
var btn1Text = $(".btn1").text();
$(".btn1").text(btn1Text + " [+]");
}
}
$(function () {
$('.admin-form')
//we need to save values from all inputs with class 'admin-input'
.find(':input.admin-input')
.each(function () {
//save old value in each input's data cache
$(this).data('oldValue', $(this).val())
})
.end()
.submit(function (ev) {
var changed = false;
$(':input.admin-input', this).filter(function () {
if($(this).val() != $(this).data('oldValue')){
changed = true;
}
});
if($(this).hasClass('changed') && (!changed)){
alert("None of the thresholds were changed!");
ev.preventDefault()
}
if($(this).hasClass('changed') && changed){
var allowSubmit = window.confirm("You have set a unique threshold for one or more sub-elements below. Are you sure you want to reset them all?")
if (!allowSubmit)
ev.preventDefault()
}
});
});
$(document).on('input', '.admin-input', function(){
$(this).closest('form').addClass('changed');
});
</script>
<style>
.expand1 { display: none;
}
.btn1 { cursor: pointer;
}
body {
background-color: rgb(255,255,255);
font: 15px Verdana, Helvetica, sans-serif;
}
table#t02, #t02 th, #t02 td {
border: none;
border-collapse: collapse;
font-size:95%;
font-weight:normal;
}
#button1{
position: relative;
top:50px;
left:35%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
#button2{
position: relative;
top:50px;
left:50%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
input[type=number] {
max-width: 50px;
}
html {
overflow-y: scroll;
}
</style>
</head>
<body>
<form id="form1" method="post" class="admin-form">
<div style="float:left; width:50%">
<br />
<br />
<table id="t02" class="table2">
<tr>
<th style="padding:0 30px 0 0;"></th>
<th></th>
<th style="padding:0 10px 0 0;">Green</th>
<th colspan="3" style="padding:0 10px 0 0">Yellow</th>
<th></th>
<th style="padding:0 10px 0 0">Red</th>
</tr>
<tr>
<td class="btn1" style="padding:0 30px 0 0;"><b>Row1 (%)</b></td>
<td>&lt</td>
<td style="padding:0 10px 0 0"><input type="number", class="admin-input", name="row1_good_high", value="5", size="3", maxlength="3"></td>
<td><input type="number", class="admin-input", name="row1_warning_low", value="5", size="3", maxlength="3"></td>
<td>-</td>
<td style="padding:0 10px 0 0"><input type="number", class="admin-input", name="row1_warning_high", value="15", size="3", maxlength="3"></td>
<td>&gt</td>
<td style="padding:0 10px 0 0"><input type="number", class="admin-input", name="row1_critical_low", value="15", size="3", maxlength="3"></td>
</tr>
<tr>
<td align="center" class="expand1">Sub Row</td>
<td class="expand1">&lt</td>
<td class="expand1"><input type="number", name="row1_good_high_Sub Row", value="5", size="3", maxlength="3"></td>
<td class="expand1"><input type="number", name="row1_warning_low_Sub Row", value="5", size="3", maxlength="3"></td>
<td class="expand1">-</td>
<td class="expand1"><input type="number", name="row1_warning_high_Sub Row", value="15", size="3", maxlength="3"></td>
<td class="expand1">&gt</td>
<td class="expand1"><input type="number", name="row1_critical_low_Sub Row", value="15", size="3", maxlength="3"></td>
</tr>
</table>
</div>
<div style="clear:both">
<input type="submit" onclick="return confirm('Are you sure you want to submit the change?')" name="submitButton" value="Submit" id="button1" style="height:50px; width:100px"/>
<input title="Set thresholds to baseline thresholds" type="submit" onclick="return confirm('Are you sure you want to set all thresholds to the baseline thresholds?')" name="resetButton" value="Reset" id="button2" style="height:50px; width:100px"/>
</div>
</form>
</body>
</html>
goog validation jquery plugin: http://jqueryvalidation.org/
you can define dependency like this:
$(".selector").validate({
rules: {
contact: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email").is(":checked");
}
}
}
}
});
Thank you for your replies, Yaco Zaragoza and miralong.
Finally I was able to come up with following which does what I wanted:
<html>
<head>
<title>TestPage</title>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
addPlusSign();
$(".btn1").click(function(){
$(".expand1").toggle();
var btn1Text = $(".btn1").text();
if(btn1Text.indexOf("+") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '-');
$(".btn1").text(temp);
} else if (btn1Text.indexOf("-") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '+');
$(".btn1").text(temp);
}
});
$('[id^="number"]').focusout(function() {
var current_field_name = this.id;
if (current_field_name.indexOf("_1") > -1) {
var good_high = Number(document.getElementById(current_field_name).value);
if (good_high < 0) {
alert(good_high + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
} else if (current_field_name.indexOf("_2") > -1) {
var warning_low = Number(document.getElementById(current_field_name).value);
var previous_field_name_1 = current_field_name.replace(/2$/, "1");
var good_high = Number(document.getElementById(previous_field_name_1).value);
if (warning_low < good_high) {
alert(warning_low + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
} else if (current_field_name.indexOf("_3") > -1) {
var warning_high = Number(document.getElementById(current_field_name).value);
var previous_field_name_1 = current_field_name.replace(/3$/, "1");
var good_high = Number(document.getElementById(previous_field_name_1).value);
var previous_field_name_2 = current_field_name.replace(/3$/, "2");
var warning_low = Number(document.getElementById(previous_field_name_2).value);
if (warning_high < warning_low) {
alert(warning_high + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
} else if (current_field_name.indexOf("_4") > -1) {
var critical_low = Number(document.getElementById(current_field_name).value);
var previous_field_name_1 = current_field_name.replace(/4$/, "1");
var good_high = Number(document.getElementById(previous_field_name_1).value);
var previous_field_name_2 = current_field_name.replace(/4$/, "2");
var warning_low = Number(document.getElementById(previous_field_name_2).value);
var previous_field_name_3 = current_field_name.replace(/4$/, "3");
var warning_high = Number(document.getElementById(previous_field_name_3).value);
if (critical_low < warning_high) {
alert(critical_low + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
}
});
})
function addPlusSign(){
if($(".expand1")){
var btn1Text = $(".btn1").text();
$(".btn1").text(btn1Text + " [+]");
}
}
$(function () {
$('.admin-form')
//we need to save values from all inputs with class 'admin-input'
.find(':input.admin-input')
.each(function () {
//save old value in each input's data cache
$(this).data('oldValue', $(this).val())
})
.end()
.submit(function (ev) {
var changed = false;
$(':input.admin-input', this).filter(function () {
if($(this).val() != $(this).data('oldValue')){
changed = true;
}
});
if($(this).hasClass('changed') && (!changed)){
alert("None of the thresholds were changed!");
ev.preventDefault()
}
if($(this).hasClass('changed') && changed){
var allowSubmit = window.confirm("You have set a unique threshold for one or more sub-elements below. Are you sure you want to reset them all?")
if (!allowSubmit)
ev.preventDefault()
}
});
});
$(document).on('input', '.admin-input', function(){
$(this).closest('form').addClass('changed');
});
</script>
<style>
.expand1 { display: none;
}
.btn1 { cursor: pointer;
}
body {
background-color: rgb(255,255,255);
font: 15px Verdana, Helvetica, sans-serif;
}
table#t02, #t02 th, #t02 td {
border: none;
border-collapse: collapse;
font-size:95%;
font-weight:normal;
}
#button1{
position: relative;
top:50px;
left:35%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
#button2{
position: relative;
top:50px;
left:50%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
input[type=number] {
max-width: 50px;
}
html {
overflow-y: scroll;
}
</style>
</head>
<body>
<form id="form1" method="post" class="admin-form">
<div style="float:left; width:50%">
<br />
<br />
<table id="t02" class="table2">
<tr>
<th style="padding:0 30px 0 0;"></th>
<th></th>
<th style="padding:0 10px 0 0;">Green</th>
<th colspan="3" style="padding:0 10px 0 0">Yellow</th>
<th></th>
<th style="padding:0 10px 0 0">Red</th>
</tr>
<tr>
<td style="padding:0 30px 0 0;">Row1</td>
<td>&lt</td>
<td style="padding:0 10px 0 0"><input type="number", name="row1_good_high", value="30", size="3", maxlength="3", id="number42_1"></td>
<td><input type="number", name="row1_warning_low", value="30", size="3", maxlength="3", id="number42_2"></td>
<td>-</td>
<td style="padding:0 10px 0 0"><input type="number", name="row1_warning_high", value="60", size="3", maxlength="3", id="number42_3"></td>
<td>&gt</td>
<td style="padding:0 10px 0 0"><input type="number", name="row1_critical_low", value="60", size="3", maxlength="3", id="number42_4"></td>
</tr>
<tr>
<td style="padding:0 30px 0 0;">SubRow</td>
<td>&lt</td>
<td style="padding:0 10px 0 0"><input type="number", name="subrow_good_high", value="30", size="3", maxlength="3", id="number12_1"></td>
<td><input type="number", name="subrow_warning_low", value="30", size="3", maxlength="3", id="number12_2"></td>
<td>-</td>
<td style="padding:0 10px 0 0"><input type="number", name="subrow_warning_high", value="60", size="3", maxlength="3", id="number12_3"></td>
<td>&gt</td>
<td style="padding:0 10px 0 0"><input type="number", name="subrow_critical_low", value="60", size="3", maxlength="3", id="number12_4"></td>
</tr>
</table>
</div>
<div style="clear:both">
<input type="submit" onclick="return confirm('Are you sure you want to submit the change?')" name="submitButton" value="Submit" id="button1" style="height:50px; width:100px"/>
<input title="Set thresholds to baseline thresholds" type="submit" onclick="return confirm('Are you sure you want to set all thresholds to the baseline thresholds?')" name="resetButton" value="Reset" id="button2" style="height:50px; width:100px"/>
</div>
</form>
</body>
</html>

Hide input box once click to other element or mouseup but retain once focus

How to hide input box once mouseup or click to other element and retain once focus? My current code is below, the mouseup is working but the thing is once focus on showed input boxes, they're being hidden immediately. See the demonstration below and click edit button. Input boxes will show, but will disappear once they are focused.
$(".edit").click(function () {
var $span = $(this);
$(this).closest('tr').find('.textdisplay').hide();
$(this).closest('tr').find('.editbox').css("display", "inline");
var ID = $(this).attr('id');
var RemoveIDedit = ID.replace('edit_', '');
$(this).hide();
$("#save_" + RemoveIDedit).css("display", "inline");
});
$(".save").click(function () {
var $span = $(this);
$(this).closest('tr').find('.textdisplay').css("display", "inline");
$(this).closest('tr').find('.editbox').hide();
var ID = $(this).attr("id");
var RemoveIDsave = ID.replace('save_', '');
$(this).hide()
$("#edit_" + RemoveIDsave).css("display", "inline");
});
$(document).mouseup(function () {
$(".editbox").hide();
$(".textdisplay").show();
$(".edit").css("display", "inline");
$(".save").css("display", "none")
});
.save {
display: none;
}
table {
width: 400px;
}
}
table td {
border: 1px solid;
}
.trash {
font-size: 14px;
padding-left: 5px;
}
.save, .edit {
padding-left: 5px;
position: absolute;
font-size: 14px;
}
.editbox {
font-size:14px;
display: none;
}
.textdisplay {
font-size: 14px;
float: left;
font-weight: normal;
word-wrap:break-word;
white-space: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
<tr>
<td> <span class="textdisplay"> Data 1A </span>
<input type="text" class="editbox" value="Data 1A" />
</td>
<td> <span class="textdisplay"> Data 1B </span>
<input type="text" class="editbox" value="Data 1B" />
</td>
<td>
Delete
Edit
Save
</td>
</tr>
<tr>
<td>
<span class="textdisplay"> Data 2A </span>
<input type="text" class="editbox" value="Data 2A" />
</td>
<td>
<span class="textdisplay"> Data 2B </span>
<input type="text" class="editbox" value="Data 2b" />
</td>
<td>
Delete
Edit
Save
</td>
</tr>
</table>
JS Fiddle
so just change your mouseup to following code:
$(document).mouseup(function(e){
if ($(e.target).hasClass('editbox')) return false;
$(".editbox").hide();
$(".textdisplay").show();
$(".edit").css("display","inline");
$(".save").css("display","none")
});
as in this fiddle:
https://jsfiddle.net/L6v2880z/7/
EDIT: Sorry $(this) was the wrong context i used before...

Javascript Onload expected object error

I'm getting "scrollingMsg" is undefined. It's not the cause though; it was functioning before I started doing the validSalesAmt() function. Beside that, not sure if this will help find the bug, but clicking the fields in the form gave an error saying that function wasn't defined. Please, no recommendations 'you can do it this way instead' because this is an assignment for school that has to be done as is in the textbook.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter 10 Shoreline State Bank</title>
<script type="text/javascript">
var adMsg = " **Did you know some used cars can have 100% loan value? Ask for details! **"
var beginPos = 0
function scrollingMsg()
{
msgForm.scrollingMsg.value=adMsg.substring(beginPos,adMsg.length)+adMsg.substring(0,beginPos)
beginPos=beginPos+1
if (beginPos>adMsg.length)
{
beginPos=0
}
window.setTimeout("scrollingMsg()",200)
}
var salesAmt
var loanAmt
var loanRate
var loanYears
function validSalesAmt()
{
var salesAmt=parseInt(homeLoanForm.SaleAmount.value,10)
if(isNaN(salesAmt)||(salesAmt <= 0))
{
alert("The sales price is not a valid number!")
homeLoanForm.SaleAmount.value = ""
homeLoanForm.SaleAmount.focus()
}
else
{
var downPmtAmt=parseInt(homeLoanForm.DownPayment.value, 10)
if(isNaN(downPmtAmt)||(downPmtAmt<=0)||(downPmtAmt>salesAmt))
{
alert("The down payment should be greater than 0 and less than the sales amount!")
homeLoanForm.DownPayment.value=""
homeLoanForm.DownPayment.focus()
}
else
{
loanAmt = salesAmt-downPmtAmt
homeLoanForm.LoanAmount.value=loanAmt
homeLoanForm.Rate.focus()
}
}
}
function CalcLoanAmt()
{
loanRate=parseFloat(homeLoanForm.Rate.value)
if (isNaN(loanRate) || (loanRate <= 0))
{
alert("The interest rate is not a valid number!")
homeLoanForm.Rate.value=""
homeLoanForm.Rate.focus()
}
else
{
loanYears=homeLoanForm.Years.value
if (isNaN(loanYears) || (loanYears < 1 || loanYears >30))
{
alert("Please select a valid number from the list (10,15,20, or 30)!")
homeLoanForm.Years.selectedIndex = 0
homeLoanForm.Years.focus()
}
else
{
var monthlyPmtAmt = monthlyPmt(loanAmt,loanRate,loanYears)
homeLoanForm.Payment.value=dollarFormat(monthlyPmtAmt.toString())
}
}
}
function monthlyPmt(loanAmt,loanRate,loanYears)
{
var interestRate = loanRate/1200
var Pmts = loanYears*12
var Amnt - loanAmt * (interestRate/(1-(1/Math.pow(1+interestRate,Pmts))))
return Amnt.toFixed(2)
}
function dollarFormat(valuein)
{
var formatValue= ""
var formatDollars= ""
formatAmt = valuein.split(".",2)
var dollars = formatAmt[0]
var dollarLen = dollars.length
if (dollarLen > 3)
{
while (dollarLen > 0)
{
tempDollars = dollars.substring(dollarLen - 3,dollarLen)
if(tempDollars.length == 3)
{
formatDollars = ","+tempDollars+formatDollars
dollarLen = dollarLen - 3
}
else
{
formatDollars = tempDollars+formatDollars
dollarLen = 0
}
}
if(formatDollars.substring(0,1) == ",")
{
dollars = formatDollars.substring(1,formatDollars.length)
}
else
dollars = formatDollars
}
var cents = formatAmt[1]
var formatValue="$"+dollars+"."+cents+
return formatValue
}
function popUpNotice()
{
open("chapter10-1notice.html","noticeWin","width-520,height=330")
}
function copyRight()
{
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
displayDateLast.innerHTML="<h6>Copyright© Shoreline State Bank"+"<br />This document was last modified "+lastModDate+".</h6>"
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
</head>
<body onLoad="scrollingMsg(); popUpNotice(); copyRight();">
<div class="center-div">
<p class="center-items"><img src="chapter10-1banner.jpg" alt="banner" /></p>
</div>
<div class="center-div">
<form id="msgForm">
<p style="text-align:center">
<input type="text" name="scrollingMsg" size="25" /></p>
</div>
<p style="text-align:center; font-size:16; font-weight:bold;">Home Mortgage Loan Payment Calculator</p>
<p class="block"><strong>Directions: </strong>Enter the agreed selling price, press the tab key, enter the down payment and press the tab key. The loan amount will be calculated automatically. Then enter the interest rate and the number of years for the loan and click the Calculate button.</p>
<div class="center-div">
<form id="homeLoanForm" method="post">
<table>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Sales Price:
</td>
<td class="align-left"><input type="text" name="SaleAmount" size="9" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Down Payment in Dollars
</td>
<td class="align-left"><input name="DownPayment" type="text" id="DownPayment" size="9" onBlur="validSalesAmt()" /></td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Loan Amount
</td>
<td class="align-left"><input name="LoanAmount" type="text" id="LoanAmount" size="9" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Interest Rate (e.g. 5.9):
</td>
<td class="align-left"><input name="Rate" type="text" id="Rate" size="5" maxlength="5" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Number of Years:
</td>
<td><select name="Years" id="Years">
<option value="0">Select Number of Years</option>
<option value=10>10</option>
<option value=15>15</option>
<option value=20>20</option>
<option value=30>30</option>
</select></td>
</tr>
<tr>
<td class="right-align">
<input name="button" type="button" value="Calculate" onClick="CalcLoanAmt()"/>
</td>
<td class="align-left">
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">Monthly Payment:</span>
</td>
<td><input type="text" name="Payment" id="Payment" value=" " size="12" /></td>
</tr>
<tr>
<td colspan="2" class="align-center">
<span style="color:#cc0000; font-size:12px;">* Indicates a required field.</span>
</td>
</tr>
</table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
when the browser finds a syntax-error in a <script> he will discard the entire script-code within this script.
a simple demonstration:
<body onLoad="foo();bar();foobar();">
<script type="text/javascript">
var a + b;//syntax-error, similar to line 86 in your script
//this will not run because this script has been discarded
//because of the syntax-error above
function bar(){
alert('bar works');
}
</script>
<script type="text/javascript">
//this will run because here is no syntax-error,
//the function is available
function foo(){
alert('foo works');
}
//although this function is available too this will not run
//because of the error forced by the call of bar()
function foobar(){
alert('foobar works');
}
</script>
</body>
That's why the function scrollingMsg will be unknown, although there is no syntax-error within this function, because there are multiple syntax-errors in this script, fix them.

Categories

Resources