PROBLEM:
I have form which submits list of fields. My form includes 2 'overwrite' fields:
counter - how many items to be submitted
field overwrite - if filled it suppose to overwrite all inputs in table with the same value
finally I have 5 field inputs (field_1, field_2, field_3, field_4 and field_5).
What I am trying to do is:
Counter - when filled it will disable field_ with number lower than value in counter, eg. when counter = 3, inputs field_4 and field_5 will get disabled.
field_0 - when empty, I would like user to be able to fill anything in table. When populated, I would like field_0 to be copied over to all cells in table.
WHAT I HAVE DONE:
I currently have extremely inefficient working code. I have complicated 'if' statement which checks counter and field_0 individually for every single of items (field_1 - field_5) one by one and sets them to enable/disable or copies over field_0 value. I also have 'clearFieldClass' function which clears all items with class 'field' when field_0 is being changed. While it works for 5 fields and one field type final version of the page will have 200 fields x 10 different classes. I am trying to avoid having 2000 lines of code doing basically he same thing.
function clearFieldClass() {
var elements = [] ;
elements = document.getElementsByClassName("field");
for(var i=0; i<elements.length ; i++){
elements[i].value = "" ;
}
}
<form action="https://www.tobesubmitted.to.com?" onchange="
if (counter.value > 0 && field_0.value == '') {document.getElementById('field_1').disabled = false;} else if (counter.value > 0 && field_0.value !== '') {field_1.value = field_0.value, document.getElementById('field_1').disabled = false;} else {document.getElementById('field_1').disabled = true; field_1.value = ''};
if (counter.value > 1 && field_0.value == '') {document.getElementById('field_2').disabled = false;} else if (counter.value > 1 && field_0.value !== '') {field_2.value = field_0.value, document.getElementById('field_2').disabled = false;} else {document.getElementById('field_2').disabled = true; field_2.value = ''};
if (counter.value > 2 && field_0.value == '') {document.getElementById('field_3').disabled = false;} else if (counter.value > 2 && field_0.value !== '') {field_3.value = field_0.value, document.getElementById('field_3').disabled = false;} else {document.getElementById('field_3').disabled = true; field_3.value = ''};
if (counter.value > 3 && field_0.value == '') {document.getElementById('field_4').disabled = false;} else if (counter.value > 3 && field_0.value !== '') {field_4.value = field_0.value, document.getElementById('field_4').disabled = false;} else {document.getElementById('field_4').disabled = true; field_4.value = ''};
if (counter.value > 4 && field_0.value == '') {document.getElementById('field_5').disabled = false;} else if (counter.value > 4 && field_0.value !== '') {field_5.value = field_0.value, document.getElementById('field_5').disabled = false;} else {document.getElementById('field_5').disabled = true; field_5.value = ''};
">
<table border="0">
<tr>
<th align="left">Overwrites</th>
<th></th>
</tr>
<tr>
<td><label>Counter </label></td>
<td><input required type="text" id="counter" name="counter" placeholder="Max 50"></input></td>
</tr>
<tr>
<td><label>Overwrite field: </label></td>
<td><input required type="text" id="field_0" name="field_0" placeholder="Field" onchange="clearFieldClass()"></input></td>
</tr>
</table><br><br>
<table>
<tr align="left">
<th>Field</th>
</tr>
<tr>
<td><input required type="text" class='field' id="field_1"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_2"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_3"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_4"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_5"></td>
</tr>
</table>
<input type="submit" value="Submit form"></input>
Remove onchange attribute from your html and use the following code:
document.querySelector('form').addEventListener('change', () => {
document.querySelectorAll('.field').forEach((_el, index) => {
if(!isNaN(+counter.value) && +counter.value != 0 && index + 1 > +counter.value){
_el.disabled = 'disabled';
_el.value = '';
console.log('in')
}
else{
_el.removeAttribute('disabled');
_el.value = field_0.value;
}
});
})
Related
I am trying to get the values of checkboxes which are in the same divid but have different class name.
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="CurrentYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="PreviousYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="LastYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
With above code, I am able to populate data in a table with multiple checkboxes, but unable to get the value of the checkbox where the class name is something other than EntityCheck. Below is my jQuery function:
function GetSelectedEntities() {
var entities = "";
$("#divEntities").find('td').each(function (i, el) {
var checkbox = $(this).find('input.EntityCheck');
//var check1 = $(this).find('CurrentYear');
//var check2 = $(this).find('PreviousYear');
//var check3 = $(this).find('LastYear');
var check1 = $('.CurrentYear').val();
var check2 = $('.PreviousYear').val();
var check3 = $('.LastYear').val();
if (checkbox != undefined && $(checkbox).length > 0 && $(checkbox).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "|" + EntityData;
}
}
});
return entities;
}
jQuery function is invoked on a button click event:
<button style="font:normal 9pt Arial;height:30px;width:100px;border-radius:5px; border:none; background-color:royalblue; color:white" id="btnAdd" onclick="GetSelectedEntities(event);">
Add
</button>
I tried by giving the same class name to all the checkboxes but the problem was that I was able to get the values of the year checkbox, even if the CompanyName was not selected. I need the year values only if the CompanyName checkbox is checked and it's corresponding years. I also tried by giving the id='' to the year checkbox, but could not get the values.
I am unable to figure where I am going wrong. What is that I need to change in my jQuery to get the expected result?
Something like this would work:
$('#btnAdd').on('click', function(){
var checked = $('table').find('input:checked');
checked.each(function(){
alert($(this).closest('td').text());
//do your stuff here..
});
});
Se working fiddle: https://jsfiddle.net/c8n4rLjy/
I had to make changes to get the desired solution. Please find the solution below:
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
jQuery:
function GetSelectedEntities() {
var entities = "";
var CompanySelected = false;
var counter = 0;
$("#divEntities").find('td').each(function (i, el) {
counter = counter + 1
var checkbox = $(this).find('input.EntityCheck');
var checkboxyear = $(this).find('input.chkYear');
if (counter == 2) {
if (checkbox != undefined) {
if ($(checkbox).prop('checked') == true) {
CompanySelected = true;
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "-" + EntityData;
}
}
else {
CompanySelected = false;
}
}
}
if (counter > 2) {
if (CompanySelected == true) {
if (checkboxyear != undefined) {
if ($(checkboxyear).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
entities = entities + "|" + EntityData;
}
}
}
}
if(counter == 5)
{
counter = 0;
}
});
return entities;
}
I have a table with three columns: a, b and c. The above code works for column a, b and c. The third column gives undefined value. I want to prevent this column from comparing, i.e. if I enter values in column a and b and leave column c as it is, the data should be saved. How to achieve this?
function saving(id) {
var store;
$('#mt .tb tr td').each(function() {
var value = $(this).find("input").val();
if (value === '' || value == null || value == " ")
store == "0";
else
store == "1";
});
if (store = "0") {
alert("empty rows cannot be saved")
return false;
} else
return true;
alert("saving successful")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mt">
<tr>
<thead>
<th>a</th>
<th>b</th>
<th>c</th>
</thead>
</tr>
<tr>
<tbody class="tb">
<td><input id="a"></td>
<td><input id="b"></td>
<td><i class="fa fa-pencil Addbtn"></i></td>
</tbody>
</tr>
<input type="submit" value="Save" onclick="return saving()">
</table>
You can add a class to the columns you don't want to compare
<td class='nocompare'>
and exclude those
$('#mt .tb tr td:not(.nocompare)').each
(or you could add compare to the ones you do want to compare to remove the double negative.
There were some other fundamental issues with the code:
setting a value uses = not == (store == 0)
comparing a value uses == (or ===) not = (if (store = 0))
you had an alert after the last return which would never get hit
by setting store = 1, your check only needs the last column to have a value and will pass if all of the ones before failed.
for the last issue, you can add up a count of all the passes and compare with how many there should be, eg:
var pass = 0;
$('#mt .tb tr td.check').each(function() {
var value = $(this).find("input").val();
if (value === '' || value == null || value == " ")
; // fail
else
pass++;
});
if (pass == $('#mt .tb tr td.check').length))
// all passed
or you can go with a bit flag and AND it as below.
function saving(id) {
var store = 1;
$('#mt .tb tr td.check').each(function() {
var value = $(this).find("input").val();
if (value === '' || value == null || value == " ")
store = 0;
else
store = store & 1;
});
if (store == "0") {
alert("empty rows cannot be saved")
return false;
} else {
alert("saving successful")
return true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mt">
<tr>
<thead>
<th>a</th>
<th>b</th>
<th>c</th>
</thead>
</tr>
<tr>
<tbody class="tb">
<td class='check'><input id="a"></td>
<td class='check'><input id="b"></td>
<td><i class="fa fa-pencil Addbtn"></i></td>
</tbody>
</tr>
<input type="submit" value="Save" onclick="return saving()">
</table>
I have the next table:
<table id="table_id">
<tr>
<td>Test</td>
<td>Description</td>
<td>Date</td>
</tr>
<tr>
<td><select>
<option val="1">Math</option>
<option val="2">Chemistry</option>
<option val="3">Biology</option>
</select></td>
<td><input type="text" id="txt_desc"/></td>
<td><input type="text" id="date"/></td>
</tr>
</table>
And the next javascript code for get the values
val_test_op = '';
parent.$('#table_id option:selected').each(function (index,value){
test = $.text(value).trim();
if ( index === 0 && test || index % 1 === 0 && test ) {
val_test_op += index +' TEST: ' + test;
return;
}
})
val_test_input = '';
parent.$('#table_id td>input').each(function (index,value){
test = this.value;
if ( index === 0 && test || index % 2 === 0 && test ) {
texto_examen_input += index +' Description: ' + test;
return;
}
if ( index === 1 && test || index % 3 === 0 && test ) {
texto_examen_input += index +' Date: ' + test;
return;
}
})
My question is: ¿ How i get the value from the option:selected and input text in a only "each function" ?
I don't think you need a each function for getting values from fields in the table.
If you add ids to the fields, you could select those directly with jquery then use the val function to get their values easily.
<table id="table_id">
<tr>
<td>Test</td>
<td>Description</td>
<td>Date</td>
</tr>
<tr>
<td><select id="txt_test">
<option val="1">Math</option>
<option val="2">Chemistry</option>
<option val="3">Biology</option>
</select></td>
<td><input type="text" id="txt_desc"/></td>
<td><input type="text" id="txt_date"/></td>
</tr>
</table>
Then with javascript:
val_test_op = $('#txt_test').val();
texto_examen_desc = $('#txt_desc').val();
texto_examen_date = $('#txt_date').val();
If you really want to use a single each function to get all the values, you could use the :input selector that jquery provides and do the following:
values = '';
$('#table_id').find(':input').each(function (index, input) {
values += $(input).val();
});
I added in a button to alert what the selected value is.
function myFunction(){
var theSelect = document.getElementById("table_id").getElementsByTagName("select")[0];
var selectedOption = theSelect.options[theSelect.selectedIndex].text;
alert(selectedOption);
}
document.getElementById("myButton").addEventListener("click", myFunction, false);
https://jsfiddle.net/e1hxn6kL/
Give your select an ID such as id="opts"
Then
var opts = [];
$.each($("#opts:selected"),function(opt){
opts.push(opt.Val());
}
var txt_desc = $("#txt_desc").Val();
var date = $("#date").Val();
Or similar
HTML Code:
<html>
<head>
<title>Registration</title>
<meta charset="utf-8">
<link href="home.css" rel="stylesheet" type="text/css"/>
<link href="booking.css" rel="stylesheet" type="text/css"/>
<script src="val_registration.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery.css">
<script src="jquery01.js" type="text/javascript"></script>
<script src="jquery02.js" type="text/javascript"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script language="JavaScript1.2">
var howOften = 5; //number often in seconds to rotate
var current = 0; //start the counter at 0
var ns6 = document.getElementById&&!document.all; //detect netscape 6
// place your images, text, etc in the array elements here
var items = new Array();
items[0]="<a href='link.htm'><img alt='photo01' src='photo01.jpg' height='237' width='750' border-style='inset' border-weight:'10px' /></a>"; //a linked image
items[1]="<a href='link.htm'><img alt='photo02' src='photo02.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[2]="<a href='link.htm'><img alt='photo03' src='photo03.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[3]="<a href='link.htm'><img alt='photo04' src='photo04.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[4]="<a href='link.htm'><img alt='photo05' src='photo05.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
function rotater() {
document.getElementById("placeholder").innerHTML = items[current];
current = (current==items.length-1) ? 0 : current + 1;
setTimeout("rotater()",howOften*1000);
}
function rotater() {
if(document.layers) {
document.placeholderlayer.document.write(items[current]);
document.placeholderlayer.document.close();
}
if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current]
if(document.all)
placeholderdiv.innerHTML=items[current];
current = (current==items.length-1) ? 0 : current + 1; //increment or reset
setTimeout("rotater()",howOften*1000);
}
window.onload=rotater;
</script>
</head>
<body>
<div id="login" name="login">
  Login  <b><b>|</b></b>
 New user?  
</div>
<img src="logo.jpg" alt="logo" id="logo" width="500" height="100" usemap="#logomap"/></br>
<map id="logomap" name="logomap">
<area shape="rect" coords="0,0,743,146" href="home.htm" alt="home"/>
<area shape="default" coords"0,0,743,146" href="home.htm" alt="home"/>
</map></br>
<div id="placeholderdiv"></div><br/>
<div id="mlink" >
Home
About Us
Promotion
Contact Us
FAQs
</div><br/>
<div id="opac">
<h1> Registration </h1>
<hr/>
<form action="success(registration_page).html" method="post" id="myform" onsubmit="return val_registration ()">
<table rules="none" cellpadding="10px" cellspacing="10px">
<tr>
<td><label for="Username">Username(No case sensitive):<span id="imp">*</span></label></td><td><input type="text" id="Username" tabindex="1"/>
<br/><span class="eg"> eg:ZerOGravitY</span></td>
</tr>
<tr>
<td><label for="Password">Password(Must more than<br/> 8 characters):<span id="imp">*</span></label></td><td><input type="text" id="Password" tabindex="2"/>
<br/><span class="eg"> eg:567834gravity</span></td></td>
</tr>
<tr>
<td><label for="Retype_password">Retype password:<span id="imp">*</span></label></td><td><input type="text" id="Retype_password" tabindex="3"/>
<br/><span class="eg"> eg:567834gravity</span></td></td>
</tr>
<tr>
<td><label for="First_name">First name:<span id="imp">*</span></label></td><td><input type="text" id="First_name" tabindex="4"/>
<br/><span class="eg"> eg:Loh</span></td></td>
</tr>
<tr>
<td><label for="Last_name">Last name:<span id="imp">*</span></label></td><td><input type="text" id="Last_name" tabindex="5"/>
<br/><span class="eg"> eg:Le You</span></td></td>
</tr>
<tr>
<td><label for="ID_number">ID number (Please omit '-') :<span id="imp">*</span></label></td><td><input type="text" id="ID_number" maxlength="12" tabindex="6"/>
<br/><span class="eg"> eg:940731140991</span></td></td>
</tr>
<tr>
<td><label for="datepicker">DOB:<span id="imp">*</span></label></td>
<td><input type="text" id="datepicker" tabindex="7"/></td>
</tr>
<tr>
<td>Mobile number:<span id="imp">*</span></td>
<td colspan="3">
<select tabindex="8">
<optgroup label="Prefix">
<option value="010">010</option>
<option value="012">012</option>
<option value="013">013</option>
<option value="016">016</option>
<option value="017">017</option>
<option value="018">018</option>
<option value="019">019</option>
</optgroup>
</select>
<input type="text" id="Mobile_number" tabindex="9"/>
<input type="text" class="err" id="err_Mobile_number" readonly="readonly"/>
<br/><span class="eg">
eg:2345678 or 23456789</span>
</td>
</tr>
<tr>
<td><label for="E_mail">E-mail:<span id="imp">*</span></label></td>
<td><input type="text" id="E_mail" tabindex="10"/>
<br/><span class="eg"> eg:abc123#hotmail.com</span></td></td>
</tr>
<tr>
<td colspan="4"><input type="submit" value="Confirm" id="confirm2" tabindex="11" />
<input type="reset" value="Cancel" id="cancel2" tabindex="12"/></td>
</tr>
<tr>
<td>Notes: <span id="imp">*</span> indicates the column that must be filled</td>
</tr>
</table>
</form>
</div>
<hr/>
<b><i id="copyright">Copyrighted : © 2014 I ♥ Travels agency. </i></b>
<b><address id="address"> Address : I love agency, Taman Setapak, Jalan Genting Klang, 53300 Kuala Lumpur </address></b>
</body>
</html>
This is my JavaScript code (for form validation):
function val_registration ()
{
var val_Username = document.getElementById("Username").value;
var string_Username = /^[a-zA-Z0-9]{1,}$/;
var err = "";
if (val_Username == null || val_Username == "" || !string_Username.test(val_Username))
{
err += "\u2022Username cannot be blank/Username can contain\n alphabets or numbers only.\n";
document.getElementById("Username").focus();
}
var val_Password = document.getElementById("Password").value;
var string_Password = /^[a-zA-Z0-9]{9,}$/;
if (val_Password == null || val_Password == "" || !string_Password.test(val_Password))
{
err += "\u2022Password cannot be blank/Password can contain\n alphabets or numbers only and it must contain at \n least 9 characters.\n";
document.getElementById("Password").focus();
}
var val_Retype_password = document.getElementById("Retype_password").value;
if (val_Retype_password == null || val_Retype_password == "" || val_Retype_password != val_Password)
{
err += "\u2022Retype password cannot be blank/Retype password\n must same with password typed.\n";
document.getElementById("Retype_password").focus();
}
var val_First_name = document.getElementById("First_name").value;
var string_First_name = /^[a-zA-Z]{1,}$/;
if (val_First_name == null || val_First_name == "" || !string_First_name.test(val_First_name))
{
err += "\u2022Firstname cannot be blank/Firstname can contain \u00A0alphabets only.\n";
document.getElementById("First_name").focus();
}
var val_Last_name = document.getElementById("Last_name").value;
var string_Last_name = /^[ a-zA-Z#'\-_()\.,]{1,}$/;
if (val_Last_name == null || val_Last_name == "" || !string_Last_name.test(val_Last_name))
{
err += "\u2022Lastname cannot be blank/Lastname can contain\n alphabets or special symbols(# ' - _ ( ).,) only.\n";
document.getElementById("Last_name").focus();
}
var val_ID_number = document.getElementById("ID_number").value;
var string_ID_number = /^[0-9]{12}$/;
if (val_ID_number == null || val_ID_number == "" || !string_ID_number.test(val_ID_number))
{
err += "\u2022Id number cannot be blank/Id number can contain\n excatly 12 numbers only.\n";
document.getElementById("ID_number").focus();
}
var val_datepicker = document.getElementById("datepicker").value;
if (val_datepicker == null || val_datepicker == "")
{
err += "\u2022DOB cannot be blank.\n";
document.getElementById("datepicker").focus();
}
var val_Mobile_number = document.getElementById("Mobile_number").value;
var string_Mobile_number = /^[0-9]{7,8}$/;
if (val_Mobile_number == null || val_Mobile_number == "" || !string_Mobile_number.test(val_Mobile_number))
{
err += "\u2022Mobile number cannot be blank/Mobile number can\n \u00A0contain 7 or 8 numbers only.\n";
document.getElementById("Mobile_number").focus();
}
var val_E_mail = document.getElementById("E_mail").value;
var atpos = val_E_mail.indexOf("#");
var dotpos = val_E_mail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2 >= val_E_mail.length)
{
err += "\u2022E-mail cannot be blank/E-mail format must follow\n \u00A0the example provided.\n";
document.getElementById("E_mail").focus();
}
if (err != null || err != "")
{
alert(err);
return false;
}
}
This works fine except for one thing:
When all fields are empty, an alert box pops up to indicate the error. However, after I click 'OK', it directly moves to the DOB field instead of
the username field.
When I click OK, I want it to validate and focus on the first element in the sequence which is not filled or is invalid.
For example: If both the username and password fields are empty and I click OK, the focus should go to the username field first.
you need to return false; after each validation check!
try this:
Edit1:
function val_registration()
{
var $invalidInput;
var val_Username = document.getElementById("Username").value;
var string_Username = /^[a-zA-Z0-9]{1,}$/;
var err = "";
if (val_Username == null || val_Username == "" || !string_Username.test(val_Username))
{
err += "\u2022Username cannot be blank/Username can contain\n alphabets or numbers only.\n";
var $input = document.getElementById("Username");
$invalidInput=$input;
}
var val_Password = document.getElementById("Password").value;
var string_Password = /^[a-zA-Z0-9]{9,}$/;
if (val_Password == null || val_Password == "" || !string_Password.test(val_Password))
{
err += "\u2022Password cannot be blank/Password can contain\n alphabets or numbers only and it must contain at \n least 9 characters.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Password");
$invalidInput=$input;
}
}
var val_Retype_password = document.getElementById("Retype_password").value;
if (val_Retype_password == null || val_Retype_password == "" || val_Retype_password != val_Password)
{
err += "\u2022Retype password cannot be blank/Retype password\n must same with password typed.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Retype_password");
$invalidInput=$input;
}
}
var val_First_name = document.getElementById("First_name").value;
var string_First_name = /^[a-zA-Z]{1,}$/;
if (val_First_name == null || val_First_name == "" || !string_First_name.test(val_First_name))
{
err += "\u2022Firstname cannot be blank/Firstname can contain \u00A0alphabets only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("First_name");
$invalidInput=$input;
}
}
var val_Last_name = document.getElementById("Last_name").value;
var string_Last_name = /^[ a-zA-Z#'\-_()\.,]{1,}$/;
if (val_Last_name == null || val_Last_name == "" || !string_Last_name.test(val_Last_name))
{
err += "\u2022Lastname cannot be blank/Lastname can contain\n alphabets or special symbols(# ' - _ ( ).,) only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Last_name");
$invalidInput=$input;
}
}
var val_ID_number = document.getElementById("ID_number").value;
var string_ID_number = /^[0-9]{12}$/;
if (val_ID_number == null || val_ID_number == "" || !string_ID_number.test(val_ID_number))
{
err += "\u2022Id number cannot be blank/Id number can contain\n excatly 12 numbers only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("ID_number");
$invalidInput=$input;
}
}
var val_datepicker = document.getElementById("datepicker").value;
if (val_datepicker == null || val_datepicker == "")
{
err += "\u2022DOB cannot be blank.\n";
if($invalidInput==undefined){
var $input = document.getElementById("datepicker");
$invalidInput=$input;
}
}
var val_Mobile_number = document.getElementById("Mobile_number").value;
var string_Mobile_number = /^[0-9]{7,8}$/;
if (val_Mobile_number == null || val_Mobile_number == "" || !string_Mobile_number.test(val_Mobile_number))
{
err += "\u2022Mobile number cannot be blank/Mobile number can\n \u00A0contain 7 or 8 numbers only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Mobile_number");
$invalidInput=$input;
}
}
var val_E_mail = document.getElementById("E_mail").value;
var atpos = val_E_mail.indexOf("#");
var dotpos = val_E_mail.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= val_E_mail.length)
{
err += "\u2022E-mail cannot be blank/E-mail format must follow\n \u00A0the example provided.\n";
if($invalidInput==undefined){
var $input = document.getElementById("E_mail");
$invalidInput=$input;
}
}
if (err != null || err != "")
{
$invalidInput.focus();
alert(err);
return false;
}
}
Why it was not working before:
your script was checking each element setting focus and adding error message as required for each element till the last element in the list. Focus state can only be active for a single element on the page at a time. Since the last erroneous element was receiving the focus every time for all the elements, it never stopped at first element.
What I did:
In updated script: I took a variable to store invalid element's reference. As soon the code finds an invalid element- it assigns it to variable $invalidElement. It does the same for every element. So this way $invalidElement always refere to first erroneous element at a time whereas errors get added to the error list every time.
In the end it checks if error is not null. It it is, focus to the first erroneous element and show the error message.
Simple as that!
Hope it helps!
Usually on HTML, the focus order of elements depends on tabindex attribute.
However, if you want to avoid the "natural" or the defined by tabindex order of your focusing, you can always use
yourObject.focus();
Just define the situation you want to control and the behaviour you need to apply when it happens.
This question already has answers here:
Password Strength Meter [closed]
(3 answers)
Closed 9 years ago.
I'm creating a Create Account page and I'm trying to verify that the password they are creating follows the proper format.
The password format needs to be:
Minimum of:
15 characters
2 UPPER
2 lower
2 Numbers
2 Special
I've searched and have only been able to find a validation script that checks for 1 of each character, which I am currently using. I'm also using a function to confirm the password and confrim password fields match on key up, and a separate function to do the same on submit. Validating that they match on submit is not working either.
Here's what I have so far:
<script>
var anUpperCase = /[A-Z]/;
var aLowerCase = /[a-z]/;
var aNumber = /[0-9]/;
var aSpecial = /[!|#|#|$|%|^|&|*|(|)|-|_]/;
function testpasswd(form, ctrl, value)
{
if (value.length < 15 || value.search(anUpperCase) == -1 ||
value.search (aLowerCase) == -1 || value.search (aNumber) == -1 || value.search (aSpecial) == -1)
{
document.getElementById("pw").innerHTML="Invalid Password";
}
else
{
location.href = "submit.cfm";
}
}
function checkpasswds()
{
theForm = document.getElementById ( 'reg' ) ;
confm = document.getElementById ( 'confirm') ;
if (theForm.passwd2.value != '' && theForm.passwd1.value != '')
{
if (theForm.passwd1.value != theForm.passwd2.value)
{
confm.style.background = "url('images/wrong.png')" ;
confm.style.backgroundRepeat = "no-repeat" ;
confm.style.backgroundPosition = "right" ;
}
else
{
confm.style.background = "url('images/correct.png')" ;
confm.style.backgroundRepeat = "no-repeat" ;
confm.style.backgroundPosition = "right" ;
}
}
}
function cnfmpasswd(form, ctrl, value)
{
theForm = document.getElementById ( 'reg') ;
if (theForm.passwd2.value != '' && theForm.passwd1.value != '')
{
if (theForm.passwd1.value != theForm.passwd2.value)
{
return (false);
}
else
{
return (true);
}
}
}
function submitForm()
{
document.forms['reg'].submit;
testpasswd('reg','passwd1',document.getElementById('passwd1').value);
cnfmpasswd('reg','passwd2',document.getElementById('passwd2').value);
}
</script>
<cfform action="submit.cfm" method="post" name="reg" id="reg" format="html">
<table width="947" border="0">
<tr>
<td width="180" align="right"><p style="color:#EB0000; font-size:14px" align="center" id="pw"></p></td>
<td width="118" align="right">
Password:
</td>
<td width="635">
<cfinput
name="passwd1"
title="Must contain at least 2 of each of the following: UPPERCASE, lowercase, numeric, and special characters"
type="password"
required="yes"
onKeyUp="checkpasswds();"
/>
(min 15 characters with 2 UPPER, 2 lower, 2 numeric, and 2 special)
</td>
</tr>
<tr>
<td id="confirm" align="right"></td>
<td align="right">
Confirm Password:
</td>
<td>
<cfinput
name="passwd2"
type="password"
required="yes"
onKeyUp="checkpasswds();"
/>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>
<cfinput name="submit"
type="button"
value="Submit"
class="button"
onClick="submitForm()"
/>
</td>
</tr>
</table>
I'm a little new with javascript. Details will be greatly appreciated. I hope someone can help! Thanks!
I'm not looking for a strength meter or on keyup validation. I simply want to validate the password on submit.
This should do it:
var password = "TEstpass1aaaaaaa$$";
console.log(isOkPass(password));
function isOkPass(p){
var anUpperCase = /[A-Z]/;
var aLowerCase = /[a-z]/;
var aNumber = /[0-9]/;
var aSpecial = /[!|#|#|$|%|^|&|*|(|)|-|_]/;
var obj = {};
obj.result = true;
if(p.length < 15){
obj.result=false;
obj.error="Not long enough!"
return obj;
}
var numUpper = 0;
var numLower = 0;
var numNums = 0;
var numSpecials = 0;
for(var i=0; i<p.length; i++){
if(anUpperCase.test(p[i]))
numUpper++;
else if(aLowerCase.test(p[i]))
numLower++;
else if(aNumber.test(p[i]))
numNums++;
else if(aSpecial.test(p[i]))
numSpecials++;
}
if(numUpper < 2 || numLower < 2 || numNums < 2 || numSpecials <2){
obj.result=false;
obj.error="Wrong Format!";
return obj;
}
return obj;
}