Uncaught syntax error: invalid token while executing javascript snippet - javascript

i am trying to build dynamic input fields using javascript and codeigniter. while executing the snippet, there is an error of Uncaught SyntaxError: Invalid or unexpected token.
i have created table where i am fetching data from database. All of my tables data is is working fine with the javascript snipped except one where i have a drop down list.
This is my table where i am fetching data.
<td><input class="typeahead form-control" type="text" placeholder="Enter Parameter"></td>
<td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>
<td> <input type="quantity" class="form-control" id="quantity" placeholder="Enter Quantity"></td>
<td><input type="price" class="form-control" id="price" placeholder="Enter Price"></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
This is my javascript snippet where i am making the table dynamic to add more rows of the same input fields.
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"> <td><input class="typeahead form-control" type="text" placeholder="Enter Parameter"></td>\n\
<td> <input type="quantity" class="form-control" id="quantity" placeholder="Enter Quantity"></td>\n\
<td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>\n\
<td><input type="price" class="form-control" id="price" placeholder="Enter Price"></td>\n\
<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
My above javascript function works fine if i remove this line from the function
<td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>\n\
But if i add this line i get that described error.

Try this,
<td> <?php echo form_dropdown("id",$unit_name, "", "class="form-control"");?> </td>

Related

How to use laravel array into <script> code for loop(foreach)

I need to use laravel variables (foreach($attributes as $attribute)) into javascript code
I have dynamic input add or remove the page in laravel blade. visit: Dynamically Add or Remove input fields using JQuery
Now I want to use select and dropdown instead of simple input (name) but how to pass variables collection into script tag?
This is first static dropdown:
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<select class="form-control m-select2" id="m_select2_1" name="attribute[1]['name']">
<option value="value">name</option>
<option value="value2">name2</option>
<option value="value3">name3</option>
</select>
</td>
<td>
<input type="text" name="attribute[1]['price']" placeholder="Enter your Price" class="form-control name_list" />
</td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
and this is my code in script tag:
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="attribute['+i+'][\'name\']" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="attribute['+i+'][\'price\']" placeholder="Enter your Price" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
I want to create something like this instead of attribute[]['name'] in script tag:
<select class="form-control m-select2" id="m_select2_1" name="attribute[1]['name']">
#foreach($attributes as $attribute)
<option value="{{$attribute->id}}">{{$attribute->name}}</option>
#endforeach
</select>
You can use #json or {!! json_encode() !!} to assign it to a javascript variable in your .blade.php file.
<script>
let data = #json($attributes)
</script>
In JS file, data variable will have the array you want:
console.log(data);

AJAX - Post Table Rows and Individual Inputs

I have a project in Laravel that I am working on and one portion requires me to work with submitting a form through a modal, the problem is I'm not as familiar with AJAX as I'd like to be and I've run into an issue.
Here are the modal contents:
<table>
<tr>
<td>
{{ csrf_field() }}
<select name="payer_id" class="js-basic-single payer_id" style="width:100%;" id="payer_id">
<option></option>
#foreach($customers as $customer)
<option value="{{ $customer->id }}">{{ $customer->customer_name }}</option>
#endforeach
</select>
<div id="existing_biller_details" class="hidden" name="existing_biller_details" style="margin-top:10px;">
</div>
<select class="form-control deposit_type" name="deposit_type" id="deposit_type">
<option disabled selected>Please Select</option>
<option value="Check">Check</option>
<option value="Cash">Cash</option>
<option value="ECheck">ECheck</option>
</select>
<div name="check_number" id="check_number" class="hidden">
<input type="text" placeholder="Check Number" class="form-control" id="check_number" name="check_number">
</div>
<input type="text" class="form-control" placeholder="Payment Amount" name="payment_amount" id="payment_amount">
<input type="date" class="form-control" placeholder="Date of Deposit" name="date_deposit" id="date_deposit">
<textarea placeholder="Notes" style="width:100%;" class="form-control" id="notes" name="notes"></textarea>
</td><td style="width:50%;">
<table style="width:100%;" id="freight_bill_items">
<thead>
<td style="width:30%;font-weight:bold;text-align:center;">Bill No.</td><td style="width:30%; font-weight:bold; text-align:center;">Amount</td>
</thead>
<tbody>
<tr style="height:40px">
<td style="width:30%;text-align:center;"><input type="text" name="payment_details[shipment_id][]" required class="form-control name_list" id="shipment_id" placeholder="Bill No." required></td><td style="width:30%;text-align:center;"><input type="text" name="payment_details[amount][]" required class="form-control name_list" id="amount" placeholder="Amount" required>
</td><td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</tbody>
</table>
<div id="freight_bill_items_subtotal;" style="font-weight:bold; padding-top:10px; padding-bottom:10px; text-align:left; background-color: #f0f8ff;">
SUBTOTAL:
<input type="text" readonly name="freightBillSubtotal" id="freightBillSubtotal" class="form-control total_field" style="display:inline;" value="0.00">
</div>
</td>
</tr>
</table>
As you can see a little bit lower, there is a div called "freight_bill_items", with a table and in the only tbody row, the two text inputs and a button to add another table row with the same exact inputs.
Now here at the moment is my ajax script:
<script type="text/javascript">
$(document).on('click', '.createPayment', function() {
$('.modal-title').text('Record New Payment');
$('#payment').modal('show');
});
$('.modal-footer').on('click', '.add_payment', function() {
//START
var payment_details = [];
//END
$.ajax({
type:'POST',
url: '/payments/createNew',
data: {
payer_id: $('input[name=payer_id]').val(),
notes: $('input[name=notes]').val(),
payment_amount: $('input[name=payment_amount]').val(),
date_deposit: $('input[name=date_deposit]').val(),
check_number: $('input[name=check_number]').val(),
deposit_type: $('input[name=deposit_type]').val(),
payment_details:payment_details, //LOOKING FOR ASSISTANCE HERE//
_token: $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#payment').modal('show');
toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
toastr.success('Successfully recorded Payment!', 'Success Alert', {timeOut: 5000});
}
},
});
});
</script>
Now what I'm stuck on is how do I pass these rows and their input contents into arrays to POST along with the other values?
I would suggest that you remove id from inputs that are duplicated. Assign a class instead.The shipment id can be assigned as an attribute.
<input class="payment_details" shipment_id="{shipment_id}" value="" required>
function get_array(element){
// Inputs having mutliple fields(grouped by class) will be returned as an array
arr = [];
element.map(function(){
arr[$(this).attr('shipment_id')] = $(this).val();
});
return arr;
}
var payments = get_array($('.payment_details'));
You now have an array whose key is shipment_id and value is input value for the respective element. Pass this array in your AJAX.

