jquery append and remove dynamic table row errors - javascript

I have an issue with my jquery code. It is designed to append new table row when the ajouter button is clicked.
It works well except that it adds rows depending on the number of rows already present. If there are five rows on the table and you click the add button it will add five empty rows instead of one and I don't know where the error is coming from.
This is the code:
<?php
echo '<td>'
. '<input type="button" class="deleteButton" value="Supp."/> '
. '<a href="javascript:void(0);" >'
. '<input type="button" class="addCF" value="Ajouter"/>'
. '</a>'
. '</td>';
echo'</tr>';
?>
<script>
$(document).ready(function () {
$(".addCF").click(function () {
$("#demoajax").append('<tr><td><input type="text" name="brice2[]" value="" placeholder="Ref" /> </td><td><input type="text" name="brice[]" value="" placeholder="Label" /></td><td><input type="text" name="mytext[]" value="" placeholder="Quantite en besoin" /></td><td><input type="text" name="brice51[]" value="" placeholder="Unite" /></td><td><input type="text" name="brice52[]" value="" placeholder="Fabrication Utile" /></td><td> <input type="button" value="Supp"/></td></tr>');
});
$("#demoajax").on('click', '.remCF', function () {
$(this).parent().parent().remove();
});
});
</script>

Related

JQuery autocomplete() works only in first row of table

Autocomplete jQuery UI only works the first row of table.
I'm working on a pharmacy search engine form with the Autocomplete jQuery UI on Bootstrap, the problem is that the autocomplete only works the first row. When i click add button it create a new row but in new row it do not work.
My jQuery syntax is as:
$("#itemSearch").autocomplete({
source: "{{ route('autoCompSearch') }}",
minLength:3,
select: function(key, value){
console.log(key, value);
},
});
My addRow() is as following;
$('#journalRows').on('keydown', '#addRow',function(event){
// alert('you are here...');
count++;
dynamic_field(count);
return true;
}
and my dynamic_filed(count) function is as;
function dynamic_field(number)
{
// New Function to add New Row in Journal
var html = '';
html += '<tr class="options" name="line_items">'
html += '<td width="5%"><input type="text" id="checkbox. $user->id ." name="id[]" class="form-control" value="" disabled=""></td>'
html += '<td width="15%"><input type="text" name="barcode_id[]" id="barcodeSearch" class="form-control"></td>'
html += '<td width="30%"><input type="text" name="item_id[]" id="itemSearch" class="form-control select-product"></td>'
html += '<td width="5%"><input type="text" name="qty[]" value="1" class="form-control calc" onkeyup="InvoiceCalculation()"></td>'
html += '<td width="10%"><input type="text" id="sal_price" value="1" name="sal_price[]" class="form-control calc" onkeyup="InvoiceCalculation()"></td>'
html += '<td width="5%"><input type="text" name="discPer[]" class="form-control" value="0" placeholder="Discount percentage..." onkeyup="InvoiceCalculation()"></td>'
html += '<td width="15%"><input type="text" id="totUnitAmount" name="totUnitAmount[]" class="form-control form-control-sm" value="0"></td>'
html += '<td><input type="button" id="addRow" name="addRow[]" class="form-control btn btn-success" value="+"></td>'
html += '<td><input type="button" id="removeRow" name="removeRow[]" class="form-control btn btn-danger" value="-"></td>';
html += '</tr>';
$('#journalRows').append(html);
};
This is works but only autocomplete option is not working in second and onward rows.....
For new row you need to change the Id of the autocomplete field. Each autocomplete field should have a unique id:
$("#itemSearch").autocomplete({
source: "{{ route('autoCompSearch') }}",
minLength:3,
select: function(key, value){
console.log(key, value);
},
});
$("#itemSearch1").autocomplete({
source: "{{ route('autoCompSearch') }}",
minLength:3,
select: function(key, value){
console.log(key, value);
},
});
Also you need to initialise autocomplete module on the field after it's created, otherwise it won't be in the DOM and jQuery won't work for the field
UPDATE:
change your dynamic_field function as follows:
function dynamic_field(number)
{
// New Function to add New Row in Journal
var html = '';
html += '<tr class="options" name="line_items">'
html += '<td width="5%"><input type="text" id="checkbox. $user->id ." name="id[]" class="form-control" value="" disabled=""></td>'
html += '<td width="15%"><input type="text" name="barcode_id[]" id="barcodeSearch" class="form-control"></td>'
html += '<td width="30%"><input type="text" name="item_id[]" id="itemSearch-'+number+'" class="form-control select-product"></td>'
html += '<td width="5%"><input type="text" name="qty[]" value="1" class="form-control calc" onkeyup="InvoiceCalculation()"></td>'
html += '<td width="10%"><input type="text" id="sal_price" value="1" name="sal_price[]" class="form-control calc" onkeyup="InvoiceCalculation()"></td>'
html += '<td width="5%"><input type="text" name="discPer[]" class="form-control" value="0" placeholder="Discount percentage..." onkeyup="InvoiceCalculation()"></td>'
html += '<td width="15%"><input type="text" id="totUnitAmount" name="totUnitAmount[]" class="form-control form-control-sm" value="0"></td>'
html += '<td><input type="button" id="addRow" name="addRow[]" class="form-control btn btn-success" value="+"></td>'
html += '<td><input type="button" id="removeRow" name="removeRow[]" class="form-control btn btn-danger" value="-"></td>';
html += '</tr>';
$('#journalRows').append(html);
$("#itemSearch-"+number).autocomplete({
source: "{{ route('autoCompSearch') }}",
minLength:3,
select: function(key, value){
console.log(key, value);
},
});
};

How to insert a PHP code which has HTML tag inside the Javascript

I want to add a PHP script which has HTML tags, inside a javascript. Below you can see the code I tried. But It's not working and stating that there is an error
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 11;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td><select class="form-control select2" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%">'+
<?php foreach ($productData as $product) { echo "<option value='" . $product->product_id . "'>" . $product->product_name . "</option>"; }?>+
'</select> </td><td><input class="form-control" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td>
<td><input class="form-control" name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td>
<td align="center"><button class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';
$('#data').append(strToAdd);
});
$('#remove').on("click", function(){
$('#data tr:last').remove();
})
});
//]]>
</script>
This is the error I get:
You need to put an extra ' after echo " otherwise you do not get the desired javascript string like '<option... >' but you get an <option... > which means nothing in a js code.
echo "'<option value='" . $product->product_id . "'>'"

