Form validation linking fields as required - javascript

I am looking to do some client size validation. Below you will find an example of my template.
When this form is submitted it is okay for a line to be empty. However I want to be sure if even one item in a line is selected/has an entry that all lines will have an entry. For example. There should always be either Nothing OR require a Date, start Time, stop time, and class. (the class is populated by a button in another location) The validation will be used to warn the individual if they are missing anything and if they submit we will disregard the record as incomplete.
I have looked at jquery Validation as we are already using it on other forms in our project but, I have been unable to find a way to link row items together.
<form>
<table id="payableEventTable" class="table table-condensed table-striped">
<thead>
<tr>
<th>Date</th>
<th>Class/Scenario</th>
<th>Start</th>
<th>Stop</th>
<th>Break</th>
</tr>
</thead>
<tbody id="payableEventTableBody">
<c:forEach begin="0" end="5" varStatus="i">
<tr>
<td><input type="date" class="input-small" name="claimForm.payableEvents[${i.index}].eventDate" /></td>
<td>
<select class="classSelect" name="claimForm.payableEvents[${i.index}].event">
<option></option>
</select>
</td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStartTime" /></td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStopTime" /></td>
<td>
<select>
<option value="0" selected>No Break taken</option>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
</select>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Technology we are willing to use. HTML, CSS, javaScript, jQuery, (lightweight plugins for jquery). We also have to make sure the solution works back to IE8.
Edit:
I built a JSFiddle. To help with visualization.
Edit:
I have come up with an answer. However, if anyone is able to improve on my answer, streamline it/make it look nicer I would still be willing to give out the Bounty to that person.

Here is my suggestion: To make your code more legible, you can combine the three functions validateRow(), isRowEmpty(), isRowComplete() into one simpler validateRow() function. Also it is a lot faster, because you only need to go through all elements and check their values once instead of twice.
I also created a simple to use validateForm() function to tidy things up.
The validateForm() function can now be used in an event handler:
// Event Handler
$('#validate').bind('click', function(e){
e.preventDefault();
if(validateForm()) {
alert("next");
//$('#claimWizard').wizard('next');
}
});
// Form Validation
var validateForm = function(){
var valid = true;
$('#payableEventTableBody tr').each(function() {
if (validateRow($(this))) {
$(this).removeClass("error");
}
else {
valid = false;
$(this).addClass('error');
}
});
return valid;
}
var validateRow = function(row){
var state = null,
valid = true;
row.find('input, select').each(function() {
var value = $(this).val(),
isEmpty = (value != 0 && value !== '');
//if its the first element just save the state
if(state === null) {
state = isEmpty;
}
// if this field has not the same state as the rest
else if(state !== isEmpty) {
valid = false;
}
})
return valid;
}
And here's your fiddle with my code implemented: http://jsfiddle.net/KNDLF/

So, what I came up with:
Three methods: isRowValid(), isRowEmpty(), isRowComplete()
The rows need to be either empty or complete.
//The following code is part of my logic on continuing
var valid = true;
$('#payableEventTableBody tr').each(function() {
$(this).removeClass('error');
if (!isRowValid($(this))) {
valid = false;
$(this).addClass('error');
return;
}
});
if (valid) {
$('#claimWizard').wizard('next');
}
//The following is my validation methods
<script type="text/javascript">
function isRowValid($tr) {
return (isRowEmpty($tr) || isRowComplete($tr));
}
function isRowEmpty($tr) {
var isEmpty = true;
$tr.find('input, select').each(function() {
var value = $(this).val();
if (value != 0 && value !== '') {
isEmpty = false;
}
});
return isEmpty;
}
function isRowComplete($tr) {
var isComplete = true;
$tr.find('input, select').each(function(){
var value = $(this).val();
if(value === ''){
isComplete = false;
}
});
return isComplete;
}
</script>

This should be good to start with
http://jsfiddle.net/rJaPR/
$('#validate').bind('click', function(e){
e.preventDefault();
$('#payableEventTable tr').each(function(){
var tr = $(this);
var newRowValue=0;
$(tr).find('input, select').each(function(){
var value = $(this).val();
switch(newRowValue){
case 0:
// first input/select
newRowValue = ((value!=0 && value!='') ? 1 : -1);
break;
case 1:
// there are some values in this row
if (value==0 || value=='')
tr.css('backgroundColor', 'red');
break;
case -1:
// this row should be empty
if (value!=0 && value!='')
tr.css('backgroundColor', 'red');
break;
}
})
})
})

Related

How to get value of dynamically generated textbox with same id using AJAX/PHP?

