Select from database with dynamic where condition - php

In this case, I made ​​a row with jquery additional mechanism to obtain the parameters that I will use in data search.
$(document).ready(function() {
DataProvide();
ManipulationHere();
$('table').delegate('input[type=text].onlyDate', 'focusin', function(event) {
$(this).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true,
yearRange: '1972:2020',
});
});
$('table').delegate('input[type=text].onlyMonth', 'focusin', function(event) {
$(this).monthpicker();
});
}); //Tutup Document Ready
function ManipulationHere(){
var count = 1;
$(".button").click(function(){
count += 1;
var $row = $('<tr>'
+ '<td>' + '</td>'
+ '<td>' + '<input id="data2_' + count + '" type="text" name="data2_' + count + '" class="data2" />' + '</td>'
+ '<td>' + '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden">'
+ 'Remove' + '</td>'
+ '</tr>').appendTo("#customFields");
var copyData = $("#data1_1").clone();
var repID = copyData.attr('id', 'data1_' + count + '');
var repName = copyData.attr('name', 'data1_' + count + '');
$row.find('td:first').append(repID)
var check = $row.find('td:first').html();
var get = $(check).attr('id')
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
count -= 1;
});
$("#customFields").on('change', '.tabelBaru', function() {
var validator = $("#signupForm").validate();
validator.resetForm();
var $this = $(this),
nilai = $this.val();
console.log(nilai);
if(nilai=='gender'){
$this.closest("tr").find(".data2").replaceWith(
'<select name="data2_' + count + '" class="data2">'
+ '<option value="man" selected >Man</option>'
+ '<option value="woman">Woman</option>'
+ '</select>'
)
}
else if(nilai=='religion'){
$this.closest("tr").find(".data2").replaceWith(
'<select name="data2[]" class="data2">'
+ '<option value="protestan" selected >Protestan</option>'
+ '<option value="khatolik">Khatolik</option>'
+ '<option value="islam">Islam</option>'
+ '<option value="budha">Budha</option>'
+ '<option value="hindu">Hindu</option>'
+ '</select>'
)
}
else if(nilai=='blood'){
$this.closest("tr").find(".data2").replaceWith(
'<select name="data2_' + count + '" class="data2">'
+ '<option value="gol_a" selected >A</option>'
+ '<option value="gol_b">B</option>'
+ '<option value="gol_ab">AB</option>'
+ '<option value="gol_o">O</option>'
+ '</select>'
)
}
else if(nilai=='birth_date'){
$this.closest("tr").find(".data2").replaceWith(
'<input type="text" id="data2_' + count + '" name="data2_' + count + '" value="" placeholder="Date Format" class="onlyDate"/>'
)
}
else if(nilai=='start_date'){
$this.closest("tr").find(".data2").replaceWith(
'<input type="text" id="data2_' + count + '" name="data2_' + count + '" value="" placeholder="Date Format" class="onlyDate"/>'
)
}
else if(nilai=='end_date'){
$this.closest("tr").find(".data2").replaceWith(
'<input type="text" id="data2_' + count + '" name="data2_' + count + '" value="" placeholder="Date Format" class="onlyDate"/>'
)
}
else if(nilai=='join_date'){
$this.closest("tr").find(".data2").replaceWith(
'<input type="text" id="data2_' + count + '" name="data2_' + count + '" value="" placeholder="Date Format" class="onlyDate"/>'
)
}
else if(nilai=='los_month'){
$this.closest("tr").find(".data2").replaceWith(
'<input type="text" id="data2_' + count + '" name="data2_' + count + '" value="" placeholder="Month Format" class="onlyMonth"/>'
)
}
else{
$this.closest("tr").find(".onlyDate").replaceWith(
'<input type="text" id="data2_' + count + '" name="data2_' + count + '" value="" class="data2"/>'
)
}
});
}
function DataProvide(){
selectValues = {
"pilih" : "-Pilih-",
"id" : "ID",
"emp_name" : "Employee Name",
"photo_path" : "Photo Path",
"emp_id" : "Employee ID",
"birth_place" : "Birth Place",
"birth_date" : "Birth Date",
"age" : "Age",
"gender" : "Gender",
"religion" : "Religion",
};
$.each(selectValues, function(key, value) {
$('#data1_1')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
The results of the above process, I have a line that will be used as a parameter.
For example, when a row is added :
I want to create query generated after the SAVE process is :
SELECT * from my_table_name WHERE id='123'
If I add one more line parameters with example :
I want to create query generated after the SAVE process is :
SELECT * from my_table_name WHERE id='123' and employee_name='Testing'
And if I want to add another parameter search by adding a third line :
I want to query is generated after clicking the button in the process is :
SELECT * from my_table_name WHERE id='123' and employee_name='Testing' and employee_id='111'
I have made ​​a function to try to read the data from the form POST results like this :
$Query = "SELECT * from my_table_name WHERE ....... << from looping"
foreach ($_POST['rows'] as $key => $count ){
$Data1 = $_POST['data1_'.$count];
$Data2 = $_POST['data2_'.$count];
echo $Data1." >> ".$Data2;
echo "<br>";
}
How do I get the data key and value from the POST results for later input into my query?

You are almost there, you just need to change your loop a little bit.
$query = "SELECT * from my_table_name WHERE ";
$first = true;
foreach ($_POST['rows'] as $key => $count ) {
$field = $_POST['data1_' . $count];
$value = $_POST['data2_' . $count];
if ($first) {
$query .= $field . " = '" . $value . "'";
$first = false;
} else {
$query .= " AND " . $field . " = '" . $value . "'";
}
}
Keep in mind, this will only work if you submit at least one item to be queried against.
This also assumes that what you get back from $field is the name of the field in the database.
As an additional exercise, I strongly suggest that you look to see if you database implementation can use prepared statements. They are significantly more secure.

Related

Couldn't Calculate Price and Qty on table using Php Ajax

I am creating a ecommerce site for my final year project.while I am creating a project I ran in to the problem with product shall be able add the card but when I view the card product shown which I added into the card.my problem is if the give qty it will auto calculation and display result on the total textbox.and final totel show display below. I attached image below what i tried so far. But couldn’t calculate the total and final total.
Display the Products
<script>
getProducts();
function getProducts() {
$.ajax({
type: 'GET',
url: 'all_cart.php',
dataType: 'JSON',
success: function(data) {
data.forEach(function(element) {
var id = element.id;
var product_name = element.product_name;
var price = element.price;
$('#mytable tbody').after
(
'<tr> ' +
'<td>' + id + '</td>' +
'<td>' + product_name + '</td>' +
'<td>' + price + '</td>' +
"<input type='hidden' name='price' value='" + price + "'>" +
'<td>' + "<input type = 'text' id='qty' name='qty'/>" + '</td>' +
'<td>' + "<input type = 'text' id='amount'/>" + '</td>' +
'</tr>');
});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
Auto calcaltion the price * qty
$(function() {
$("#price, #qty").on("keydown keyup click", qty);
function qty() {
var sum = (
Number($("#price").val()) * Number($("#qty").val())
);
$('#amount').val(sum);
console.log(sum);
}
});
You dont should append multiple elements with same ID in a page
Can you try
function getProducts() {
$.ajax({
...
$('#mytable tbody').after
(
'<tr> ' +
'<td>' + id + '</td>' +
'<td>' + product_name + '</td>' +
'<td>' + price + '</td>' +
"<input type='hidden' name='price' class='price' value='" + price + "'>" +
'<td>' + "<input type = 'text' class='qty' name='qty'/>" + '</td>' +
'<td>' + "<input type = 'text' class='amount'/>" + '</td>' +
'</tr>');
});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
$(function() {
$(".price, .qty").on("keydown keyup click", function () {
var price = $(this).parents('tr').find('.price');
var qty= $(this).parents('tr').find('.qty');
var sum = (
Number($(price).val()) * Number($(qty).val())
);
$(this).parents('tr').find('.amount').val(sum);
calculateAmount();
});
function calculateAmount() {
var total = 0;
$('.amount').each(function(e){
total += Number($(this).val());
});
$('#total-amount').text(total);
}
});
This is a demo: https://codepen.io/phuongnm153/pen/bymYOQ
When you get $("#price").val() and $("#qty").val() in jQuery but you have many $("#price") & $("#qty") duplicate. You should be run this in console.
I hope it's helpful for you

Make it pretty using php

object(stdClass)#1 (1) {
["return"]=>
string(43362) "[{"Searchstring":"?showitemlist=1&Keyword=blue&acctwebguid=12bad325-a118-4778-825a-cc7d5308e24f&orderby=ItemName%20DESC&requestguid=29E60B17-8601-4839-AD00-00DB0D45A2CB","Recordcount":15446},{"Maxretail":7.42000000,"Displayname":"","Suplitemno":"COA09B/K","Supplieritemid":"D7784D83-F63D-4219-BDB1-F7AE76F74CC8","Minretail":5.99000000,"Minqty":25,"Rushavailable":0,"Imagepath":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/medium/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597800","Imagepathsm":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/small/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597799","Prodtime":10,"Imagepathlg":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/large/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597800","Companyname":"Graphik Business Accessories","Displayno":"","Imagepathmd":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/medium/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597800","Shownopricing":0,"Itemname":"Zume Coaster Set"},{"Maxretail":50.38000000,"Displayname":"","Suplitemno":"7003-47","Supplieritemid":"F7374437-2DF5-4D4B-B654-32F7C7B8971E","Minretail":39.98000000,"Minqty":10,"Rushavailable":0,"Imagepath":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","addlImagesLarge":["images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_b_1.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_b_3.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_d.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_d_2.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_d_3.jpg?_=1438623370"],"Imagepathsm":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","Prodtime":5,"Imagepathlg":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","addlImagesSmall":["images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_b_1.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_b_3.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_d.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_d_2.jpg?_=1438623370","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_d_3.jpg?_=1438623371"],"Companyname":"Leed&apos;s / Leeds","Displayno":"","Imagepathmd":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","addlImagesMed":["images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_b_1.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_b_3.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_d.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_d_2.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_d_3.jpg?_=1438623370"],"Shownopricing":0,"Itemname":"Zoom® Audio Decibel Bluetooth Speaker"},.......
<script>
$(document).ready(function() {
var data = '[{"Maxretail":...,"Itemname":"Youth Chameleon T-Shirt"]';
var table = '<table><thead><th>First Name</th><th>Last Name</th><th>Image</th><th>More</th></thead><tbody>';
var obj = $.parseJSON(data);
$.each(obj, function() {
table += '<tr><td>' + this['Itemname'] + '</td><td>' + this['Supplieritemid'] + '</td><td><img src="https://cdn.distributorcentral.com/' + this['Imagepath'] + ' alt="' + this['Itemname'] + '" /></td><td><img src="https://cdn.distributorcentral.com/' + this['addlImagesSmall'] + ' alt="' + this['Itemname'] + '" />' + this['addlImagesSmall'] + '</td></tr>';
});
table += '</tbody></table>';
document.getElementById("datalist").innerHTML = table;
});

PHP-jQuery: Display a timer on each table row where end time is not set

I have a function that displays a countup timer but I've only been able to make it work for a single row. I'd like to make a timer appear on each row where the end time of the action has not yet been set.
This is the full code.
<script>
$('document').ready(function()
{
var uni_id = //value of id needed to query the database table;
$.ajax({
type : 'POST',
url : 'get_time.php',
dataType: 'json',
data : {uni_id: uni_id},
cache: false,
success : function(result)
{
for (var i = 0; i < result.length; i++){
var startDateTime = new Date(result[i].uni_start_time); //Not sure if it's wrong to add all returning values here but so far it works but only for a single row on the table.
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer;
var rec_id = result[i].rec_id;
function updateTimer() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var minutes = Math.floor(diff/(60));
diff = diff-(minutes*60);
var seconds = diff;
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
$("#on_going_"+rec_id).html(hours+':'+minutes+':'+seconds);
}
setInterval(updateTimer, 1000);
$('#uni_time_table tbody').append(
'<tr>'
+'<td class="center hidden" id="'+result[i].rec_id+'">' + result[i].rec_id + '</td>'
+'<td class="center">' + result[i].uni_id + '</td>'
+'<td>' + result[i].uni_name + '</td>'
+'<td>' + result[i].uni_loc + '</td>'
+'<td class="center">' + result[i].uni_date + '</span></td>'
+'<td class="center">' + result[i].uni_start_time + '</td>'
+(result[i].uni_end_time == null ?
'<td class="center"></td>' //this will always be empty if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_end_time + '</td>'
)
+(result[i].uni_end_time == null ?
'<td class="center" id="on_going_'+result[i].rec_id+'"></td>' //the timer will only be triggered here if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_total_time + '</td>' //this will display the total time as long as the uni_end_time is set.
)
+'</tr>');
}
}
});
});
</script>
So far, only the first entry in the table displays the timer. Every time I add another entry, that second entry just remains blank while the timer still works with the first entry.
How can I make the timer work for each row on the table?
EDIT: Sample Data from json
rec_id "1"
uni_date "2016-10-28"
uni_loc "Custom Location"
uni_id "2356"
uni_name "Custom Name"
uni_start_time "10/28/2016 09:04:28"
uni_end_time null
uni_total_time null // this shows null because end_time is empty which is when the timer should kick in.
Here is a solution for you with little modifications of your code:
var startStamp = [];
function updateTimer(result) {
var newDate = new Date();
var newStamp = newDate.getTime();
for (var j = 0; j < result.length; j++) {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp[j])/1000);
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var minutes = Math.floor(diff/(60));
diff = diff-(minutes*60);
var seconds = diff;
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
$("#on_going_"+result[j].rec_id).html(hours+':'+minutes+':'+seconds);
}
}
$('document').ready(function()
{
var uni_id = 1;//
$.ajax({
type : 'POST',
url : 'get_time.php',
dataType: 'json',
data : {uni_id: uni_id},
cache: false,
success : function(result) {
for (var i = 0; i < result.length; i++) {
var startDateTime = new Date(result[i].uni_start_time);
startStamp[i] = startDateTime.getTime();
$('#uni_time_table tbody').append(
'<tr>'
+ '<td class="center hidden" id="' + result[i].rec_id + '">' + result[i].rec_id + '</td>'
+ '<td class="center">' + result[i].uni_id + '</td>'
+ '<td>' + result[i].uni_name + '</td>'
+ '<td>' + result[i].uni_loc + '</td>'
+ '<td class="center">' + result[i].uni_date + '</span></td>'
+ '<td class="center">' + result[i].uni_start_time + '</td>'
+ (result[i].uni_end_time == null ?
'<td class="center"></td>' //this will always be empty if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_end_time + '</td>'
)
+ (result[i].uni_end_time == null ?
'<td class="center" id="on_going_' + result[i].rec_id + '"></td>' //the timer will only be triggered here if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_total_time + '</td>' //this will display the total time as long as the uni_end_time is set.
)
+ '</tr>');
}
setInterval((function () {
updateTimer(result);
}), 1000);
}
});
});

How to get data from input type text that created by jquery in php

in my program user can create by clicking on button (jquery). But php does not send data to another page.
jquery:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>ویژگی '+ counter + ' : </label>' +
'<input type="text" name="txt' + counter +
'" id="textbox' + counter + '" class="form-control" style="margin:5px">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
php :
$x = 1;
while ($x<11)
{
$name = 'txt' . $x ;
if(isset($_POST[$name]) && $_POST[$name]!='')
{
object::object_Insert($_POST[$name],$s);
}
$x++;
}

Validating array of inputs using javascript

I hav a rather large form it has 8 fields for entering books .
Now for user to add more books there is a button add more books ,on click of which a javascript function is called and 7 out of 8 fields are duplicated.
User can add maximum 6 books , and all the input fields created dynamically have their names as arrays . I am able to post them and store in a table , Now i want to validate them using javascript.
I have been tryng to do this since a week and am a new to Javascript . Please help me.
MY JAVASCRIPT CODE
function addInput(divName){
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit)
{
alert("You have reached the limit of adding " + counter + " inputs");
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML ="<table>"+ "<tr align='right'>" + "<td>"+ " Name of book" + (counter + 1) + " " +" : <input type='text' name='bname1[]' > "+"</td>" + "</tr>"+"<tr align='right'>"+ "<td>"+" Name of Authour"+(counter + 1)+" "+": <input type='text' name='aname1[]'>"+"</td>"+"</tr>"+"<tr align='right'>"+"<td>"+"Publisher"+(counter+1)+" "+": <input tyme='text' name='pub1[]'>"+"</td>"+"</tr>"+ "<tr align='right'>" +"<td>"+ "ISDN Number " + (counter + 1) +" "+ ": <input type='text' name='isdn1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" +"<td>"+ " Edition " + (counter + 1) + " "+": <input type='text' name='edi1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" + "<td>"+ "Price"+(counter + 1) +" "+ " :<input type='number' name='cost1[]'>"+"</td>"+"</tr>"+"<tr align='right'>" + "<td>"+ "Number of copies"+(counter + 1) +" "+ ": <input type='number' name ='num1[]'> "+"</td>" + "</tr>"+ "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter=counter+1;
}
}
there is divsion in the html form to which all this is added.
Please help !
thanx in advance ..
here is your solution. http://codebins.com/codes/home/4ldqpbq
HTML
<div id="testDiv">
</div>
<button onclick="addInput('testDiv')">
Add New Items
</button>
<button onclick="validate('testDiv')">
Validate
</button>
JavaScript
var counter = 0;
var limit = 6
function addInput(divName) {
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<table>" + "<tr align='right'>" + "<td>" + " Name of book" + (counter + 1) + " " + " : <input type='text' name='bname1[]' > " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Name of Authour" + (counter + 1) + " " + ": <input type='text' name='aname1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Publisher" + (counter + 1) + " " + ": <input tyme='text' name='pub1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "ISDN Number " + (counter + 1) + " " + ": <input type='text' name='isdn1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Edition " + (counter + 1) + " " + ": <input type='text' name='edi1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Price" + (counter + 1) + " " + " :<input type='number' name='cost1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Number of copies" + (counter + 1) + " " + ": <input type='number' name ='num1[]'> " + "</td>" + "</tr>" + "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter = counter + 1;
}
}
function validate(divName) {
var container = document.getElementById(divName).getElementsByTagName("input");
for (var len = container.length, i = 0; i < len; i++) {
// if only requried validation
if (container[i].value == "") {
container[i].style.borderColor = "red"
} else {
container[i].style.border = ""
}
//if you want saperate validation for each
switch (container[i].name) {
case "bname1[]":
//validate according to filed
break;
case "aname1[]":
//validate according to filed
break;
case "pub1[]":
//validate according to filed
break;
case "isdn1[]":
//validate according to filed
break;
case "edi1[]":
//validate according to filed
break;
case "cost1[]":
//validate according to filed
break;
case "num1[]":
//validate according to filed
break;
}
}
}
Couple of suggestions for you to consider:
1) consider grouping ALL the fields you want to duplicate inside a single div in your form.
Then when the user wants to add new item (book) all you will need to do will be copy the content of this div. This way you will maintain only one copy of field-set.
2) consider dynamic generic form validation too. You add the validation rules to your form field definition with extra attributes i.e. [<input ... validationRules="mandatory,minimumLength=10..." />] I think that you can achieve something similar with JQuery, but I personally prefer NOT to use large libraries to do small jobs.
3) consider giving your fields unique ids too.
use
var bname= document.getElementsByName('bname1[]');
var aname=document.getElementsByName('aname1[]'); .........
for(var i=0;i<bname.length;i++)
{
//Your validations
}
for(var i=0;i<aname.length;i++)
{
//Your validations
}.....
..
do this for all elements in your code..
Validation function example:
function validate_field(f) { // f is input element
var name = f.name; // or also f.getAttribute('name')
var value = f.value; // or also f.getAttribute('value'), but should be defined
var error_div = document.getElementById(name+'err');
//alert('name '+name+' value '+value);
if (name.indexOf('bname') == 0) { // if validate book name
if (value == '') { // e.g. book name should not be empty string?
error_div.innerHTML = 'book name cannot be empty!';
return false; // field is wrong
}
}
else if (name.indexOf('aname') == 0) { // if validate author name
if (value.length<2) {
error_div.innerHTML = 'author\'s name is too short!';
return false; // at least two characters long name? :)
}
}
else if (name.indexOf('pub') == 0) { // if validate publisher
if (value.length<2) {
error_div.innerHTML = 'publisher\'s name is too short!';
return false;
}
}
else if (name.indexOf('isdn') == 0) { // if validate ISDN Number
if (value == '') {
error_div.innerHTML = 'ISDN cannot be empty!';
return false;
}
}
else if (name.indexOf('edi') == 0) { // if validate Edition
if (value == '') {
error_div.innerHTML = 'edition cannot be empty!';
return false;
}
}
else if (name.indexOf('cost') == 0) { // if validate Price
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please write a price using digits!';
return false;
}
}
else if (name.indexOf('num') == 0) { // if validate Number of copies
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please number of copies via digits!';
return false;
}
}
error_div.innerHTML = 'ok';
return true; // field is ok
// you can also have a look at http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
}
Full working script here: pastebin.com/UkVP2uLb

Categories