Input Clear Button for Textareas

Updating what has worked and the current issue:
I have 1 clear button beside each field. Each clear button works. The problem is after clearing both fields, when selecting another file from the dropdown, it only populates the text field with the file name and does not display the contents in the second textarea until refreshing the page.
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div><font color=#2F6054>Below is the list of your saved codes. To view or delete your codes, select it from the list.</font></font></div><p>
<select size="1" name="CodeList" id="CodeList">
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo "<option>" . $file . "</option>";
}
}
?>
</select><p>
<font color=#2F6054><font size=4>Enter Codes Here</font></font>
<form method="post" action="/evo/avsaveprocess.php">
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<table width="100%">
<tr>
<td>Description:</td>
<td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
<td><button type="reset" class="clear-tn" value="Clear"></button></td>
</tr>
<tr>
<td valign="top">Code:</td>
<td>
<textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Save" />
function code:
<script>
$(function(){
$('.clear-btn').on('click',function(e){
e.preventDefault();
$(this).closest('tr').find('input[type="text"],textarea').val('');
});
});
</script>
Edited to show current working code
Editing to show on change script at the bottom of my form for the dropdown
<script>
$(document).ready(function(){
// apply a change event
$('#CodeList').change(function() {
// update input box with the currently selected value
$('#CodeName').val($(this).val());
$.get( '<? echo $directory ?>' + '/' + $('#CodeName').val(), function( data ) {
$( "#CodeValue" ).val( data );
});
});
});
</script>
You can try the below link, it works without javascript or jquery. Just simple HTML
<form>
<input type="reset" />
<input type="submit" />
<input type="text" />
<textarea></textarea>
</form>
Here is the demo
Change type attribute "button" to "reset".
<button type="reset" class="clear-btn">Clear</button>
Try below working fiddle as per your requirement.
http://fiddle.jshell.net/t7gkr8rk/1/

Make Wish List Dynamic for each item/ article

HI i got a little Problem i have whish list script which adds artivcles from shop into a session and saves them but when i click on the which list he only adds the first item how to male it dynamic that every wish list click is for the individual item in the shop
my article structure, onclick of wlbutton1 or wlbutton2 he should add the article with id1 or 2 to the wishlist:
echo '<div class="span3 filter--'.$obj->product_prop1.'" data-price="'.substr($obj->price, 0, -3) . '" data-popularity="3" data-size="s|m|xl" data-color="pink|orange" data-brand="'.$obj->product_brand.'">';
echo '<div class="product">';
echo '<div class="product-img featured">';
echo '<form method="post" action="../cart_update.php">';
echo '<div class="picture"><img src="images/'.$obj->product_img_name.'">';
echo '<div class="img-overlay"><button class="add_to_cart btn more btn-primary">Kaufen</button>...mehr</div>';
echo '</div>';
echo '</div>';
echo '<div id="result"></div>';
echo '<div class="main-titles"><h4 class="title">'.$currency.$obj->price.'</h4>';
echo '<h5 class="no-margin isotope--title" id="product'.$obj->id.'">'.$obj->product_name.'</h5>';
echo '<p class="no-margin pacifico" style="position: absolute;right: 10px;top: 5px; text-transform: capitalize;">'.$obj->product_brand.'</p>';
echo '<p class="no-margin" style="position: absolute;right: 10px;top: 25px;"><a class="wl-button'.$obj->id.'"><i class="icon-gift"></i></a></p>';
echo '</div>';
echo '<p class="desc">'.substr($obj->product_desc, 0, 160) . '...</p>';
echo '<input type="hidden" name="product_qty" value="1" />';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
echo '</div>';
My Jquery Code how to make it dynamic and individual for eacht artivle?:
$(".wl-button").click(function() {
var wlproduct = $('#product').text();
var wlproducturl = $('#producturl').attr('href');
$.ajax({
type : "POST",
url : "../assets/wlscript.php",
data : { wlproduct : wlproduct, wlproducturl : wlproducturl },
success : function(data) {
$('div#result').text('You added '+wlproducturl+' '+wlproduct+'\'s to your wishlist.');
}
});
});
Here an example of how you can do to find the data you need to add your article.
First the HTML example :
<div class="products">
<form>
<p>
<!-- Fist article -->
<span>Article 1</span>
<!-- A name construct so that I can easilly find in which iteration of the loop I am -->
<input type="hidden" name="article[0].id" value="1" />
<input type="hidden" name="article[0].name" value="article1" />
<button class="addButton">Add article</button>
</p>
<p>
<!-- Second article -->
<span>Article 2</span>
<input type="hidden" name="article[1].id" value="2" />
<input type="hidden" name="article[1].name" value="article2" />
<button class="addButton">Add article</button>
</p>
<!-- … others articles -->
</form>
</div>
And the Javascript part :
$(document).ready(function(){
$(".addButton").on("click", function(event){
event.preventDefault();
var button = $(this);
var parent = button.parent(); // We need to find the container in which to seach our fields.
var idArticle = parent.find("input[name$='.id']").val(); // Find the ID
var nameArticle = parent.find("input[name$='.name']").val(); // Find ather data
alert("Add article with id = " + idArticle + " and name = " + nameArticle);
// Next step is the ajax method to call the server with the correct data.
});
});
By working like that, you can then send to your server the data you need to add an article to your wishlist.
Here the link to the JS Fiddle example.
In this example, you can see how to work around the HTML content from the button to find the inputs.
You can find more about "tree traversal" with the jQuery API.