Validation of a dynamic form that can add or remove fields

I have a form that can have fields added and deleted.
I built the form from a tutorial I found and it works perfectly except if you forget to complete one of the fields. the PHP checking works, ie my data base does not get filled with a load of blank values but to the user it looks as if it has all gone through.
I have been trying to validate my form with javascript and have tried a couple of ways but my knowledge of JS is limited and i am struggling.
This is the code that I've written so far:
function validateForm() {
if (document.getElementById$(this).attr("id").validity.valueMissing) {
alert("Please complete all of the fields");
}
}
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="date" name="date[]" id="date'+i+'" required /></td><td><textarea rows="6" cols="50" name="name[]" id="name'+i+'" placeholder="Enter the training session" required ></textarea></td><td><button type="button" name="remove" id="'+i+'" class="btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
method:"POST",
data:$('#add_name').serialize(),
success:function(data){
alert(data);
$('#add_name')[0].reset();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<form name="add_name" id="add_name" onsubmit="return validateForm()">
<div>
<table id="dynamic_field">
<tr>
<td><input type="date" name="date[]" id="date'+i+'" required /></td>
<td><textarea rows="6" cols="50" name="name[]" id="name'+i+'" placeholder="Enter the training session" required ></textarea></td>
<td><button type="button" name="add" id="add">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" value="Submit" />
</div>
</form>
</div>
Any suggestion would be very helpful with the form validation.
I made few changes so your code can catch if Date have been selected:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
<form name="add_name" id="add_name" onsubmit="return validateForm()">
<div>
<table id="dynamic_field">
<tr>
<td><input type="date" name="date[]" id="date0" required /></td>
<td><textarea rows="6" cols="50" name="name[]" id="name0" placeholder="Enter the training session" required ></textarea></td>
<td><button type="button" name="add" id="add">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" value="Submit" />
</div>
</form>
</div>
<script>
function validateForm() {
if (document.getElementById$(this).attr("id").validity.valueMissing) {
alert("Please complete all of the fields");
}
}
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row' + i + '"><td><input type="date" name="date[]" id="date'+i+'" required /></td><td><textarea rows="6" cols="50" name="name[]" id="name'+i+'" placeholder="Enter the training session" required ></textarea></td><td><button type="button" name="remove" id="'+i+'" class="btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
var isValid = true;
for(var c=0; c < i; c++)
{
if ($('#date'+c).val()=='')
{
alert('Please choose date') ;
$('#date'+c).css({'border' : '1px solid red'});
isValid = 0;
}
else
{ $('#date'+c).css({'border' : '1px solid black'}); }
} // end for
if(isValid) { doSave() }
});
});
function doSave() {
$.ajax({
method:"POST",
data:$('#add_name').serialize(),
success:function(data){
alert(data);
$('#add_name')[0].reset();
}
});
}
</script>

Dynamic Invoice Forms fields and posting to a database

