How to save multiple form data using jquery ajax in laravel? - javascript

I am a bit confused with this. How to save multiple row data in laravel using ajax? The idea is to add products and when click on submit button I want to save the table data in database. I am getting an error as invalid argument supplied for foreach in my controller.
This is my blade template with script.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Products Invoice</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row" id="invoice-data">
<div class="col-md-12">
<table class="table table-bordered" id="main_table">
<thead>
<tr>
<th scope="col">Product Name</th>
<th scope="col">Description</th>
<th scope="col">Price</th>
<th scope="col">Qty</th>
{{--<th scope="col">Discount</th>--}}
<th scope="col">Amount</th>
<th scope="col">
<button class="btn btn-success addRow">Add More</button>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="product_name[]" class="form-control productname" id="row_0">
<option>Select Product</option>
#foreach($products as $product)
<option name="product_name[]" value="{{$product->id}}">{{$product->name}}</option>
#endforeach
</select>
</td>
<td><input type="text" name="description[]" class="form-control description" readonly></td>
<td><input type="text" id="price" name="price[]" class="form-control price"
onkeyup="rateChange($(this));" readonly></td>
<td><input type="text" name="qty[]" class="form-control qty" onkeyup="qtyChange($(this));"
onkeypress='return onlynumbers(event);'></td>
{{--<td><input type="text" name="dis[]" class="form-control dis"></td>--}}
<td><input type="text" name="amount[]" id="amount" class="form-control amount" readonly></td>
<td><a class="btn btn-danger remove">X</a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<label for="discount"><b>SubTotal</b></label>
<input type="text" name="subTotal[]" id="subTotal" class="subTotal">
</div>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<label for="discount"><b>Discount <span>%</span></b></label>
<input type="text" name="discount[]" id="discount" class="discount" onkeyup="amount_discount();"
onkeypress='return onlynumbers(event);'>
</div>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<label for="SubTotal"><b>Total</b></label>
<input type="text" name="total[]" id="total" class="total" readonly>
</div>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<button type="button" id="saveInvoice" name="saveInvoice" class="btn btn-success float-right">Submit</button>
</div>
</div>
</div>
</div>
</body>
<script>
$("#saveInvoice").click(function () {
$.ajax({
url: "{{ route('invoice.store') }}",
method: "POST",
data: $("#invoice-data").serialize(),
dataType: "json",
success: function (data) {
console.log(data);
}
});
});
</script>
</html>
And this is my controller to store the data.
public function store(Request $request)
{
$invoices = [];
foreach ($request->input('product_name') as $key => $value) {
$invoices["product_name.{$key}"] = 'required';
$invoices["description.{$key}"] = 'required';
$invoices["price.{$key}"] = 'required';
$invoices["qty.{$key}"] = 'required';
$invoices["amount.{$key}"] = 'required';
$invoices["subTotal.{$key}"] = 'required';
$invoices["discount.{$key}"] = 'required';
$invoices["total.{$key}"] = 'required';
}
$validator = Validator::make($request->all(), $invoices);
if ($validator->passes()) {
foreach ($request->input("product_name") as $key => $value) {
$invoice = new Invoice;
$invoice->product_name = $request->get("product_name")[$key];
$invoice->description = $request->get("description")[$key];
$invoice->price = $request->get("price")[$key];
$invoice->qty = $request->get("qty")[$key];
$invoice->amount = $request->get("amount")[$key];
$invoice->subTotal = $request->get("subTotal")[$key];
$invoice->discount = $request->get("discount")[$key];
$invoice->total = $request->get("total")[$key];
$invoice->save();
}
}
}
It returns me 500 internal server error.

I think you need to print the "$request->input('product_name')" before foreach loop to check product name is coming is an array or not? because error you are getting is " invalid argument supplied for foreach in my controller". Just write print_r($request->input('product_name')) and check value is coming is an array or not?

Related

JavaScript: drop down on select "other" the input field next to it will enable

