Unable to use form validations when adding rows with javascript - javascript

I am trying to submit a laravel form
Using a button I am adding dynamic rows with javascript. Code is
<input type="button" value="Add Particular" onClick="addRow('dataTable')"/>
Laravel Form:
<table class="table" id="dataTable">
<tr>
<td>
<label for="Fee Category" > Fee Category * </label>
<select name='CategoryID[]' rows='5' class='CategoryID' code='{$CategoryID}'
class='select2 ' requred ></select>
</td>
<td>
<label for="Amount">Amount *</label>
{{ Form::text('amount[]', $row['amount'],array('class'=>'form-control', 'placeholder'=>'', 'required'=>'true', 'parsley-type'=>'number' )) }}
</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
Javascript Functions to add & Delete Rows:
function addRow(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount<5)
{
var row = table.insertRow (rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0;i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML= table.rows[0].cells[i].innerHTML;
}
}
else
{
alert("Max Reached")
}
}
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
I am unable to use Laravel form validation error results to newly added rows. Its working fine on hard coded form rows. Please help
Also How can I keep minimum of one row. Currently delete button deletes all rows

You can add an onchange event on every field even in the dynamic ones, they will call the validator as sson as they are changed so the user knows in no time if it was a valid entrance.
I wrote this code in a hurry, color example is applied, new line example is too, remove is added too, empty box on focus is applied too and all other things asked.
<html>
<head>
<script type="text/javascript">
/**
A dynamic name is assigned to a new field created.
*/
var id=0;
var dbq="\"";
/************************* addRow function end ******************************************/
function addRow(count)
{
/**
Decide what fieldset is going to host the row
*/
var myFieldset='fieldset2';
var section='2';
if(count==4){
myFieldset='fieldset1';
var organisationID = id++;
var positionID = id++;
var section=''
}
/**
Create ids
*/
divID = id++;
nameID = id++;
emailID = id++;
/**
The row will be hosted in a div
*/
var myDiv = document.createElement("div");
myDiv.setAttribute("id", divID);
/**
Create the text boxes
*/
myDivInnerHTML=
'<input type=text name=name'+section+'[]'+' value=Name id='+nameID+
' onFocus='+dbq+'emptyTheBox('+nameID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+nameID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+nameID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=email'+section+'[]'+' value=Email id='+emailID+
' onFocus='+dbq+'emptyTheBox('+emailID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+emailID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+emailID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+'>' ;
/**
Decide if we need 4 or 2 boxes
*/
if(count==4)
myDivInnerHTML=myDivInnerHTML+
'<input type=text name=organisation'+section+'[]'+' value=Organisation id='+organisationID+
' onFocus='+dbq+'emptyTheBox('+organisationID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+organisationID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+organisationID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=position'+section+'[]'+' value=Position id='+positionID+
' onFocus='+dbq+'emptyTheBox('+positionID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+positionID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+positionID+');'+dbq+
' style='+dbq+'color:#66634F'+dbq+'>' ;
/**
Create a button to remove the row too.
*/
myDivInnerHTML=myDivInnerHTML+
'<input type=button class="remove" value="Remove" onClick='+dbq+'removeDiv('+divID+','+ myFieldset +');'+dbq+' >';
/**
Add the div-row to the fieldset
*/
myDiv.innerHTML = myDivInnerHTML;
document.getElementById(myFieldset).appendChild(myDiv);
}
/************************* addRow function end ******************************************/
/**
Change the color of the text being entered
*/
function changeInputColor(caller){
document.getElementById(caller).style.color = 'black';
}
/**
Remove a row on demand
*/
function removeDiv(divID, myFieldset){
myFieldset.removeChild(document.getElementById(divID));
}
/**
Empty the box on initial click
*/
function emptyTheBox(caller)
{
var val=document.getElementById(caller).value;
if(val=='Name' || val=='Email' || val=='Organisation' || val=='Position' )
document.getElementById(caller).value='';
}
/**
Display a message
*/
function echo(message)
{
document.getElementById('message').innerHTML="<h3>"+message+"</h3>";
}
/**********************Validates a single field, return false on fail************************/
function fieldValidator(caller)
{
var error='';
/**
Identify the field (if it is email, name etc) by getting the first character
which is always the same,also get its value and full name
*/
var currentFieldCategory = document.getElementById(caller).name.charAt(0);
var currentFieldValue = document.getElementById(caller).value;
var currentField = document.getElementById(caller);
/**
Check for empty value
*/
if(currentFieldValue == '')
{
echo('Please fill the data!');currentField.focus();
return 'Please fill the data!';
}
/**
Check if default value left behind
*/
if(currentFieldValue.toLowerCase()=="name" || currentFieldValue.toLowerCase()
=="email" || currentFieldValue.toLowerCase()=="organisation" ||
currentFieldValue.toLowerCase()=="position" )
{
echo('Please check you entry, default data left behind!');currentField.focus();
return 'Please check you entry, default data left behind!';
}
/**
Validate the NAME field
*/
if(currentFieldCategory=='n')
{
if(currentFieldValue.match(/^[ |'|-]/)||!(/^[a-zA-Z- ']*$/.test(currentFieldValue))
|| currentFieldValue.length<4 || currentFieldValue.length>70)
{
echo('Non valid name found!');currentField.focus();
return 'Non valid name found!';
}//inner if
}//outer if
/**
Validate a non empty EMAIL name field
*/
if(currentFieldCategory=='e')
{
var atpos=currentFieldValue.indexOf("#");
var dotpos=currentFieldValue.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=currentFieldValue.length)
{
echo('Non valid email found!');currentField.focus();
return 'Non valid email found!';
}//inner if
}//outer if
/**
Validate a non empty ORGANIZATION name field
*/
if(currentFieldCategory=='o')
{
if(currentFieldValue.length<2 || currentFieldValue.length>50)
{
echo('Use at least 2 letters and less than 50 for your organisation.');
currentField.focus();
return 'Use at least 2 letters and less than 50 for your organisation.';
}//inner if
}//outer if
/**
Validate a non empty POSITON name field
*/
if(currentFieldCategory=='p')
{
if(currentFieldValue.length<7 || currentFieldValue.length>40)
{
echo('Use at least 7 letters and less than 40 to describe your position.');
currentField.focus();
return 'Use at least 7 letters and less than 40 to describe your position.';
}//inner if
}//outer if
/**
Now on success do the rest
*/
document.getElementById(caller).style.backgroundColor = '#FF9900';
document.getElementById('message').innerHTML="";
return true;
}
/*****************fieldValidator ***function ends*****************************************/
/*******************************************************************************************/
function finalValidator()
{
/**
Get the form object
*/
var myForm=document.getElementById('booking').elements;
/**
Check if the form has no rows, for now 3 indicates no rows,
BE CAREFULL it might change if more buttons added,
just alert the length to see.
*/
if(myForm.length==3)
return false;
/**
Iterate through the form for all fields
*/
for(var i = 0; i < myForm.length; i++)
{
//If it is a text field validate it
if(myForm[i].type=='text')
{
var validation = fieldValidator(myForm[i].id);
if(validation!==true)
{
echo (validation);
return false;//prevent submit
}//validation if
}//field type if
}//for loop
}//function
/*******************************************************************************************/
</script>
</head>
<body bgcolor=gray>
<div id="add-buttons"><span class="add" onclick="addRow(4);"><input type="button" class="button" value="Add Waged Person"></span><span class="add" onclick="addRow(2);"><input type="button" class="button" value="Add Unwaged Person"></span></div>
<div id="message" ></div>
<div id="form-wrap">
<form method="post" name="booking" id="booking" action="bookingengine.php">
<fieldset id="fieldset1">
<div class="subtitle">Waged/Organisation Rate</div>
</fieldset>
<fieldset id="fieldset2">
<div class="subtitle">Unwaged Rate</div>
</fieldset>
<!-- return finalValidator will allow submit only if fields are validated-->
<p><input type="submit" name="submit" id="submit" onClick="return finalValidator();"
value="Submit booking" class="submit-button" /></p>
</form>
</body>
</html>
Validation added. The array and the color things are a bit trivial and you should show what effort you have done here your self.It is interesting to be involved only when you see the will on someone.

