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><</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>></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"><</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">></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><</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>></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><</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>></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>
Related
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 '
I am customizing this basic jQuery Data Table with Search Filter tutorial for my own use and it works great except I can't figure out how to toggle to show a specific message when the filter returns no results: https://www.coderbench.com/develop-jquery-data-table-search-filter/
Here is the script:
$(document).ready(function(){
$("#txtsearch").keyup(function(){
var value = $(this).val().toLowerCase();
$("#table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
This works for what I need except I want to display the following text above my table when there are no row matches and all rows are toggled hidden:
<span class="warning">Your search returned no results, please modify your entry.</span>
I imagine there's some elaborate conditional statement I could make here but I'm wondering if there's a simple way to do this....as is often the case. Thanks! Here is the full sample page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#txtsearch").keyup(function(){
var value = $(this).val().toLowerCase();
$("#table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #e3e3e3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #efefef;
}
</style>
<div>
<input id="txtsearch" type="text" placeholder="Search Here..." />
<br><br>
<table>
<thead>
<tr>
<th>Movies</th>
<th>Rating</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Spiderman Homecoming</td>
<td>9/10</td>
</tr>
<tr>
<td>Wonder Woman</td>
<td>8/10</td>
</tr>
<tr>
<td>The Guardians of Galaxy 2</td>
<td>8/10</td>
</tr>
<tr>
<td>Ant Man</td>
<td>7.5/10</td>
</tr>
</tbody>
</table>
</div>
Here's my try.
I don't use jQuery much so feel free to adapt things to a more "jQuery"-way.
const warning = document.querySelector('.warning');
const table = document.querySelector('table');
$(document).ready(function() {
$("#txtsearch").keyup(function() {
let value = $(this).val().toLowerCase();
let numberOfResults = 0;
$("#table tr").filter((index, tableRow) => {
let isAMatch = $(tableRow).text().toLowerCase().indexOf(value) > -1;
$(tableRow).toggle(isAMatch);
if (isAMatch) {
numberOfResults++;
}
});
if (numberOfResults === 0) {
warning.classList.add('show')
table.classList.add('no-results');
} else {
warning.classList.remove('show');
table.classList.remove('no-results');
}
});
});
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
}
table.no-results {
display: none;
}
td,
th {
border: 1px solid #e3e3e3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #efefef;
}
.warning {
margin-bottom: 10px;
display: none;
}
.warning.show {
display: block;
}
<div>
<span class="warning">Your search returned no results, please modify your entry.</span>
<input id="txtsearch" type="text" placeholder="Search Here..." />
<br><br>
<table>
<thead>
<tr>
<th>Movies</th>
<th>Rating</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Spiderman Homecoming</td>
<td>9/10</td>
</tr>
<tr>
<td>Wonder Woman</td>
<td>8/10</td>
</tr>
<tr>
<td>The Guardians of Galaxy 2</td>
<td>8/10</td>
</tr>
<tr>
<td>Ant Man</td>
<td>7.5/10</td>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
I have been given a task to make 2 HTML pages, one with form where the user enter his/her contact information and another where the user's information are viewed in a table.
I just need to use these languages only (JavaScript, jquery, HTML, CSS ,bootstrap); no use of PHP/JSP, only client-side language
and no database should be used. Up until now I have done this much.
$(function()
{
$('#form').validate(
{
rules:
{
email:
{required:true,
email:true
},
gender:
{required:true
},
cont:{
required:true,
number:true}
}
})
});
function onsumit(){
localStorage.setItem("input0",1);
var ip=document.getElementById("name");
localStorage.setItem("input1", ip.value);
var ip2=document.getElementById("email");
localStorage.setItem("input2", ip2.value);
var ip3=document.getElementById("cont");
localStorage.setItem("input3", ip3.value);
var ip4=document.getElementById("gender");
localStorage.setItem("input4", ip4.value);
var ip5=document.getElementById("comment");
localStorage.setItem("input5", ip5.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a> CONTACT FORM</a>
<form class="table-responsive" id="form" name="form" action="next.html" method="get" onsubmit="onsumit()" >
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name"required>*<p id="p1"></p></td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont"required>*<p id="p2"></p></td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email"required>*<p id="p3"></p></td>
</tr>
<tr>
<td>Gender:</td>
<td><select id="gender" name="gender" required>
<option value="" >SELECT</option>
<option value="male">MALE</option>
<option value="female">FEMALE</option>
</select>*<p id="p4"></p></td>
</tr>
<tr>
<td>comments:</td>
<td> <textarea class="form-control" rows="5" id="comment" maxlength="100"></textarea>
</td>
</tr>
</table>
<label><input id="submit" type="submit" value="SUBMIT"></label>
</form>
</div>
now this is the second html page.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
body {
font: 20px Montserrat, sans-serif;
line-height: 1.8;
color: black;
}
p {font-size: 16px;}
.margin {margin-bottom: 45px;}
.bg-1 {
background-color: #1abc9c; /* Green */
color: #ffffff;
}
.bg-2 {
background-color: #474e5d; /* Dark Blue */
color: #ffffff;
}
.bg-3 {
background-color: #ffffff; /* White */
color: #555555;
}
.bg-4 {
background-color: #2f2f2f; /* Black Gray */
color: #fff;
}
.container-fluid {
padding-top: 70px;
padding-bottom: 70px;
}
.navbar {
padding-top: 15px;
padding-bottom: 15px;
border: 0;
border-radius: 0;
margin-bottom: 0;
font-size: 12px;
letter-spacing: 5px;
}
.navbar-nav li a:hover {
color: #1abc9c !important;
}
#divmid {
margin:20px;
padding:20px;
border:3px solid red;
}
table{
text-align:left ;
}
th, td {
padding: 20px;
text-align:left;
}
textarea{
max-height:300px;
resize:none;
}
#div1{
text-align:center;
}
#tab2 {
text-align:left ;
border:2px solid red;
margin-left:auto;
margin-top:40px;
margin-bottom:200px;
}
#pick{
padding:100px;
}
<style>
table, td,th{
border: 1px solid black;
}
</style>
<body onload="load()">
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>S No.</th>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>COMMENTS</th>
<th>EDIT</th>
</tr>
</table>
</div>
</body>
The problem is I need to create a row in second page each time a user input with the new values in the form, but what in have done, it only creating one row and always updating it with the new values. Though I have used Local storage but still I am stuck here.
The problem is in the line 6 of your code. The parameter 1 passed to the insertRow function instantiates the variable row with the first row of your table. This way, every time you use insertCell in the row variable it updates the value on this first row. I think switching to rowCount + 1 will do the job.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(rowCount + 1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
take a look at this code. I think it should be what you are looking for.
Everytime the form is submitted, I first get the value of the local storage and add the new entry as JSON.
On the other page, I get the local storage, transform the value to get an object from the JSON string and use that object to show the informations inside the table.
Hope this help!
First Page :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function onsumit() {
if (typeof(Storage) !== "undefined") {
// Exemple of str : {'d' : [{'name':'Mister A','cont':'1',email':'MisterA#test.com'},{'name':'Mister B','cont':'1','email':'MisterB#test.com'}]}
var str = localStorage.getItem("contactinformation");
var contactModel;
if (str !== '') {
contactModel = JSON.parse(str);
} else {
contactModel = {
d : []
};
}
contactModel.d[contactModel.d.length] = {
name:$('#name').val(),
cont:$('#cont').val(),
email:$('#email').val()
}
localStorage.setItem("contactinformation",JSON.stringify(contactModel));
return true;
} else {
// Sorry! No Web Storage support..
return false;
}
}
</script>
</head>
<body>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a>CONTACT FORM</a>
<form id="form" name="form" action="next.html" method="get" onsubmit="return onsumit();">
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name">*</td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont">*</td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email">*</td>
</tr>
</table>
<input id="submit" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
Second Page :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, td,th{
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
var str = localStorage.getItem("contactinformation");
var info = JSON.parse(str);
if (typeof(info.d) !== "undefined") {
for (var x=0;x<info.d.length;x++) {
$('#tab2').append('<tr><td>' + info.d[x].name + '</td><td>' + info.d[x].cont + '</td><td>' + info.d[x].email + '</td></tr>');
}
}
}
});
</script>
</body>
</html>
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>
I have a dynamically created table where row2 and column2 onward elements are input fields. User can change these fields and submit.
I want to put a check so that in any row:
The 1st input field should not be greater than 2nd, 3rd or 4th
The 2nd input field should not be greater than 3rd or 4th. And it should not be smaller than 1st.
The 3rd input field should not be greater than 4th. And it should not be smaller than 1st or 2nd.
The 4th input field should not be smaller than 1st or 2nd or 3rd.
So if the user tries to change any value to an invalid value and click submit button, then an error message should be displayed and form should not be submitted. So only option on the message window should be an OK button which should bring the user back to the old page (before changes were made to any field).
I tried doing it by making use of getElementById() and giving same id for all four input fields in a row, but the getElementById() returns the first element if more than one id exists (id not being unique).
I checked possibility to try getElementsByName() but the value of name attribute is being generated dynamically and only "_good_high", "_warning_low", "_warning_high" and "_critical_low" is constant part of it.
Can you please suggest me some way to add this validation?
Link to jsfiddle is ExampleFiddle
<html>
<head>
<title>CommDesk AdminPage</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;
}
span.note1 {float:left}
span.note2 {font-size:90%}
table#t02, #t02 th, #t02 td {
border: none;
border-collapse: collapse;
font-size:90%;
font-weight:normal;
}
#button1{
position: relative;
top:10px;
left:75%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
</style>
</head>
<body>
<form id="form1" method="post" class="admin-form">
<div style="float:left; width:50%">
<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><</td>
<td style="padding:0 10px 0 0"><input type="text", class="admin-input", name="acd_call_volume_good_high", value="50", id="1", size="3", maxlength="3"></td>
<td><input type="text", class="admin-input", name="acd_call_volume_warning_low", value="50", id="1", size="3", maxlength="3"></td>
<td>to</td>
<td style="padding:0 10px 0 0"><input type="text", class="admin-input", name="acd_call_volume_warning_high", value="100", id="1", size="3", maxlength="3"></td>
<td>></td>
<td style="padding:0 10px 0 0"><input type="text", class="admin-input", name="acd_call_volume_critical_low", value="100", id="1", size="3", maxlength="3"></td>
</tr>
<tr>
<td align="center" class="expand1">SubRow1</td>
<td class="expand1"><</td>
<td class="expand1"><input type="text", name="acd_call_volume_good_high_SubRow1", value="50", id="2", size="3", maxlength="3"></td>
<td class="expand1"><input type="text", name="acd_call_volume_warning_low_SubRow1", value="50", id="2", size="3", maxlength="3"></td>
<td class="expand1">to</td>
<td class="expand1"><input type="text", name="acd_call_volume_warning_high_SubRow1", value="100", id="2", size="3", maxlength="3"></td>
<td class="expand1">></td>
<td class="expand1"><input type="text", name="acd_call_volume_critical_low_SubRow1", value="100", id="2", size="3", maxlength="3"></td>
</tr>
</table>
<input type="submit" name="submitButton" value="Submit" id="button1" style="height:50px; width:100px"/>
</div>
</form>
</body>
</html>
If you add the following snippet to you main $(function() {....
$( '.admin-input' ).change( function( e ) {
temp = e.target.name.split( '_' )
col = temp[ temp.length-2 ] + '_' + temp[ temp.length-1 ]
#validation logic
})
col will give you the last part of the changed cell's name e.g. warning_low. From there you can do any validation you want.
If you can change your perl code to change the names of the cells slightly so there is a better delimiter to split on, it would clean the code up a little ( e.g. acd_call_volume-warning_low ) but it's not so important.
I would also google for "jquery validator"