My dropdown works when I only have 1 row of input fields, but when I click "add" to append new row of input fields it does not work now.
I want the new row that I append to enable "Please specify" whenever I choose "other"
note: that "Sick leave" is a drop down.
<table id="main_table" class="table">
<thead>
<tr>
<td class="border">No.</td>
<td class="border">Name</td>
<td class="border">Request Type</td>
<td class="border">Add. Information / Comment</td>
<td class="border">action</td>
</tr>
</thead>
<tbody>
<tr>
<td class="border"><center><span id="itemNum" style="font-size: 23px;">0</span></center></td>
<td><input type="text" name="" class="form-control" name="requestFor" placeholder="Teacher's name" id="floatingTextarea1"></td>
<td>
<div class="row">
<div class="col">
<select name="requestType" onclick="checkRequestType()" id="requestType" class="form-control" required>
<option value="Sick leave">Sick leave</option>
<option >Other</option>
</select>
</div>
<div class="col">
<input type="text" name="requestType" id="OtherType" value="" id="school" class="form-control" disabled placeholder="Please Specify">
</div>
</div>
</td>
<td>
<input type="text" name="" class="form-control" name="description" placeholder="Leave additional information/comment here" id="floatingTextarea2">
</td>
<td>
<button type="button" name="remove" id="remove" class="btn btn-danger"><i class="bi bi-x-lg"></i></button>
</td>
</tr>
</tbody>
</table>
<button class="btn btn-success" type="button" name="add" id="add">ADD</button>
here is the javascript i used to append or add new row to the table.
<script type="text/javascript">
//---------------------------------//
//script to add new input fields---//
//---------------------------------//
$(document).ready(function(){
var html = '<tr><td class="border"><center><span id="itemNum" style="font-size: 23px;">0</span></center></td><td><input type="text" name="" class="form-control" name="requestFor" placeholder="Teacher\'s name" id="floatingTextarea1"></td><td><div class="row"><div class="col"><select name="requestType" onclick="checkRequestType()" id="requestType" class="form-control" required><option value="Sick leave">Sick leave</option><option value="Sick leave">Sick leave</option><option value="Sick leave">Sick leave</option><option value="Sick leave">Sick leave</option><option >Other</option></select></div><div class="col"><input type="text" name="requestType" id="OtherType" value="" id="school" class="form-control" disabled placeholder="Please Specify"></div></div></td><td><input type="text" name="" class="form-control" name="description" placeholder="Leave additional information/comment here" id="floatingTextarea2"></td><td><button type="button" name="remove" id="remove" class="btn btn-danger"><i class="bi bi-x-lg"></i></button></td></tr>';
var x = 1;
var num = 1;
$('#add').click(function(){
if(true) {
$("#main_table").append(html);
x++;
}
});
$('#main_table').on('click','#remove',function(){
$(this).closest('tr').remove();
x--;
});
});
</script>
here is the javascript I used to check If the tropdown contains "other" to enable the input field next to it.
<script type="text/javascript">
function checkRequestType(){
if(document.getElementById("requestType").value == "Other"){
document.getElementById("OtherType").disabled = false;
console.log("true");
}else{
document.getElementById("OtherType").disabled = true;
console.log("false");
}
}
</script>
<script src="https://code.jquery.com/jquery-3.6.0.js" ></script>
you can use this code i have test this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<table id="main_table" class="table">
<thead>
<tr>
<td class="border">No.</td>
<td class="border">Name</td>
<td class="border">Request Type</td>
<td class="border">Add. Information / Comment</td>
<td class="border">action</td>
</tr>
</thead>
<tbody>
<tr>
<td class="border">
<center><span id="itemNum" style="font-size: 23px;">0</span></center>
</td>
<td><input type="text" name="" class="form-control" name="requestFor" placeholder="Teacher's name"
id="floatingTextarea1"></td>
<td>
<div class="row">
<div class="col">
<select name="requestType" id="requestType" class="form-control request_type" required>
<option value="Sick leave">Sick leave</option>
<option>Other</option>
</select>
</div>
<div class="col">
<input type="text" name="requestType" id="OtherType" value="" id="school" class="form-control" disabled="disabled"
placeholder="Please Specify">
</div>
</div>
</td>
<td>
<input type="text" name="" class="form-control" name="description"
placeholder="Leave additional information/comment here" id="floatingTextarea2">
</td>
<td>
<button type="button" name="remove" id="remove" class="btn btn-danger"><i class="bi bi-x-lg"></i></button>
</td>
</tr>
</tbody>
</table>
<button class="btn btn-success" type="button" name="add" id="add">ADD</button>
<script type="text/javascript">
//---------------------------------//
//script to add new input fields---//
//---------------------------------//
$(document).ready(function () {
var html = '<tr><td class="border"><center><span id="itemNum" style="font-size: 23px;">0</span></center></td><td><input type="text" name="" class="form-control" name="requestFor" placeholder="Teacher\'s name" id="floatingTextarea1"></td><td><div class="row"><div class="col"><select name="requestType" id="requestType" class="form-control request_type" required><option value="Sick leave">Sick leave</option><option value="Sick leave">Sick leave</option><option value="Sick leave">Sick leave</option><option value="Sick leave">Sick leave</option><option >Other</option></select></div><div class="col"><input type="text" name="requestType" id="OtherType" value="" id="school" class="form-control" disabled placeholder="Please Specify"></div></div></td><td><input type="text" name="" class="form-control" name="description" placeholder="Leave additional information/comment here" id="floatingTextarea2"></td><td><button type="button" name="remove" id="remove" class="btn btn-danger"><i class="bi bi-x-lg"></i></button></td></tr>';
var x = 1;
var num = 1;
$('#add').click(function () {
if (true) {
$("#main_table").append(html);
x++;
}
});
$('#main_table').on('click', '#remove', function () {
$(this).closest('tr').remove();
x--;
});
$('body').on('change', '.request_type',function() {
var element = $(this);
var target = element.parent().parent().next().children();
console.log(target)
if (element.val() == "Other") {
console.log(element.parent().parent().find('#OtherType'))
// target.prop("disabled", false);
element.parent().parent().find('#OtherType').removeAttr("disabled")
} else {
target.attr('disabled', true);
}
})
});
</script>
</body>
</html>
your function will not work because you have tried to get elements by id that will pick only the first occurrence of element.
so you can use "this" and "closest" like this
function checkRequestType(e){
var element = e;
var target = element.parentElement.nextSibling.firstChild;
if(element.value == "Other"){
target.disabled = true;
}else{
target.disabled = false;
}
}
add this function like this
<select onchange="checkRequestType(this)">