In this webpage I am generating multiple textbox dynamically and each textbox is meant to hold unique value and I want to get that value dynamically.But I'm not being able to catch the value of the textbox according to its position. This code is only working for the firstly generated textbox. I have code like this
<tr>
<td align="center"><input type="text" name="serialNoArray[]" id="serialArray" onChange="checkusername()" ><span id="std_id_status"></span></td>
</tr>
<script>
function checkusername() {
var s = _("serialArray").value;
if(s != "") {
_("std_id_status").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true){
_("std_id_status").innerHTML = ajax.responseText;
}
}
ajax.send("std_id_check="+s);
}
}
</script>
First you should use classes not id, because an element with id must be unique for the entire document.
And since you use onChange you can pass the element using this like that onChange="checkusername(this)" .
I guess you should also change the code of the restrict function onkeyup="restrict('serialArray')" also but i do not see that code so I cannot help you more if you do not provide this code too...
<tr>
<td align="center"><input type="text" name="serialNoArray[]" class="serialArray" onkeyup="restrict('serialArray')" onChange="checkusername(this)" ><span class="std_id_status"></span></td>
</tr>
Then you can get only the value of the element being changed and change the html of the matching span only.(I use jQuery in the example so you should include it in your document.)
<script>
function checkusername(s) {
if (s.value != "") {
$(s).nextAll('.std_id_status').first().html('checking ...');
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
$(s).nextAll('.std_id_status').first().html(ajax.responseText);
}
}
ajax.send("std_id_check=" + s.value);
}
}
</script>
Since i do not have all your javascript code I could not test it but something like this should work.
I have not tested but this should do it
All the dynamically generated textboxes, give them a class
<input type="text" class="tagMe" placeholder="Enter Serial No." onkeypress="return isNumberKey2(event)" onkeyup="restrict('serialArray')" onChange="checkusername()" required autofocus >
Collecting the data
var info= "";
$('.tagMe').each( obj, function( key, value ) {
if(info != "")
info += "^"; // ^ is a delimiter
info += value;
});
Send info to your server, split on ^ and parse data (careful of empty elements)

Multiple inputs with duplicate value check

I have a button to create input tags. When user click submit button I want to find inputs with duplicate values and change border to red.
I'm not using jquery validate plugin
html code:
<form>
<table>
<tr>
<td><input type="text" name="text[]" id="1"> <button class="add">add</button></td>
</tr>
</table>
<input type="submit" id="submit" value="check">
</form>
jQuery code:
// add input
var i = 2;
$('.add').click(function(e){
e.preventDefault();
$('table').append("<tr><td><input type="text" name="text[]" id="'+i+'"> <button class="add"></td></tr>");
i++;
});
$('#submit').click(function(){
// I do not know how to write ...
});
Here is what you want
$('#submit').click(function () {
var valid = true;
$.each($('input[type="text"]'), function (index1, item1) {
$.each($('input[type="text"]').not(this), function (index2, item2) {
if ($(item1).val() == $(item2).val()) {
$(item1).css("border-color", "red");
valid = false;
}
});
});
return valid;
});
If somebody is after this, with a lot of inputs, and is concerned with efficiency, this yields the same result (duplicates besides the first occurrence are marked):
$('#submit').click(function(){
var values = []; //list of different values
$('table input:text').each(
function() {
if (values.indexOf(this.value) >= 0) { //if this value is already in the list, marks
$(this).css("border-color", "red");
} else {
$(this).css("border-color", ""); //clears since last check
values.push(this.value); //insert new value in the list
}
}
);
});
fiddle:
https://jsfiddle.net/4s82L4vg/

Javascript Drop Down

I'm working on a form that has multiple drop downs which get checked whether the user has selected something or not. Most fields are mandatory so upon clicking submit, red text replaces the black, showing which have to be filled in. It isn't validating for some reason or doing what it is i'm trying to accomplish. Other fields that have a id such as 'literature' work fine but this doesn't. Could it be because it's numeric?
Javascript:
var lit = document.getElementById("012");
var hasLeadLiterature = false;
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
if (!hasLeadLiterature){
changeCSS("lbl_literature", "errored");
ErrorText=ErrorText+"11";
}
------
if (submitcount != 0){
alert("This form has already been submitted. Thank you!");
return;
}
/** Submit form check */
if (ErrorText == ""){
submitcount++; form.submit();
} else{
return;
}
------
HTML:
<TR>
<TD width="30%" valign="middle" ALIGN="left"><LABEL id="lbl_literature" for="lbl_literature" class="normal">How would you prefer to receive<br /> literature?: <SPAN class="required">*</SPAN></LABEL></TD><TD width="70%" valign="top" ALIGN="LEFT">
<TABLE>
<TR>
<td class="text_input"> <!-- 012 -->
<select id="012" name="012" title="Literature Preference">
<option value="None">--None--</option>
<option value="Print">Print</option>
<option value="Digital">Digital</option>
</select>
</td>
</TR>
</TABLE>
</TD>
</TR>
Any help would be much appreciated!!
Thanks in advance!
I believe there is a problem with your for loop, it is not looping anything, have you checked it does loop?
I suggest you read up about how to use a for loop, correct code will be more like:
for (var i=0; i<lit.length; i++)
Because this loop is not valid hasLeadLiterature never changes which by the nature of your code bypasses everything.
It looks like your validation is checking the opposite condition. Take a look:
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
If you get rid of the unnecessary loop structure, you're doing this:
if (lit[0].selected === true) {
hasLeadLiterature = true;
}
In this case, lit[0] is the first, empty option element in the select element. So your condition is saying that if the empty option is selected, the form validates. Shouldn't you reverse that condition? Something like this:
if (lit[0].selected === false) {
hasLeadLiterature = true;
}