for adding the row
function addRow(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount<5)
{
var row = table.insertRow (rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0;i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML= table.rows[0].cells[i].innerHTML;
}
}
else
{
alert("Max Reached")
}
}
to delete the particular row use the rowIndex to find the particular row and deleteRow to delete the particular row from the table
function deleteRow(btn) {
var row = btn.parentNode.parentNode.rowIndex;
document.getElementById("dataTable").deleteRow(row);
}
for the valdation use the parentNode and childNodes because they will work on DOM

Related

Get multiple user inputs in one form field

I am trying to make a form field that asks the user which countries it has visited, and limit this to 10. So the user has to give ten inputs in one form field.
But when I click on the submit button it won't let the user enter a second time. It just calls the function that displays the first country that the user has entered.
How do I keep the values the user is entering in the form field and when the user has entered all the ten countries, then click on submit to call the function that would display all the countries?
function validateForm() {
var repeat = new Array();
for (i = 0; i < 10; i++) {
var x = document.forms["form1"]["countries"].value;
repeat.push(x);
}
document.write(repeat);
}
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" onclick="validateForm()" value="Click Me!">
It keeps on displaying that one country the user has entered 10 times, instead of letting user enter ten countries and then displaying then when clicking on submit.
This will do what you sketched out. I don't think it's a very good way of asking a user for 10 items, as there's no feedback as to how many they've entered, nor the ability to edit the items once entered, nor a way of clearing the list to enter 10 more. Also, this will never actually submit the list. But this meets the requirements as stated:
var repeat = [];
function validateForm() {
var countries = document.getElementById("countries");
if (repeat.length < 10) {
var x = countries.value;
repeat.push(x);
countries.value = "";
countries.focus();
}
if (repeat.length === 10) {
var hid = document.getElementById("list");
hid.value = repeat.join('|');
console.log(hid.value);
var ul = document.getElementById("display");
ul.innerHTML = "";
for (var i = 0; i < 10; i++) {
ul.innerHTML += `<li>${repeat[i]}</li>`;
}
document.getElementById("done").style.display = "block";
}
}
window.onload = function() {
document.getElementById("click").addEventListener("click", validateForm);
};
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" id="click" value="Click Me!">
<input type="hidden" id="list" name="listOfCountries">
</form>
<br>
<div id="done" style="display:none">
Countries entered:
<ul id="display"></ul>
</div>
Note that the hidden fields listOfCountries will contain the list of 10 countries, delimited by a pipe symbol "|". It's up to you to post that to a server.
You could use a global array for the countries and store until ten countries in the array.
function enterCountry() {
var input = document.getElementById('country');
if (input.value && countries.length < 10) {
countries.push(input.value);
input.value = '';
input.placeholder = 'insert ' + (10 - countries.length);
}
if (countries.length === 10) {
input.placeholder = 'ready';
document.getElementById('allCountries').innerHTML = countries.join(', ');
}
}
var countries = [];
<form id="form1">
Enter the countries:
<input type="text" id="country" placeholder="insert 10"><br><br>
<input type="button" onclick="enterCountry()" value="Click Me!">
</form>
<div id="allCountries"></div>
Hey you can get multiple input value on submit with jquery
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});

