Can Javascript be written in .edge file? - javascript

I just started learning Adonis.js and I would like to know if it's possible to write Javascript in an .edge file? I've found this tutorial (here) on how to add table row dynamically and I want to implement this in my Adonis.js project. I've add the coding inside a <script> tag, yet there's nothing happen when I clicked the 'Add' button. Does anyone know how to work this out? Or even have another solution on this?
Thank you in advance for the help.
#layout('main')
#section('content')
Go back
<hr>
<h1>Create Club</h1>
<form action="/clubs/create" method="POST">
{{ csrfField() }}
<div class="form-group">
<label>Club Name</label>
<input type="text" name="clubName" class="form-control" value="{{ old('clubName', '') }}">
{{ elIf('<span class="text-danger">$self</span>', getErrorFor('clubName'), hasErrorFor('clubName')) }}
</div>
<div class="form-group">
<label>Club Description</label>
<textarea name="clubDesc" class="form-control">{{ old('clubDesc', '') }}</textarea>
{{ elIf('<span class="text-danger">$self</span>', getErrorFor('clubDesc'), hasErrorFor('clubDesc')) }}
</div>
<br>
<table class="table order-list">
<thead>
<tr>
<td>Name</td>
<td>Position</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="memberName" class="form-control"/>
</td>
<td>
<input type="text" name="position" class="form-control"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-sm btn-block" id="addrow" value="Add Member"/>
</td>
</tr>
</tfoot>
</table>
<button class="btn btn-primary" type="submit">Create!</button>
</form>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="memberName' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="position' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
</script>
#endsection

From the docs:
in order to write raw HTML, you must wrap it inside {{{ }}}
That suggests that you should be able to do*:
{{{
<script>
// .. JavaScript here
</script>
}}}
*There may be other - potentially better, ways. I've never used the templating engine before, but the above seems to accomplish what you are looking for.

Related

jQuery validation on dynamic table form not working on using blur

I am creating form dynamically which has n rows (coming from array having n elements). Form fields have two type of columns (text & number) which I have given different id.
Although JQuery validation is working but "validate parts button" is not responding correctly. From the code condition it should not be enabled in case text is not valid.
Thanks..!
<div class="container-sm">
<div class="col-md-12 text-center">
<input class="btn btn-outline-primary" type="button" onclick = "buildTagPartsTable()" id="partNum" style="height:40px; width:220px" value="Enter Form Details#">
</div>
</div>
<div class="container-sm">
<div class="row">
<form id = "partsQuantForm">
<div class="col-lg-12" style="width:700px;overflow:auto; max-height:400px;">
<div class="partsTagsForm">
<table class="table table-striped" id="validTagsParts" style="width:100%;">
<thead>
<tr>
<th>Valid Row</th>
<th>Part </th>
<th># </th>
<th>Part </th>
<th># </th>
</tr>
</thead>
<tbody id="tagsPartsTable"></tbody>
</table>
</div>
<div class="col-md-12 text-center">
<input class="btn btn-outline-primary" type="button" id="tagsParts" style="height:40px; width:220px" value="Validate Parts ">
</div>
</div>
</form>
</div>
</div>
<script>
function buildTagPartsTable(){
validTagsInfo = ['Row1', 'Row2', 'Row3', 'Row4', 'Row5'];
var table = "<table>";
for (let key in validTagsInfo) {
table += `<tr>
<td>${validTagsInfo[key]}</td>
<td><input type="text" class="form-control" id = "partInfo" name="partInfo[0]" style="width:5em" minlength="5" maxlength="5" ></td>
<td><input type="number" class="form-control" id = "partQuantInfo" name="partQuantInfo[0]" style="width:3em" minlength="1" maxlength="1"></td>
<td><input type="text" class="form-control" id = "partInfo" name="partInfo[1]" style="width:5em" minlength="5" maxlength="5"></td>
<td><input type="number" class="form-control" id = "partQuantInfo" name="partQuantInfo[1]" style="width:3em" minlength="1" maxlength="1"></td>
</tr>`;
}
table += "</table>";
document.getElementById("tagsPartsTable").innerHTML = table;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('input').on('blur', function() {
if ($("#partsQuantForm").valid()) {
$('#tagsParts').prop('disabled', false);
} else {
$('#tagsParts').prop('disabled', true);
}
});
jQuery("#partsQuantForm").validate({
rules: {
'partInfo[]': {
required: true,minlength: 5,maxlength: 5
},
'partQuantInfo[]': {
required: true,minlength: 2,maxlength: 2
}
}
});
});
</script>

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