javascript validation of radio buttons in a form

hope someone can shed light on the below code which alerts always the error below. The code was devised to validate one radio button is selected otherwise return false to the current page otherwise proceed with the form action. Thanking in you in advance!!
function onDisplayItemsForm(){
var re = false; // used to determine when a button is checked
var radIdSelected = frmDisplayItems;
// traverse the radio buttons
// if one is checked sets re to true, and stops the iteration
for(var i=0; i<radIdSelected.length; i++)
{
if(radIdSelected[i].checked == true)
{
re = true;
break;
}
if (!radIdSelected[i].checked)
{
alert("Please select product");
return false;
}
return true;
}
};
The form is as follows:
<form name="frmDisplayItems" action="showItem.php" onsubmit="return onDisplayItemsForm();" >
<table width="50%" border="1">
<th>Country of Origin</th>
<th>Select</th>
</tr>
<td><input name=\"radId\" type=\"radio\" value=\"$id\" /></td>
</tbody>
</table>
<p><input name="btnSubmit" type="submit" value="Select"/> </p>
</form>
<
It's the value of re that you want to check after the loop has finished:
if (!re)
{
alert("Please select product");
return false;
}
return true;

How to hide/show messages in javascript when they should be hidden/shown?

I have a code below where it contains a form which contains text inputs a drop down menu:
$editsession = "
<form id='updateCourseForm'>
<p><strong>Current Course Details:</strong></p>
<table>
<tr>
<th>Course ID:</th>
<td><input type='text' id='currentCourseNo' name='CourseNocurrent' readonly='readonly' value='' /> </td>
</tr>
</table>
<div id='currentAlert'></div>
<p><strong>New Course Details:</strong></p>
<table>
<tr>
<th>Course ID:</th>
<td><input type='text' id='newCourseNo' name='CourseNoNew' value='' /> </td>
</tr>
</table>
<div id='newAlert'></div>
</form>
<p id='submitupdatebtn'><button id='updateSubmit'>Update Course</button></p>
";
echo $editsession;
Now I want to validate the form using Javascript and below is the code for the javascript validation:
function editvalidation() {
var isDataValid = true;
var currentCourseO = document.getElementById("currentCourseNo");
var newCourseNoO = document.getElementById("newCourseNo");
var currentCourseMsgO = document.getElementById("currentAlert");
var newCourseMsgO = document.getElementById("newAlert");
if (currentCourseO.value == ""){
currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
$('#newAlert').hide();
isDataValid = false;
}else{
currentCourseMsgO.innerHTML = "";
}
if (newCourseNoO.value == ""){
newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit";
$('#newAlert').show();
isDataValid = false;
} else{
newCourseMsgO.innerHTML = "";
}
return isDataValid;
}
Now this is the problem I am getting:
What I am trying to state in my javascript validation is that if the #currentCourseNo is empty (text input is blank), then it displays the error message for this which belongs to the div tag #currentAlert, but it hides messages which are displayed in the div tag #newAlert. If the #currentCourseNois not empty then show the #newAlert error messages if there are any.
The problem I am having is that it is still showing the #newAlert error messages when the #currentCourseNo text input is empty, when it really should be hidden. What needs to be changed in the javascript above in order to achieve what I want to achieve?
First, learn about jQuery.
For your process, my common flow is to add a first pass of validation on the blur event of the inputs, and a second (exactly the same) pas of validation on the submit event of the form, something like :
var error = $('.errormsg');
var checks =
{
"fieldName1": function(val) { return /*true or an error string*/ },
"fieldName2": function(val) { return /*true or an error string*/ }
};
$('input')
.focus(function()
{
$(this).removeClass('error');
})
.blur(function()
{
error.slideUp(200);
var check = checks[this.name];
if (!check) { return; }
var validation = check(this.value);
if (typeof validation === "string")
{
$(this).addClass('error');
error.text(validation).slideDown(200);
}
});
$('form').submit(function(e)
{
//e.preventDefault();
if ($('input.error').length != -1)
{
error.text('All fields are required').slideDown(200);
return;
}
for(var check in checks)
{
var field = $('input[name="' + check + '"]');
if (field.length == -1) { continue; }
var validation = check(field.val());
if (typeof validation === "string")
{
field.addClass('error');
error.text(validation).slideDown(200);
return;
}
}
});

Categories

Resources