Javascript add / remove textbox - javascript

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) ?>

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>

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.

Can Javascript be written in .edge file?

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.

Jquery clone function is appending twice

So i am trying to use Jquery clone function. My problem is the first clone is okay. Then then the next are always appending two times.
JS
var initpriceinquiry = function(){
$(document).on("click",".btn_addMore_unit",function () {
var cloned = $(".price_inquiry_source tbody ").html();
var oldL = $(".units").length;
cloned = cloned.replace(/\[\x\]/g,oldL);
$(cloned).insertBefore("#targetRow");
modSelect2("select[name='pi_product_id[]']","/admin/price_inquiry/get_ajax_input?type=product_id&custom_type",function(obj) {
$.ajax({url:"", type: "get", data:"get_unit=1&product_id="+obj.val(), success: function(data)
{
eval("var record = "+data+";");
obj.parent().next().html(record[0]);
obj.parent().next().next().html(record[1]);
obj.parent().next().next().next().html("<textarea name = 'remark' class = 'form-control'></textarea>");
} });
});
});
}
HTML
<table class = 'hidden price_inquiry_source'>
<tr class = 'units'>
<td >
<select name = 'pi_product_id[]' class = 'form-control unitcodes[x]' style="width:120px">
</select>
<br>
<a href='javascript:void(0)' style='' onclick="$(this).parent().parent().remove();" class=''><i class='fa fa-trash'></i></a>
</td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
{{-- To BE CLONED --}}
Cloned should be inserted here
<table class="table table-condensed table-hover" id = "tableData">
<thead>
<tr>
<th>UNIT CODE</th>
<th>DESCRIPTION</th>
<th>SELLING PRICE</th>
<th>REMARKS</th>
</tr>
</thead>
<tbody>
<tr id = 'targetRow'>
<td colspan="4"><button class="btn btn-link btn_addMore_unit"
href="javascript:void(0)" style="display: inline-block;"><i class="fa fa-
plus "></i> ADD UNIT</a></td>
</tr>
</tbody>
</table>
See Image Attached for my problem
Image
Any help would be appreciated thanks!
Try this
//add `add_field_button` to your clone button
<a class="add_field_button btn btn-xs btn-success">Click me</a>
// add this class `input_fields_wrap` to your input field div
<div class="input_fields_wrap">
<input type="text" class="form-control" name="" value="i will be clone">
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append("<div>"+
"<div class='form-group form-inline'>"+
"<label for=''>hello there</label>"+
"<input type='text' class='form-control' name='' value='i am cloned one'>"+
"</div>"+
"<a href='#' class='btn btn-danger btn-xs remove_field'>remove me</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<a class="add_field_button btn btn-xs btn-success">clone me</a>
<div class="col-md-4 input_fields_wrap">
<div class="form-group form-inline">
<label for="">sample input</label>
<input type="text" class="form-control" name="" value="i will be clone">
</div>
</div>
</div>
</div>

Deleted data still prompts as existed

I have 2 process for sending a data. 1st is from a table and 2nd is by textboxes. "table_select" is where I retrieve the data, and "attendee_table" is where I send the data temporarily before I save the process. On submit, it saves to database.
The problem is when I check for duplicate entries, it functions well. But when I delete one of the entries, it is still prompting that the entry is existed. NOTE: It is not yet saved in the database.
But when I save it to database, the removed entry is not included in the database. What does this mean?
Here is my Jquery/Javascript code:
attendees_id=0;
$(document).ready(function(){
// ADD ATTENDEES BY SEARCH
var addMem = [];
$("#add_button").click(function(){
$('#table_select input[type="checkbox"]:checked').each(function(){
var getRow = $(this).parents('tr');
var value = (getRow.find('td:eq(2)').html()); //names
var value1 = (getRow.find('td:eq(3)').html()); //specialty
var value3 = (getRow.find('td:eq(1)').html()); //prc
var index = $.inArray(value3, addMem);
if (index >= 0){
alert('exists');
$('input[type=checkbox]').prop('checked', false).uniform('refresh');
}
else {
$('#attendee_table tr:last').after('<tr><td></td><td><input type="text" class="form-control" name="prc[' + attendees_id + ']" id="prc" value="' + value3 + '" readonly></td><td><input type="text" class="form-control" value="' + value + '" id="names" name="name[' + attendees_id + ']" readonly></td><td><input type="text" class="form-control" value="' + value1 + '" id="specialties" name="specialty[' + attendees_id + ']" readonly></td><td><input type="button" class="btn btn-warning" name="delete_btn1[' + attendees_id + ']" id="delete_btn1" onclick="deleteMem(this)" value="Delete"></td></tr>');
addMem.push(value3,value,value1);
$("#mod_search").modal('hide');
attendees_id=attendees_id+1;
}
});
});
// ADD ATTENDEES BY ADD
var addNon = [];
$("#addRow").click(function (e) {
var val2 = $("#id_no").val();
var val = $("#attendee_name").val();
var val1 = $("#specialty").val();
var ind = $.inArray(val, addNon);
if (val == ""){
alert('Enter name of attendee.')
}
else if (val1 == ""){
alert('Enter specialty of attendee.')
}
else{
if (ind >= 0){
alert('exists');
$('#attendee_name').val('');
$('#specialty').val('');
}
else {
$('#attendee_table tr:last').after('<tr><td></td><td><input type="text" class="form-control" name="prc[' + attendees_id + ']" id="prc" value=""></td><td><input type="text" class="form-control" value="' + val + '" id="names" name="name['+ attendees_id +']" readonly></td><td><input type="text" class="form-control" value="' + val1 +'" id="specialties" name="specialty[' + attendees_id + ']" readonly></td><td><input type="button" class="btn btn-warning" name="delete_btn[' + attendees_id + ']" id="delete_btn" value="Delete" onclick="deleteNon(this)" ></td></tr>');
addNon.push(val,val1);
$('#attendee_name').val('');
$('#specialty').val('');
}
}
attendees_id=attendees_id+1;
});
});
//DELETE DATA FROM SEARCH
function deleteMem(t){
var row = t.parentNode.parentNode;
var yes = confirm('Are you sure?');
if (yes){
document.getElementById("attendee_table").deleteRow(row.rowIndex);
console.log(row);
}
else{
event.preventDefault();
}
}
//DELETE DATA FROM ADD
function deleteNon(t){
var row = t.parentNode.parentNode;
var yes = confirm('Are you sure?');
if (yes){
document.getElementById("attendee_table").deleteRow(row.rowIndex);
console.log(row);
}
else{
event.preventDefault();
}
}
This is my "table_select":
<table class="table table-hover table-managed" id="table_select">
<thead>
<tr>
<th>ID</th>
<th>PRC</th>
<th>Name</th>
<th>Speciality</th>
</tr>
</thead>
<tbody>
<?php
$sql_search="SELECT * FROM `personal_profile`";
$sql_run=mysql_query($sql_search);
while($m=mysql_fetch_array($sql_run))
{
?>
<tr>
<td><input type="checkbox" name="member_select[]" id="member_select" value="<?php #$m['id']; ?>"></td>
<td><?php echo #$m['prc_license_num']; ?></td>
<td id="names"><?php echo #$m['lastname'].', '.#$m['firstname'].' '.#$m['middlename'];?></td>
<td id="specialties"><?php echo #$m['speciality'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
"attendee_table":
<table class="table table-managed table-hover" id="attendee_table">
<thead>
<tr>
<th>No.</th>
<th>PRC</th>
<th>Name</th>
<th>Speciality</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sql_select="SELECT * FROM `event_attendees` WHERE `id`='".#$_REQUEST['member_select']."'";
$sql_run=mysql_query($sql_select);
while($row=mysql_fetch_array($sql_run))
{
?>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
//ADDING ATTENDEE BY TEXTBOX
<div class="row">
<div class="form-group">
<div class="col-md-2 col-md-offset-1">
<label class="control-label">Name</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" id="attendee_name" name="attendee_name" value="<?=#$_REQUEST['name']?>"/>
</div>
<div class="col-md-1">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#mod_search" id="search_btn" name="search_btn" style="visibility:hidden;" >Search</button>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-2 col-md-offset-1">
<label class="control-label">Specialty/Profession</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="specialty" id="specialty" value="<?=#$_REQUEST['speciality']?>" />
</div>
<div class="col-md-1">
<button type="button" class="btn btn-info" id="addRow" name="addRow" style="visibility:hidden;">Add</button>
</div>
</div>
</div>
Where/what did I missed? Please help. Thank you.

Categories

Resources