Unable to load the array data into table on web page

I am trying to dynamically load data into a table on web page using Javascript. Here is the code I've tried:
class UI{
static displayBooks(){
const storedBooks =[
{
title : 'matrix',
author : 'john doe',
isbn : '45565'
},
{
title : 'book-two',
author : 'john toe',
isbn : '45566'
}
];
const books = storedBooks;
books.forEach((book) => UI.addBookToList(book));
}
static addBookToList(book){
const list = document.getElementById('book-list');
const row = document.createElement('tr');
row.innerHTML =`
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.isbn}</td>
<td><a href="#" class="btn btn-danger btn-sm" delete>x</td>`;
list.appendChild.row;
}
}
// Display Books
document.addEventListener('DOMContentLoaded',UI.displayBooks);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://bootswatch.com/5/yeti/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
<title>My Book List</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
<i class="fa-solid fa-book-open text-primary"></i>
My<span class="text-primary">Book</span>List
</h1>
<form id="book-form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" class="form-control">
</div>
<div class="form-group">
<label for="author">Author</label>
<input type="text" id="author" class="form-control">
</div>
<div class="form-group">
<label for="isbn">ISBN#</label>
<input type="text" id="isbn" class="form-control">
</div>
<input type="submit" value="Add Book" class="btn btn-primary w-100 mt-3">
</form>
<table class="table table-striped mt-5">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Author</th>
<th scope="col">ISBN#</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="book-list"></tbody>
</table>
</div>
<script src="main.js"></script>
</body>
</html>
If you run the above code you can see the data is not loaded into the HTML table. The expected output is:
I am not able to get the rows of arrays which I have entered. I am not able to understand what is wrong with the code. Can anyone help me out on how to console the arrays which have been stored in the storedBooks variable.
Your code seems to be almost correct for what you are trying to do. However, in the very last line of your function there's list.appendChild.row;, you are trying to access an undefined property row of appendChild, but the method Node.appendChild() needs to take a child node as an argument.
In your case it should be:
list.appendChild(row);