Trim HTML tags of a table cell with radio button and label combined

Javascript Function:
The function of my JS posted below is to loop through the column indexes defined in the 2nd parameter and at the same time loop also at the given element ids defined in the 3rd parameter. This will populated the textbox, radiobutton and dropdown fields based on the value of columns of the clicked row.
From the sample usage below, the value from column index 1 (price) will be shown in the price textbox when the table is clicked.
Sample Usage:
<table id="tblPrice" onclick="gettabledata('tblPrice', '0,1,2,3', 'PriceId,Price,strtDt,endDt')">
Problem:
The table's 2nd column (1st column is hidden) has a combination of radio button and label, and when the row is clicked the Price textbox has a value like this:
<input type="radio" name="rbDefaultPrice" class="radio" value=""> <label style="font-size: 1em" class="price" for="lblPriceRbtn">5</label>
I just need the value 5 to be shown in the Price textbox, so I need to trime the element tags being shown. All other cells with text only (no radiobutton) is copied correctly to their corresponding textboxes except for the cell that has a combination of radiobutton and label. The code responsible for this is:
document.getElementById(fieldId[i]).value = rowSelected.cells[colIndex[i]].innerHTML.trim();
The innerHTML.trim() only removes the whitespaces when I get the cell value.
JavaScript (Go to line with comment: Problem to see the code with issue):
function gettabledata(tableId, colIndexes, fieldIds) {
var table = document.getElementById(tableId); //Get table id to evaluate
var cells = table.getElementsByTagName('td'); //Get all table cells per column
//Get field Ids set in parameter
var fieldId = fieldIds.split(",");
var colIndex = colIndexes.split(",");
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
//Get column data on clicked row
cell.onclick = function () {
var rowId = this.parentNode.rowIndex;
var rowsNotSelected = table.getElementsByTagName('tr');
var rowSelected = table.getElementsByTagName('tr')[rowId]; //Get selected row
//Get number of items in array and loop (NOTE: colIndex is an array parameter defined in called javascript from View)
for (i = 0; i < fieldId.length; i++) {
var elmntTag = document.getElementById(fieldId[i]).tagName; //Get element tag name of each filedId item (SELECT, INPUT)
var elmntType = document.getElementById(fieldId[i]).getAttribute("type"); //Get element type of each filedId item (text, radio)
//Check field if dropdown or input (text or radio)
if (elmntTag == "INPUT") {
//Populate field depending on input type
if (elmntType == "text" || elmntType == "hidden") {
//PROBLEM
document.getElementById(fieldId[i]).value = rowSelected.cells[colIndex[i]].innerHTML.trim(); //Populate value of textbox id defined in the parameter
} else if (elmntType == "radio") {
//Populate value of radiobutton id defined in the parameter
var status = rowSelected.cells[colIndex[i]].innerHTML.trim();
var name = document.getElementById(fieldId[i]).getAttribute("name");
if (status == "Active") {
$('input[name=' + name + '][value="Active"]').prop('checked', true);
} else if (status == "Inactive") {
$('input[name=' + name + '][value="Inactive"]').prop('checked', true);
}
}
//Check field if dropdown or input (text or radio)
} else if (elmntTag == "SELECT") {
var dropdown = document.getElementById(fieldId[i]);
dropdown.value = rowSelected.cells[colIndex[i]].innerHTML.trim();
}
}
}
}
$('#btnUpdate').show();
$('#btnSave').hide();
}
HTML:
<table id="template" style="display:none;">
<tr>
<td class="hidden"></td>
<td>
<input type="radio" name="rbDefaultPrice" class="radio" />
<label style="font-size: 1em" class="price"></label>
</td>
<td class="startdate"></td>
<td class="enddate"></td>
</tr>
</table>
After checking several forums, I've come up with an answer:
I replaced my code from this:
document.getElementById(fieldId[i]).value = rowSelected.cells[colIndex[i]].innerHTML.trim();
To this:
document.getElementById(fieldId[i]).value = rowSelected.cells[colIndex[i]].textContent.trim();