Column cannot be null by using Auth

I'm inserting multiple data into the database. There is an error for my column report_by which is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'report_by' cannot be null (SQL: insert into 'complaints' ('defect_id', 'image', 'description', 'report_by') values (1, C:\wamp64\tmp\php8E2E.tmp, leak, ?)) Inside column report_by should be the id of the user by using Auth. It's to tell that the complaint made by which users.
users table
id
role
email
typable_id
typable_type
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Complaint;
use Illuminate\Http\Request;
class ComplaintController extends Controller
{
public function index()
{
return view('buyers.complaint');
}
public function create(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $request->image[$item],
'description' => $request->description[$item],
'report_by' => $request->user_id,
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
}
complaint.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>Make New Report</strong></h3>
</div>
<div class="panel-body">
<div>
<div class="panel">
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</form>
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
Here my javascript inside the blade
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += ' <td><input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}"><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += ' <td><input type="file" class="form-control-file" name="image[]"></td>';
html += ' <td><input type="text" class="form-control" name="description[]"></td>';
html += ' <td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop

Javascript, pass values to new added table row/cell

basically the objective of this request is to have a modal table that adds new table row/cells and pass the value of "var OBGyneID = $(this).attr("id"); " to first cell and value of "var billing_id = newID;" to second cell whenever new rows/cells is/are added. Seeking your help, thanks!
* MY MODAL*
<div id="myModal" class="modal fade card new-contact myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="card profile">
<div class="profile__img">
<img src="img/profile2.jpg" alt="">
</div>
<div class="profile__info">
<h3 style="text-transform:capitalize;" id="pxname" name="pxname"></h3>
<ul class="icon-list">
<li>LAST <p name="consdates" id="consdates"></p></li>
<li>Last visit: </li>
<li><i class="zmdi zmdi-twitter"></i> #mallinda-hollaway</li>
</ul>
</div>
</div>
<div>
<div class="table-responsive">
<table id="billingTable" class="table table-inverse table-sm table-hover table-condensed" style="font-size:120%">
<thead>
<th>OBDYID</th>
<th>CK</th>
<th>PROCEEDURE</th>
<th>AMOUNT</th>
</thead>
<tbody id="billing_body" style="text-transform:capitalize;">
<form method="get" id="insert_form">
<tr>
<td width="10%"><input type="text" style="width:100%;" id="OBGyneID" name="OBGyneID"></td>
<td width="10%"><input type="text" style="width:100%;" id="AssessMentEntryID" name="AssessMentEntryID"></td>
<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" id="ExamDesc" name="ExamDesc"></td>
<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" id="Price" name="Price"></td>
</tr>
</form>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
<input type="submit" id="addRow" value="add" name="add" class="btn btn-info" />
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
* MY JS to add new rows/cells*
$(document).ready(function () {
$("#addRow").click(function () {
$("#billingTable").append('<tr><td width="10%"><input type="text" style="width:100%;" id="OBGyneID" name="OBGyneID" ></td>'+
'<td width="10%"><input type="text" style="width:100%;" id="AssessMentEntryID" name="AssessMentEntryID"></td>'+
'<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" id="ExamDesc" name="ExamDesc"></td>'+
'<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" id="Price" name="Price"></td></tr>');
jQuery(".ExamDesc").autocomplete({
source: 'php/billingentry.php'
});
});
});
* Pass values to Modal * this will only pass value when modal pops-up but cant pass value whenever new rows/cells are added.
$(document).on('click', '.billing_data', function(){
var OBGyneID = $(this).attr("id");
var newID = new Date().getUTCMilliseconds();
var billing_id = newID;
$.ajax({
url:"php/billing_fetch.php",
method:"GET",
data:{OBGyneID: OBGyneID},
dataType:"json",
success:function(data){
$('#AssessMentEntryID').val(data.AssessMentEntryID);
$('#ExamDesc').val(data.ExamDesc);
$('#Price').val(data.Price);
$('#pxservice').val(data.pxservice);
$('#companyname').val(data.companyname);
$('#chiefcomplain').val(data.chiefcomplain);
document.getElementById("OBGyneID").value = OBGyneID;
document.getElementById("AssessMentEntryID").value = billing_id;
document.getElementById("pxname").innerHTML = (data.fname)+" "+(data.mi)+" "+(data.lname);
document.getElementById("consdates").innerHTML = (data.obgyneDate);
$('#myModal').modal('show');
}
});
});
whenever you are adding a new row HTML in billing table, you are using the same id for OBGyneID, AssessMentEntryID,ExamDesc and Price. And if you added two rows, DOM will not be able to work properly as there are multiple same ids out there. So I will suggest you to replace that with class and use class name to set values. Check below code:
$(document).ready(function () {
$("#addRow").click(function () {
$("#billingTable").append('<tr><td width="10%"><input type="text" style="width:100%;" class="OBGyneID" name="OBGyneID" ></td>'+
'<td width="10%"><input type="text" style="width:100%;" class="AssessMentEntryID" name="AssessMentEntryID"></td>'+
'<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" name="ExamDesc"></td>'+
'<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" name="Price"></td></tr>');
jQuery(".ExamDesc").autocomplete({
source: 'php/billingentry.php'
});
});
});
One you have added HTML code, then you can find out last row of billingTable and can set vales in that. Check below code:
$(document).on('click', '.billing_data', function(){
var OBGyneID = $(this).attr("id");
var newID = new Date().getUTCMilliseconds();
var billing_id = newID;
$.ajax({
url:"php/billing_fetch.php",
method:"GET",
data:{OBGyneID: OBGyneID},
dataType:"json",
success:function(data){
$("#billingTable").find(".AssessMentEntryID:last").val(data.AssessMentEntryID);
$("#billingTable").find(".ExamDesc:last").val(data.ExamDesc);
$("#Price").find(".Price:last").val(data.Price);
$("#billingTable").find(".consdates:last").html(data.obgyneDate);
//and so on
$('#myModal').modal('show');
}
});
});
Also, I would suggest you to use HTMl template tag for making clone for row. Appending HTML in JS is not a recommended way. Hope it helps you.

Javascript add / remove textbox

I have the below javascript and I cannot take the values from the textbox that code generates to the html
("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
return '<td><textarea name = "prodcut_name" type="text" value = " ' + value + '" class="form-control" /></td>' + '" /></td>'+ '<td><textarea name = "product_directions" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><button type="button" class="btn btn-danger remove">X</button></td>'
my html form that I need to take the values
<form action="{{action('ProductController#store', $id)}}" method="post">
<h5 class="text-center">Product</h5>
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<td>Product Name</td>
<td>Details</td>
<td>Remove</td>
</tr>
</thead>
<tbody id="TextBoxContainer" >
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"></i>+ Add </button></th>
</tr>
</tfoot>
</table>
</div>
</section>
This is how you add text area using pure javascript.
let textAreaDiv = document.getElementById("textAreaDiv");
addButton.onclick = addTextArea;
function addTextArea() {
let textArea = document.createElement("TEXTAREA");
textArea.value = "Nice to see you";
textAreaDiv.appendChild(textArea);
}
<button id="addButton">
Add text Area
</button>
<div id="textAreaDiv">
</div>
body
<form action="server.php" method="post">
<div id="fields"></div>
<button id="btnAdd">Add</button>
<input type="submit" value="Submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
(function() {
let fieldIndex = 0
$('#btnAdd').click(() => {
// Create every textarea with different name
let field = $('<textarea>', {
name: `field${fieldIndex++}`
})
$('#fields').append(field)
return false
})
})()
</script>
Get values on server side
server.php
<?php echo json_encode($_POST) ?>

Categories

Resources