Ajax not working on multiple inserts - CI

I want to save multiple data in one go using codeigniter and then on success load the data on my datatable wihtout refreshing the whole page. I am able to do this successfully if I use modal and insert a single value but when I try to save multiple values, it doesn't work. I produce my input boxes on button click. Below are my codes:
CONTROLLER
public function add_multiple_orders(){
$dataset=[];
$item_name=$this->input->post('m_item_name');
$quantity=$this->input->post('m_quantity');
$amount=$this->input->post('m_amount');
$order_comment=$this->input->post('m_order_comment');
$branch_name=$this->input->post('m_branch_name');
$date_added=$this->input->post('m_date_added');
for($i=0;$i<sizeof($item_name);$i++){
$dataset[$i]=array(
'date_added'=>$date_added,
'item_name'=>$item_name[$i],
'quantity'=>$quantity[$i],
'amount'=>$amount[$i],
'ordered_by'=>$this->session->userdata['username'],
'order_status'=>'ordered',
'order_comment'=>$order_comment[$i],
'branch_name'=>$branch_name
);
}
$result=$this->sales_model->insert_mult_orders($dataset);
}
VIEW
<a name="mult_page">
<button class="btn btn-info" data-toggle="collapse" data-target="#add_multiple" style="margin-left: 20px;">Add Multiple Orders</button>
<div class="collapse" id="add_multiple" style="width: 95%; margin: 0 auto; margin-top: 10px;">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body">
<form class="form_mult_ordrs form-inline" method="post">
<div class="form-group">
<label for="m_date_added">Date</label>
<input type="date" name="m_date_added" required>
</div>
<div class="form-group">
<label for="m_branch_name" class="control-label">Branch Name</label>
<select name="m_branch_name" class="form-control">
<option value="superdome">Superdome</option>';
<option value="seaside">Sea Side</option>
<option value="robinsons">Robinsons</option>
</select>
</div>
<div class="btn btn-warning pull-right" onclick="add_new_row()">Add more</div>
<hr>
<div style="font-weight: bold;">Total Php <input type="text" id="total_result" placeholder="0.00" class="form-control"></div>
<br>
<table id="mult_ord_tbl" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th class="ui-help-center">Item Name</th>
<th class="ui-help-center">Quantity</th>
<th class="ui-help-center">Amount</th>
<th class="ui-help-center">Comment</th>
<th class="ui-help-center">Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="item_name[]" class="form-control">
<?php foreach($items as $item){
echo '<option value"='.$item->item_name.'">'.$item->item_name.'</option>';
} ?>
</select>
</td>
<td><input type="text" name="m_quantity[]" placeholder="Quantity"></td>
<td><input type="text" name="m_amount[]" id='m_amount[]' placeholder="Amount" onblur="total_values()"></td>
<td><input type="text" name="m_order_comment[]" placeholder="Commment"></td>
<td>
<button class="btn btn-danger" onclick="delete_row(this)"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
</tbody>
</table>
<tr>
<td colspan="12">
<button id="btn_mult_ordrs" class="btn btn-success" onclick="save_mult_ordrs()" value="">Submit All</button>
</td>
</tr>
</form>
</div> <!-- end of panel body -->
<div class="panel-footer">
footer
</div>
</div> <!-- end of panel primary -->
</div> <!-- end of column 12 -->
</div> <!-- end of row -->
</div> <!-- end of collapse -->
<script type="text/javascript">
$(document).ready(function(){
$('#table_id').DataTable({
"order":[[0,"desc"]]
});
});
function save_mult_ordrs(){
if(confirm("Are you done?")){
var url="<?php echo site_url('sales/add_multiple_orders')?>";
add_new_row();
// $("#form_mult_ordrs").submit();
$.ajax({
url:url,
type:"POST",
data:$('#form_mult_ordrs').serialize(),
datatype:"JSON",
success:function(data)
{
alert('All data has been saved.');
location.reload();
},
error:function(jqXHR, textStatus, errorThrown){
alert('Error in saving.');
}
});
}
}
function add_new_row(){
var arrTables = document.getElementById('mult_ord_tbl');
var oRows = arrTables.rows;
var numRows = oRows.length;
var newRow = document.getElementById('mult_ord_tbl').insertRow( numRows );
var cell1=newRow.insertCell(0);
var cell2=newRow.insertCell(1);
var cell3=newRow.insertCell(2);
var cell4=newRow.insertCell(3);
var cell5=newRow.insertCell(4);
cell1.innerHTML = "<tr><td><select name='m_item_name[]' class='form-control'>" +
<?php
foreach($items as $item){
echo ('"<option value=\"'.$item->item_name.'\">'.$item->item_name.'</option>"+');
}
?>
+ "</select></td>";
cell2.innerHTML="<td height='5'><input type='text' name='m_quantity[]' placeholder='Quantity'></td>";
cell3.innerHTML="<td height='5'><input type='text' name='m_amount[]' placeholder='Amount' onblur='total_values()'></td>"
cell4.innerHTML="<td height='5'><input type='text' name='m_order_comment[]' placeholder='Comment'></td>";
cell5.innerHTML="<td><button class='btn btn-danger' onclick='delete_row(this)''><i class='glyphicon glyphicon-remove'></i></button></td></tr>";
}
</script>
MODEL
public function insert_mult_orders($data){
$this->db->insert_batch('piercapitan.sls_ordrs',$data);
return $this->db->affected_rows();
}
Your help is immensely appreciated.
Never mind guys. I found what's wrong. It's my form id! I somehow placed the name on the class and not on the id.
<form class="form_mult_ordrs form-inline" method="post">
It should have been:
<form id="form_mult_ordrs" class="form-inline" method="post">