Find the Quantity, Unit Price and Total Cost Shopping Cart

Hello I am having some difficulty with my shopping cart script. So far I have it so you can update how many quantities of the item you want and it also updates the price as well. I want it so that once you click a button that says "Add To Cart" it sends you to a page that displays your order and tells you the Quantity, Unit Price and Total Cost of it.
Below is the code I have so far.
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#Quantity").keypress(function(event) {
return /\d/.test(String.fromCharCode(event.keyCode));
});
$("#Quantity").change(function(event) {
$(this).val(Math.abs($(this).val()));
UpdatePrice();
});
$("#CartForm").submit(function(event) {
if(!isNormalInteger($("#Quantity").val()))
{
event.preventDefault();
alert("Sorry, you must select at least one of these DVD's!");
return false
}
});
UpdatePrice();
});
function UpdatePrice() {
var AdjustedPrice = parseFloat($("#BaseUnitPrice").val())*parseInt($("#Quantity").val());
$("#AdjustedPrice").html(AdjustedPrice.toFixed(2) + $("#Currency").val());
}
function ChangeQuantity(Value) {
var NewQuantity = parseInt($("#Quantity").val()) + parseInt(Value);
if(NewQuantity < 1) NewQuantity = 1;
$("#Quantity").val(NewQuantity);
UpdatePrice();
}
function isNormalInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
</script>
HTML/PHP:
echo'<div class="right"><img alt="Picture" src="dvdcovers/wolverine.jpg" height="100" width="100" /></div>';
echo'<font color="white">';
echo'<br />';
echo'<b>Title:</b> The Wolverine';
echo'<br />';
echo'<b>Quantity:</b> $Quantity;';
echo'<br />';
echo'<b>Unit Price:</b>';
echo'<br />';
echo'<b>Total Cost:</b>';
echo'</font>';
echo'<br /><br />';
echo'<h3 class="widget-title">Purchasing And Payment</h3>';
echo'<form action="cart.php" method="post" id="CartForm">';
echo'<b>Unit Price: </b><div id="AdjustedPrice"></div>';
echo'<br />';
echo'<input type="hidden" id="Currency" value=" AUD" />';
echo'<input type="hidden" id="BaseUnitPrice" name="UnitPrice" value="29.99" />';
echo'<input type="hidden" name="ProductCode" value="000" />';
echo'<br />';
echo'<input type="text" id="Quantity" name="Quantity" value="1" />';
echo'<input type="button" value="-" onclick="ChangeQuantity(-1);" />';
echo'<input type="button" value="+" onclick="ChangeQuantity(1);" />';
echo'<br />';
echo'<input type="Submit" value="Buy" />';
echo'</form>';
Basically I would like to know how to get the value of quantity, unit price and total cost to a new php page that displays these details. Any help would be great. Thankyou.
Have you tried storing variables in a session after you submit the form?
/*
Cart.php
*/
// start session
session_start();
// store session data
$_SESSION['Quantity'] = $_POST['Quantity'];
$_SESSION['UnitPrice'] = $_POST['UnitPrice'];
$_SESSION['TotalCost'] = $_SESSION['UnitPrice'] * $_SESSION['Quantity'];
echo "<br>Quantity => " .'$'. $_SESSION['Quantity'];
echo "<br>UnitPrice => " .'$'. $_SESSION['UnitPrice'];
echo "<br>TotalCost => " .'$'. $_SESSION['TotalCost'];

Categories