I am building a form to create invoices. At the moment it has the form fields of:
Product Name, QTY.
I have a "add more" button which adds another row of the above form fields.
It then submits as an array to another php page. What i am having problems with is matching each associated form field with each other because when i save it in the database i need the correct Product Name, QTY to be on the same row in the table obviously. Just not sure how to match them.
Currently my code on the form field page is:
<html>
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
On the name.php page where the form submits to. What is the best way to get each product and associated qty from the array and put them into the database row. Keeping in mind this is dynamic.
On name.php when i print out $_POST i currently have this array structure:
Array
(
[product_name] => Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
)
[qty] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[submit] => Submit
)
Im guessing I need to count the keys and then match them in the other dimension of the array. Just not sure if that is the best way or even how to do that.
You could use this
$productName = $_POST['productName'];
$qty = $_POST['qty']
foreach($productName as $key => $productName) {
$productQty = $qty[$key];
//Use your ORM (or whatever) to inster into DB
//$productName and $productQty
}
EDIT
Or, even better, you could user PHP's array_combine:
$productName = $_POST['productName'];
$qty = $_POST['qty']
$arryWithTotals = array_combine($productName, $qty);
foreach($arrayWithTotals as $productName => $productQty) {
//insert into DB
}
If you wish you can use like these way.
<html>
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><?php
session_start();
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])) {
echo $_SESSION["message"];
unset($_SESSION["message"]);
}
?></td>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
PHP
====
$data = $_POST['product_name'];
$data2 = $_POST['qty'];
$product_name = "'" . implode("','", array_values($data)) . "'";
$qty = "'" . implode("','", array_values($data2)) . "'";
$conn = mysql_connect("localhost", "root", "") or die("unable to connect Mysql");
mysql_select_db("Your DB Name called here") or die("unable to connect DB");
$query = "INSERT INTO `Your DB Name called here`.`Your Table Name called here` (`id`, `product_name`,`qty` ) VALUES (NULL, '$product_name', '$qty')";
if (mysql_query($query)) {
$_SESSION["message"] = "Successfully submitted";
}
header("location:your page name.php");

I do have a form wherein if a user enters input it should check for negative or empty input box and throw an alert message

Here is my code below. I do have a form wherein consists of three dropdowns and input boxes.So I do want to check whether a field is blank or for negative numbers being entered?
//Dependant dropdown code
$("#item").change(function() {
var iname = $(this).val();
$.post("fetch_data.php",
{"iname": iname},
function (data) {
document.getElementById('new_select').innerHTML=data;
});
});
$('#submitBtn').click(function(){
var txt = $(".check").val();
if(parseInt(txt) < 0 || txt == -1){
alert("Enter positive values ..!!!!");
}else{
$('#sess').text($('#sesion').val());
$('#ite').text($('#item').val());
$('#new').text($('#new_select').val());
$('#qin').text($('#qtyin').val());
$('#qout').text($('#qtyout').val());
}
});
$('#submit').click(function(){
$.ajax({
type:"POST",
url:'profile.php',
data:{sesion:$("#sess").text(),iname:$("#ite").text(),price:$("#new").text(),category:$("#qin").text(),qty:$("#qout").text()},
success: function(data){
$("#confirm-submit").modal("hide");
$("#result").html("<div class='alert alert-warning'>Record Inserted Successfully</div>");
setTimeout(function(){
$("#result").fadeOut();
},5000);
window.location.reload();
}
});
});
});
<form method='post' name='ireg' class="form-inline" role="form" id="formfield" enctype="multipart/form-data" onsubmit="return validateForm();">
<table id="entry" class="table table-responsive">
<tr>
<td> <label for="sesion">Session</label></td>
<td><select id="sesion" name="sesion" class="form-control check">
<option>--Select--</option>
<option>Breakfast</option>
<option>Lunch</option>
<option>Dinner</option>
</select></td>
<td> <label for="item_name">Item Name</label></td>
<td><select name="iname" id="item" class="form-control check" style="width:180px;">
<option>Select Item</option>
<?php
include 'db.php';
$select = $conn->query("SELECT item_name from items");
while($row = mysqli_fetch_array($select, MYSQLI_ASSOC))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</td>
<td>
<label for="new_select">Price</label>
</td>
<td>
<select id="new_select" name="new_select" class="form-control check">
<option>Select Price</option>
</select>
</td>
<td>
<label for="qtyin">Qty(Dine In)</label>
</td>
<td>
<input type="number" id="qtyin" min="0" name="qtyin" class="check" placeholder="QTY Dine In" style="width:80px;"/>
</td>
<td>
<label for="qtyout">Qty(Parcel)</label>
</td>
<td>
<input type="number" id="qtyout" name="qtyout" min="0" class="check" placeholder="QTY Dine Out" style="width:80px;"/>
</td>
<td>
<!-- <button type="submit" name="submit" class="btn btn-primary">Submit</button> -->
<input type="button" name="submit" value="Submit" id="submitBtn" data-toggle="modal"
data-target="#confirm-submit" class="btn btn-success" />
</td>
</tr>
</table>
</form>
I am trying to take input from user where validation is needed and once it is validated goes to modal popup to confirm then submit process..
If HTML5 validation is supported, you do not need jQuery for validation.
<input type=number min=0 required placeholder='Enter a positive number'>
If you want a custom validation message, the following should do:
<input type=number min=0 required placeholder="Enter a positive number"
oninvalid="this.setCustomValidity('Enter User Name Here')"
oninput="setCustomValidity('')">
The :invalid psuedo class can be used to apply custom CSS to it.
This link contains some examples. For browser support see caniuse.
EDIT:
For dropdowns, you may use the required attribute.
<select required>
<option value="">None</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
</select>
Note that the first option has to be blank. For details on applying required to <select> see this question.

Categories

Resources