How to add text to a span element in a for loop using JavaScript?

I'm trying to validate a form with an array and a loop. I created empty span elements in each required field. Then, in JavaScript I set up this:
var name = document.querySelector('#Name').value,
firstLastName = document.querySelector('#firstLastName').value,
secondLastName = document.querySelector('#secondLastName').value,
username = document.querySelector('#username').value,
dateBirth = document.querySelector('#dateBirth').value,
email = document.querySelector('#email').value,
gender = document.querySelector('#gender').value,
password = document.querySelector('#password ').value,
passwordConfirmation = document.querySelector('#passwordConfirmation').value,
span = document.getElementsByTagName("span"),
personalData = [name, firstLastName, secondLastName, username, dateBirth, email, gender, password, passwordConfirmation],
arrayLength = personalData.length;
for (var i = 0; i < arrayLength; i++) {
if (personalData[i]== '') {
var message = '*Required'
span[i].innerHTML = message; /* THIS PART IS NOT WORKING */
}else {
var message = ''
span[i].innerHTML = message; /* THIS PART IS NOT WORKING */
}
}
Any idea what the problem is? I'm new on this.
Here's the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Regsitrar</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body class="container-fluid">
<header class="row">
<img class="col-md-2" src="./img/cenfotec-logo.png" alt="Music Logo" width="167px" height="80px"/>
<h1 class="col-md-6">Welcome!</h1>
</header>
<section id="form" class="row">
<form class="col-md-6 col-md-offset-3" id="registrationForm" name="RegistrationForm">
<h2>Registration</h2>
<table>
<tr>
<td >
<input type="text" placeholder="Name" id="Name"> <br>
<span id="errorName" class="span"></span>
</td>
<td>
<input type="text" placeholder="Last Name" id="firstLastName">
<span id="errorFirstLastName" class="span"></span>
</td>
<td>
<input type="text" placeholder="Second Last Name" id="secondLastName">
<span id="errorSecondLastName" class="span"></span>
</td>
</tr>
<tr>
<td colspan="3">
<input type="text" placeholder="Username" id="username">
</td>
</tr>
<tr>
<td colspan="3">
<label for="dateBirth">Date of Birth: </label>
</td>
</tr>
<tr>
<td colspan="3">
<input type="date" id="dateBirth">
</td>
</tr>
<tr>
<td colspan="3">
<input type="email" placeholder="Email Address" id="email">
</td>
</tr>
<tr>
<td colspan="3">
<select id="gender">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</td>
</tr>
<tr>
<td colspan="3">
<input type="password" placeholder="Password" id="password">
</td>
</tr>
<tr>
<td colspan="3">
<input type="password" placeholder="Confirm Password" id="passwordConfirmation">
</td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="Create Account" id="btnRegistration">
</td>
</tr>
</table>
</form>
</section>
<script type="text/javascript" src="js/logicIU.js"></script>
</body>
</html>
It seems pretty wired to me that getElementsByTagName not working on span element.
For working code you can try this
<span class='.span'>Data1</span>
<span class='.span'>Data2</span>
var x = document.getElementsByClassName(".span");
x[1].innerHTML = 'works';
Here JsFiddle https://jsfiddle.net/s4cdLrcg/1/
If you are getting undefined error on span elements probably you loading script before the dom elements finishs its loading.
Try to Load your script at bottom of your html page then it will work.
You can look at the snippet below which confirms you don't have any issues with your script.
You should place the scripts after the html elements same as the below snippet.
Note: I have put the scripts inside the validate() function so that, when you type something and click the button, you can see the validation message removed.
But this snippet will work without the function as you did above.
<div>
<input type="text" id="Name" /> <span></span>
</div>
<div>
<input type="text" id="firstLastName" /> <span></span>
</div>
<div>
<input type="text" id="secondLastName" /> <span></span>
</div>
<div>
<input type="text" id="username" /> <span></span>
</div>
<input type="button" value="Validate" onclick="validate()" />
<script>
function validate() {
var name = document.querySelector('#Name').value,
firstLastName = document.querySelector('#firstLastName').value,
secondLastName = document.querySelector('#secondLastName').value,
username = document.querySelector('#username').value,
//dateBirth = document.querySelector('#dateBirth').value,
//email = document.querySelector('#email').value,
//gender = document.querySelector('#gender').value,
//password = document.querySelector('#password ').value,
//passwordConfirmation = document.querySelector('#passwordConfirmation').value,
span = document.getElementsByTagName("span"),
personalData = [name, firstLastName, secondLastName, username], //, dateBirth, email, gender, password, passwordConfirmation],
arrayLength = personalData.length;
for (var i = 0; i < arrayLength; i++) {
var message = '';
if (personalData[i] == '') {
message = '*Required';
}
span[i].innerHTML = message; /* THIS PART IS NOT WORKING */
}
}
validate();
</script>
You need to place your code inside function (i.e)
<input type="button" value="Validate" onclick="validate()" />
function validate(){
//Your code
}