Select Table Row and Insert Into Form Javascript

Im making a page that has a search function. I would like to be able to click the results in the table and have it insert the information into a form below it. For Example: a page for medical records where you would search by last name, it would populate the table with the customers info, and you can click one of the results in the table for it to fill in all the information into the form below the table.
I currently have the table pulling the results and entering the data into the form but i have to click a button before it will allow me to select anything in the table. I really dont want to have to press the button. Below is the Javascript code, and php. If you need more, I can provide it.
Javascript: I have think what requires the button to be pressed is the var row = td.parentNode line, because when its just taken away, the selecting functionality ceases.
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
populateFields(row);
}
PHP
echo '<input id="selectstyle" type="button" value="Select" onclick="test()"><br><table class="table-search" id="searchresulttable"><br>';
if(count($row)) {
$end_result = '';
echo "<tr><td><u>Last Name</u></td><td><u>First Name</u></td><td><u>Phone #</u></td><td><u>Address</u></td><td><u>License</u></td><td><u>Tax Exempt</u></td><td><u>Tax ID</u></td></tr>";
foreach($row as $r) {
$result = ucwords($r['bidlname']);
// we will use this to bold the search word in result
$bold = '<td>' . ucwords($r['bidlname']) . '</td>' . '<td>' . ucwords($r['bidfname']) . '</td><td>' . $r['bidphnum'] . '</td><td>' . $r['bidaddress'] . '</td><td>' . $r['bidlicense'] . '</td><td>' . $r['bidtaxexempt'] . '</td><td>' . $r['bidtaxid'] .'</td>';
$end_result .= '<tr>' . $bold . '</tr>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
echo '</table><br>';
I would like to be able to just click the entry i want to insert, without having to click the button first. Thoughts or ideas?
If I understood correctly your question my answer is the following snippet:
var ishigh;
function populateFields(row) {
// get the form elements
var frmElements = document.getElementById('frm');
// for each cell in current row
for(var i=0; i< row.cells.length; i++) {
// copy the cell value to the input value
frmElements[i].value = row.cells[i].textContent;
}
}
// when document is ready
window.addEventListener("DOMContentLoaded", function(event) {
// associate the click handler for the table
document.getElementById('searchresulttable').onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement;
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
// populate the form with the content of current row
populateFields(row);
}
});
function test() {
// do nothing.....
}
.highlighted {
background-color: #ffff99;
}
<input id="selectstyle" type="button" value="Select" onclick="test()"><br>
<table class="table-search" id="searchresulttable"><br>
<tr>
<td><u>Last Name</u></td>
<td><u>First Name</u></td>
<td><u>Phone #</u></td>
<td><u>Address</u></td>
<td><u>License</u></td>
<td><u>Tax Exempt</u></td>
<td><u>Tax ID</u></td>
</tr>
<tr>
<td>1bidlname</td>
<td>1bidfname</td>
<td>1bidphnum</td>
<td>1bidaddress</td>
<td>1bidlicense</td>
<td>1bidtaxexempt</td>
<td>1bidtaxid</td>
</tr>
<tr>
<td>2bidlname</td>
<td>2bidfname</td>
<td>2bidphnum</td>
<td>2bidaddress</td>
<td>2bidlicense</td>
<td>2bidtaxexempt</td>
<td>2bidtaxid</td>
</tr>
<tr>
<td>3bidlname</td>
<td>3bidfname</td>
<td>3bidphnum</td>
<td>3bidaddress</td>
<td>3bidlicense</td>
<td>3bidtaxexempt</td>
<td>3bidtaxid</td>
</tr>
</table>
<br>
<form id="frm">
Last Name:<br>
<input type="text" name="lastname"><br>
First Name:<br>
<input type="text" name="firstname"><br>
Phone #:<br>
<input type="text" name="phonenumber"><br>
Address:<br>
<input type="text" name="address"><br>
License:<br>
<input type="text" name="license"><br>
Tax Exempt:<br>
<input type="text" name="taxexempt"><br>
Tax Id:<br>
<input type="text" name="taxid"><br>
</form>
I haven't 50 rep yet so I'll have to sort of hack my approach here...
Are you using regular js or are you running a library like jQuery or underscore?
Is this specifically for touch-enabled devices or not (its okay to have both but this info would help)
My recommendation is that you use any JS library that can do batch click assignment here.
Maybe add a button to the row to trigger the action or even adjust your PHP to add properties to an and in JS preventDefault on the event then take the data from off it.
something like...
<a class="click_here_for_population" data-fisrt-name="FirstName" data-last-name="LastName" data-anything-else="foo">Add to form</a>
then...
$('click_here_for_population').click(function(e){
e.preventDefault();
// do the population stuff from $(this) or pass $(this) to the function
})
This way the event target holds the data you need without having to navigate parents/siblings.

Skip field if empty

I have 4 fields that can be filled in by end user. I would like to send the contents of these in an email but I don't want blank spaces in the email. What I am looking for is a way to ignore those empty field and only return those that have value. I have this piece of code but it only ever returns the last value :
var Textbox = Browser.getValue("myTextBox");
var Field1 = Browser.getValue("myField1");
var Field2 = Browser.getValue("myField2");
var Field3 = Browser.getValue("myField3");
var Field4 = Browser.getValue("myField4));
if (Field1 != "" ){
Browser.setValue(TextBox), (Field1 += "\n" + Textbox));
}
if (Field2 != ""){
Browser.setValue(Textbox), (Field2 += "\n" + Textbox));
}
if (Field3 != ""){
Browser.setValue(Textbox), (Field3 += "\n" + Textbox));
}
if (Field4 != ""){
Browser.setValue(Textbox), (Field4 += "\n" + Textbox));
}
Can anyone help me? I basically need that the Textbox after each statement in updated and used in the next using just Javascript.
Thank you in advance
You seem to be trying to do something like the following. It goes over all the controls in the form and gets all the values that aren't the initial value and writes them to the textarea on new lines.
<script>
// Collect all the non–default values in the form and write
// on new lines to the text area
function consolidateValues(form) {
// Get the textarea to write values to
var textArea = form.myTextBox;
// Get all controls in the form
var control, controls = form.elements;
// Variable to hold the consolidated value
var text = [];
// Collect all the values, skipping the first control
for (var i=1, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.value != control.defaultValue) {
text.push(control.value);
}
}
// write the value to the text area
textArea.value = text.join('\n');
// Stop form from submitting
return false;
}
</script>
<form onsubmit="return consolidateValues(this)">
<textarea name="myTextBox" size="100" rows="10"></textarea>
<br>
<input name="myField1">
<br>
<input name="myField2">
<br>
<input name="myField3">
<br>
<input name="myField4">
<br>
<input type="submit"> <input type="reset">
</form>