Can't get the time picker to grey out the dates in the Past

I have a JSP Page where i want the time picker to grey out the past days and only show the dates from today to furture . i have tried the endDate option but it is not working .
Heres my jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Categories</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href='<c:url value="/static/css/header.css" />'>
<!-- <script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap-datepicker.de.js" charset="UTF-8"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/a549aa8780dbda16f6cff545aeabc3d71073911e/src/js/bootstrap-datetimepicker.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/a549aa8780dbda16f6cff545aeabc3d71073911e/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<style type="text/css">
table {
table-layout: fixed;
word-wrap: break-word;
}
th {
text-align:center;
}
#categorySelect {
text-align: center;
}
#categorySelect {
margin: auto;
width: 30%;
}
#123 {
margin: auto;
width: 50%;
}
p {
font:bold;
}
</style>
</head>
<body>
<jsp:include page="../shared/header.jsp">
<jsp:param value="editCategories" name="currentPage" />
</jsp:include>
<div class="row">
<div class="text-center">
<h2>Select Category</h2>
<div class="text-muted">
<h4>Choose a Category to Edit, Update and Schedule Changes</h4>
</div>
</div>
</div>
<div class="form-group" id="categorySelect">
<select class="form-control" id="categoryMenu">
<option value="" disabled selected>Select Category</option>
<c:forEach items="${category}" var="catitem">
<option>${catitem}</option>
</c:forEach>
</select>
</div>
<br></br>
<form class="form-horizontal" role="form" action="updateCategory" method=POST id="form1">
<div class="table-responsive">
<table class="table table-bordered table-striped table-highlight">
<tr>
<th style="width:15%" >Property</th>
<th style="width:40%">Present Value</th>
<th style="width:45%">Edited Value</th>
</tr>
<tr>
<td align="center"><strong>Id</strong></td>
<td><p class="text-danger" id="id1">Id</p></td>
<td><input type="text" class="form-control" id="id" name="id" placeholder="Enter Id" disabled></td>
</tr>
<tr>
<td align="center"><strong>Cat Key</strong></td>
<!-- <td><input type="text" class="form-control" id="catKey1" name="catKey1" placeholder="Enter CatKey" disabled></td> -->
<td><p class="text-danger" id="catKey1">Cat Key</p></td>
<td><input type="text" class="form-control" id="catKey" name="catKey" placeholder="Enter CatKey" disabled></td>
</tr>
<tr>
<td align="center"><strong>Name</strong></td>
<td><p class="text-danger" id="name1">Name</p></td>
<td><input type="text" class="form-control" id="name" name="name" placeholder="Enter Name"></td>
</tr>
<tr>
<td align="center"><strong>Icon</strong></td>
<td><p class="text-danger" id="icon1">Icon</p></td>
<td><input type="text" class="form-control" id="icon" name="icon" placeholder="Enter Icon"></td>
</tr>
<tr>
<td align="center"><strong>Icon White</strong></td>
<td><p class="text-danger" id="iconWhite1">Icon White</p></td>
<td><input type="text" class="form-control" id="iconWhite" name="iconWhite" placeholder="Enter IconWhite"></td>
</tr>
<tr>
<td align="center"><strong>Color</strong></td>
<td><p class="text-danger" id="color1">Color</p></td>
<td><input type="text" class="form-control" id="color" name="color" placeholder="Enter Color"></td>
</tr>
</table>
<p align="center"><strong>Success Messages Of Services Catering The Category</strong></p>
<table class="table table-bordered table-striped table-highlight" id="tab_logic">
<tbody>
<!-- <tr id='addr1'></tr> -->
</tbody>
</table>
<table class="table table-bordered table-striped table-highlight" id="tab_logic">
<tbody>
<tr>
<td> <div class="checkbox" style="text-align:center">
<label><input type="checkbox" value="schedule" id="schedule" name="schedule">Schedule</label>
</div>
</td></tr><tr>
<td align="center"><div class="form-group" style="width:30%">
<div class='input-group date' id='datetimepicker1' >
<input type='text' class="form-control" name="date" id="date"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<!-- <div class="checkbox" style="text-align:center">
<label><input type="checkbox" value="schedule" id="schedule">Schedule</label>
</div>
<div class="form-group" style="text-align:center;width:30%">
<div class='input-group date' id='datetimepicker1' style="text-align:center">
<input type='text' class="form-control" style="text-align:center"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div> -->
<table class="table table-bordered table-striped table-highlight">
<tr>
<td colspan="3" align="center">
<div class="form-group">
<button type="submit" class="btn btn-success btn-md" id="submit">Submit</button>
</div>
</td>
</tr>
</table>
</div>
</form>
<script type="text/javascript">
var t;
$(function() {
jQuery.validator.addMethod("validHex", function(value, element) {
//return str.match(/^#[a-f0-9]{6}$/i) !== null;
if ( value.match(/^#[a-f0-9]{6}$/i) !== null)
return true
else
return false;
});
$('#form1').validate({
rules: {
icon: {
required: true,
url:true
},
color : {
required:true,
validHex: true
}
},
messages: {
icon:{
required: "Can't be empty."
},
color:{
required: "Can't be empty.",
validHex: " Enter valid hex color"
}
}
});
var date = new Date();
var d = new Date();
d.setDate(date.getDate());
$("#datetimepicker1").datetimepicker({
defaultDate: new Date(),
format:'YYYY-MM-DD HH:mm',
endDate: d,
});
$("#categoryMenu").change(function() {
var category = $("#categoryMenu").val();
loadData(category);
loadPosm(t);
var y = $("#id1").text();
loadPosmData(y);
});
});
function loadPosm(num) {
$('#tab_logic').html("<tr id=addr1></tr>");
for (var i =1 ; i<=num ; i++)
{
$('#addr'+i).html("<td align='center' style='width:15%' id='pos"+i+"'><strong>"+ (i+1) +"</strong></td><td style='width:40%'><p class='text-danger' id='posm"+i+"'>"+i+"</p></td><td><input type='text' class='form-control' id='posmi"+i+"' name='posmi"+i+"' placeholder='Enter POSM'></td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
}
}
function loadPosmData(category_id) {
$.ajax({
type : "GET",
data : {
catId : category_id
},
dataType : 'json',
async : false ,
url : "printPosmDetails",
success : function(data) {
for(var i=1 ;i <=data.length ;i++) {
$("#pos"+i.toString()).html("<strong>"+data[i-1].name+"</strong>");
$("#posm"+i.toString()).html("<strong>"+data[i-1].message+"</strong>");
$("#posmi"+i.toString()).val(data[i-1].message);
}
},
error : function() {
alert("error");
}
});
}
function loadData(category) {
$.ajax({
type : "GET",
data : {
categor : category
},
dataType : 'json',
async : false ,
url : "printCategoryDetails",
success : function(data) {
$("#id1").html("<strong>"+ data.id + "</strong>");
// $("#id").val(data.id);
$("#id").attr('disabled','disabled');
// $("#catKey").val(data.catkey);
$("#catKey1").html("<strong>"+ data.catkey + "</strong>");
$("#catKey").attr('disabled','disabled');
$("#name").val(data.name);
$("#name1").html("<strong>"+ data.name + "</strong>");
$("#icon").val(data.icon);
$("#icon1").html("<strong>"+ data.icon + "</strong>");
$("#iconWhite1").html("<strong>"+ data.icon_white + "</strong>");
$("#iconWhite").val(data.icon_white);
$("#color1").html("<strong>"+ data.color+ "</strong>");
$("#color").val(data.color);
$('#123').html(data.posmNumber);
t=data.posmNumber;
},
error : function() {
alert("error");
}
});
}
</script>
</body>
</html>
Can anyone tell me as to why this is happening .
Add minDate: 0 in your datepicker initialisation code if you want to disable past dates.
$("#datetimepicker1").datetimepicker({
defaultDate: new Date(),
format:'YYYY-MM-DD HH:mm',
endDate: d,
minDate: 0
});

Categories