Form using javascript make field required?

I have a form that uses a javascript file items.js to add new items. So each time form.php is used and the 'add items' buttons is clicked then the new row of fields show to add details.
So for example some of the code is the following to add field item name.
newCell = newRow.insertCell(3);
newCell.innerHTML = '<input class="item_text_area item_name" type="text" name="0_item_' + new_item + '" id="0_item_' + new_items + '" size="20" maxlength="250" />';
How can I edit this .js file to make the Item name field required?
Any help would be appreciated.
Per Jeevan: As you cannot be sure how many items the user submits, I would choose for an approach where all new items have unique class, say dynamicAddedItems.
As Jeevan already said, you can add the following to the form tag to prevent it from submitting if it returns false.
<form onsubmit="return validate();"></form>
With javascript:
function validate(){
var elems = document.getElementsByClassName( 'dynamicAddedItems' );
var allgood = true;
//Loop through all elements with this class
for( var i = 0; i < elems.length; i++ ) {
if( !elems[i].value || !elems[i].value.length ) {
elems[i].className += " error";
allgood = false;
} else {
elems[i].className = "item_text_area item_name dynamicAddedItems";
}
}
//If any element did not meet the requirements, prevent it from being submitted and display an alert
if( !allgood ) {
alert( "Please fill in all the required fields." );
return false;
}
//Otherwise submit the form
return true;
}
This script will add the error class if a field is empty and prevent the form from being submitted. It's up to you how you want to display a field with such a class.
You can use jquery for this. Add a class, in this case 'requiredAttr' to the required fields and then validate on form submit.
<form onsubmit="return validate();">
First Name*: <input class="requiredAttr" type="text" /><br/>
Last Name: <input type="text" /><br/>
<input type="submit" />
</form>
function validate(){
$(".requiredAttr").each(function(){
if($(this).val().length < 1){
alert("please fill in all the required fields.");
$(this).focus();
return false;
}
else{
return true;
}
});
return false;
}
Here is a working fiddle. It also brings the focus on the first un-filled field after the validation alert:
http://jsfiddle.net/YG6mk/2/

Categories

Resources