SO I have a div which displays information from arrays. With my ajax script I am increasing a value in an array and I want the whole div to change accordingly... I have already made these changes, but I dont know how to change the whole div? DO I use .attr or something else?
This is the twig:
{% for key, item in cart %}
{% if key == info.id %}
<div class="input-append">
<input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
<i class="icon-minus"></i>
<i class="icon-plus"></i>
<button class="btn btn-danger" type="button"><a href="{{ path('cart_remove', {'id': key}) }}"><i class="icon-remove icon-white"></i></button>
</div>
</td>
<td>{{ info.getQtyPrice(item)|number_format(2, '.', ',')}}</td>
<td>{{ info.getQtyDiscount(item)|number_format(2, '.', ',')}}</td>
<td>{{ info.getQtyTax(item)|number_format(2, '.', ',') }}</td>
<td>{{ info.getQtyFinal(item)|number_format(2, '.', ',') }}</td>
</tr>
{% endif %}
{% endfor %}
With Ajax I am increasing or decreasing the quantity(quantity is the variable item). When I increase or decrease the quantity I want the whole div to change accordingly. For example if the products quantity is 1 the price is 50, when I increase the quantity I want the price to change to 100. This is my script:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add/quantity',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$this.parent('.input-append').val(data.amount)
}
}
});
});
Right now the line: $this.parent('.input-append').val(data.amount) only changes the quantity in the input field.
How can I change the whole div with the prices?
Answer
Thank you for your help. this code did the trick: $('.table').load(" .table");
add a class to each td you want to update like this :
<td class="qtyprice">{{ info.getQtyPrice(item)|number_format(2, '.', ',')}}</td>
<td class="qtytax">{{ info.getQtyDiscount(item)|number_format(2, '.', ',')}}</td>
<td>{{ info.getQtyTax(item)|number_format(2, '.', ',') }}</td>
<td class="qtyfinal">{{ info.getQtyFinal(item)|number_format(2, '.', ',') }}</td>
and your Ajax you update those fields accordingly by selecting them by class :
success: function (data) {
if(data.success == false){
alert('error')
}else{
$this.closest('tr').find('.input-append').val(data.amount) ;
$this.closest('tr').find('.qtyprice').val(data.qtyprice) ;
$this.closest('tr').find('.qtytax').val(data.qtytax) ;
$this.closest('tr').find('.qtyfinal').val(data.qtyfinal) ;
}
}
your ajax response data needs to have all the prices on success.
Related
I have tried couple of ways to get icon to change on a button, that has been created with for loop on page load. Here is my element:
{% for i in data %}
<div class="accordion">
<div style="margin-left: -10px;">
<a href="#collapse{{ i }}", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse_{{ i }}">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">{{ i }}</label>
</a>
</div>
</div>
{% endfor %}
Here is my function to change the icon:
<script>
$(document).ready(function(){
$('#btn-collapse_{{ i }}').on('click', function () {
var thisElement = $(this);
var anchorElement = thisElement.find("i");
if(anchorElement.text() === "expand_less"){
anchorElement.text('expand_more');
} else {
thisElement.find("i").text("expand_less");
}
});
});
</script>
I've also tried changing the color in in another instance. Heres the element:
<tbody>
{% for i in data %}
<tr style="vertical-align: middle;">
<td>{{ i }}</td>
<td>{{ i.data1 }}</td>
<td>{{ i.data1 }}</td>
<td style="text-align: center;">
<button class="btn", id="btn-{{ i.data2 }}">
<i class="far fa-check-circle"></i>
</button>
</td>
<td style="text-align: center;">
<button class="btn", id="btn-{{ i.data3 }">
<i class="far fa-check-circle"></i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
And here is the function:
<script>
$(document).ready(function(){
var data_button = document.getElementById("btn-{{ i.data2 }}");
if({{ i.data2 }} == 'None'){
data_button.style.color = "#858796";
}
else {
data_button.style.color = "#1cc88a";
}
});
</script>
Data that is being queried in second instance is either 'None' or date.
In your script you wrote {{ i }} outside of for loop. Use class instead of id because if you get an element with id it will get only the first child, while class receives all. And you don't need commas between your element attributes.
<a href="#collapse{{ i }}" class="btn" data-id="{{forloop.counter}}" role="button" data-bs-toggle="collapse" id="btn-collapse_{{ i }}">
<script>
$(document).ready(function(){
$('.btn').on('click', function () {
data_id = $(this[data-id])
var thisElement = $(this).filter('[data-card="'+data_id+'"]');
var anchorElement = thisElement.find("i");
if(anchorElement.text() === "expand_less"){
anchorElement.text('expand_more');
} else {
thisElement.find("i").text("expand_less");
}
});
});
</script>
I use jQuery. Please include it in your head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
I had to modify the script enes islam provided, this is how I got it in the end:
<a href="#collapse{{ i }}" data-id_collapse="{{ forloop.counter }}" class="btn" role="button", data-bs-toggle="collapse" id="btn-collapse_{{ i }}">
<script>
$(document).ready(function(){
$('.btn').on('click', function () {
data_id = $(this).attr('data-id');
var thisElement = $(this).filter('[data-id=' +data_id+ ']');
var anchorElement = thisElement.find("i");
if(anchorElement.text() === "expand_less"){
anchorElement.text('expand_more');
} else {
anchorElement.text('expand_less');
}
});
});
</script>
I'm try to add click get value from my table this is my table
#foreach($inventory as $p)
<?php
$no++;
$typesql = DB::table('product_variant_pos')
->where('id_product',$p->id)
->select('type')
->distinct()
->get();
?>
<tr >
<th scope="row"><?php echo $no;?></th>
<td style="width:100px;">
#if($p->featured_image != null || $p->featured_image != '')
<img src="{{ 'Images/'.$p->featured_image }}" alt="{{ $p->featured_image }}" title="{{ $p->featured_image }}" width="100px">
#else
<h4>Nothing Image Upload</h4>
#endif
</td>
<td class="data-product" id="{{ $p->id }}" data-toggle="modal" data-target="#ModalProduct" >{{ $p->item_name }}</td>
<td>
#if(!is_null($typesql))
#foreach($typesql as $t)
<ul>
<?php
$type = DB::table('product_variant_pos')
->where('id_product',$p->id)
->where('type',$t->type)
->get();
?>
<li>{{ $t->type }}
<ul>
#foreach($type as $j)
<li>{{ $j->name }}</li>
#endforeach
</ul>
</li>
</ul>
#endforeach
#else
<?php
$type = DB::table('product_variant_pos')
->where('id_product',$p->id)
->get();
?>
<li>{{ $t->type }}
<ul>
#foreach($type as $j)
<li>{{ $j->name }}</li>
#endforeach
</ul>
</li>
</ul>
#endif
</td>
<td>{{ $p->category }}</td>
<td>{{ $p->stock }}</td>
<td>Rp. {{ $p->price }}</td>
<td>
Edit
|
delete
</td>
</tr>
#endforeach
and this is my javascript
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('.data-product').click(function(e){
var formData = {
id: $(this).attr("id"),
};
var button_id = $(this).attr("id");
$.ajax({
type:'POST',
url:'product/modal',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(data) {
$("#ModalProductTitle").html(data);
},
error: function (data) {
console.log(data);
}
});
});
} );
</script>
this script make value
The post method is not supported for this route.
I am try code for other similar question but its not work. I am try in latest laravel and php.
I think is caused csrf() is not detected in my code, but I don't know where is my mistake
can anyone help me solve this problem, thankyou+.
There are 2 alternatives, please choose one
Change your route type to POST because your AJAX type is POST Route::post('/product/modal', 'ProductController#Modal');
Or change your AJAX type to GET because your route's type is GET
$.ajax({
type:'GET',
url:'/product/modal',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(data) {
$("#ModalProductTitle").html(data);
},
error: function (data) {
console.log(data);
}
});
I'm having hard time with js and jquery executing events, I guess there is something I'm missing in my understanding of jquery.
Because I'm really new to this language, I'm confused and need some orientation if you can help me please.
what I need:
I have a form as a row, and a button that adds a new form everytime I click on it. also the new generated forms have different Ids and names.
Now every form contains two selects and need a change function to be excuted on it.
Where should I write this change function, so that every row have his own change function without getting confused with other rows.
EDIT :
<div id="myDIV1" style="display: inline">
<form action="/banque" method="POST" enctype="multipart/form-data" id="personForm" data-tiers-url="{% url 'ajax_load_tiers' %}" >{% csrf_token %}{{ form.non_field_errors }}
<table style ="border-collapse: separate;border-spacing: 15px;" id="id_forms_table">
<tr><td width="5%">N P</td><td width="8%">Date d'operation</td><td width="25%">Désignation</td><td width="10%">Type tiers</td><td width="10%">Tiers</td><td width="10%">Référence de Facture</td><td width="10%">Montant debit </td><td width="10%">Montant crédit</td></tr>
{% for form in formset %}
<tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" >
<td{% if forloop.first %} class="" {% endif %}><div class="col-xs-1"><b><p name="np1">1</p></b></div></td>
<td>
{% render_field form.dateOperation class="form-control" %}{{form.dateOperation1.errors}}
</td>
<td>{% render_field form.designation class="form-control" %}{{form..errors}}
</td>
<td>
{% render_field form.typeTiers class="form-control" %}{{form.typeTiers.errors}}
</td>
<td>
{% render_field form.tiers class="form-control" %}{{form.tiers.errors}}
</td>
<td>{% render_field form.numfacture class="form-control" %}{{form.numfacture.errors}}
</td>
<td>{% render_field form.montantdeb class="form-control" %}{{form.montantdeb.errors}}</td>
<td>{% render_field form.montantcred class="form-control" %}</td>
</tr>
{% endfor %}
<tr>
</tr>
</table>
{{ formset.management_form }}
<tr>
<!-- BUTTONS <td colspan="4">add property</td> -->
<td width="16%"><input type="submit" name="annuler" value="Annuler" class="btn btn-danger" style="float:right ;margin: 5px; margin-right: 35px"></td>
<td width="16%"><button value="" class="btn btn-success" style="float:right;margin: 5px;" onclick="verifier()">enregistrer</button></td>
</form>
<td><input type="submit" name="ajoutligne" value="Ajouter une ligne" class="btn btn-primary" id="add-row" style="background-color: #8C1944; border-color: #8C1944; float:right;margin: 5px;" onclick="test()"></td></tr>
</div>
On change of each added row by the button Ajouter une ligne , I need to execute the following change function:
$("#id_form-"+0+"-typeTiers").change(function () {
alert($('#id_form-'+0+'-typeTiers').attr('name'));
var url = $("#personForm").attr("data-tiers-url");
var typeID = $(this).val();
$.ajax({
url: url,
data: {
'tiers': typeID,
},
success: function(data) { // `data` is the return of the `load_cities` view function
alert(data);
var i=1;
var listeClt = $(data).clone(true).find('option[id=facvente],option[id=fadepenses],option[id=frs]').remove().end().html();
var listefactVentes= $(data).clone(true).find('option[id=clt],option[id=fadepenses],option[id=frs]').remove().end().html();
var listefrs = $(data).clone(true).find('option[id=facvente],option[id=fadepenses],option[id=clt],option[id=cnss]').remove().end().html();
var listefactDep= $(data).clone(true).find('option[id=clt],option[id=facvente],option[id=frs]').remove().end().html();
// var cnss= $(data).clone(true).find('select').remove().end().html();
if(listeClt!=0){
$("#id_form-"+0+"-tiers").html(listeClt);
$("#id_form-"+0+"-numfacture").html(listefactVentes);
}
else if(listefrs!=0){
$("#id_form-"+0+"-tiers").html(listefrs);
$("#id_form-"+0+"-numfacture").html(listefactDep);
}
else {
$("#id_form-"+0+"-tiers").html(data);
}
}
});
});
"#id_form-"+0+"-typeTiers" is the id of the first row select , "#id_form-"+0+"-tiers" is the Id of the select that will get populated after changing "#id_form-"+0+"-typeTiers" of the same row.
this jquery changes the first row correctly, but what about rows tha will be add after ? their fields will have as Ids 1 , 2 .. etc instead of 0 .
Any help would be great. Thank You in advance
Please look on this some samples. it may helps you
https://www.aspsnippets.com/Articles/Add-Insert-Remove-Delete-Table-Rows-dynamically-using-jQuery.aspx
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-append-and-remove-table-row-dynamically
I have a Jquery/Ajax call which updates cart details. At the moment I can't get the existing HTML in the cart-body(tablebody) to clear. The actual ajax request works and all items are added to cart but the original HTML entries stay. The particular code is here:
if (data.products.length > 0 ) {
productRows.html("")
$(cartBody).empty()
Jquery Function
function refreshCart() {
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
var productRows = cartBody.find(".cart-product")
var cartTotal = cartTable.find(".cart-total-sec")
var productQuantity = cartTable.find(".cart-item-quanity")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 0 ) {
productRows.html("")
$(cartBody).empty()
$.each(data.products, function(index, value) {
console.log(value)
console.log(data.count)
cartBody.append("<tr><td>" + value.quantity + " x" + "</td><td>"+ value.name + "</td><td>" + "£" + value.price + "</td></tr>")
})
cartTotal.find(".cart-total").text(data.total)
console.log(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
HTML Form:
<div>
<h4>This is your shopping cart</h4>
<table class="cart-table">
<tr>These are the items in your basket and their respective totals</tr><br>
<tbody class="cart-body">
{% for item in cart.items %}
<form method="POST" action='{% url "shopping-cart-remove" %}'>
{% csrf_token %}
<tr class="cart-product"><span class="cart-item-quanity">{{ item.quantity }}</span> x {{ item.product.name }} = {{ item.subtotal }}</tr>
<input type="hidden" name='id' value='{{ item.product.id }}'>
<span class='remove-span'><button>remove</button><br></span>
</form>
</tbody>
{% endfor %}
<tr class="cart-total-sec"><td class="cart-price">{{ cart.total }}</td></tr>
</div>
Any help is really appreciated.
First you are making mistake, as i can see there's form in table, on refreshing you will lose that form so i guess you should append items in form not in .cart-body.
And for emptying html use cartBody.html(""); and you don't have to use productRows.html("") at all.
The issue as pointed out by Ultrazz008, was that the HTML was incorrectly formatted. For reference:
<table class="cart-table">
<tbody class="cart-body">
<form method="POST" class='form-product-ajax' action='{% url "shopping-cart-remove" %}' data-endpoint='{% url "shopping-cart-remove" %}'>
{% csrf_token %} {% for item in cart.items %}
<tr class=cart-product>
<td>{{ item.quantity}} x {{ item.product.name }} {{ item.subtotal }}
<input type="hidden" name='id' value='{{ item.product.id }}'>
<button class='remove-btn'>remove</button>
</td>
{% endfor %}
</tr>
</form>
</tbody>
<tr class="cart-total-sec">
<td class="cart-price">{{ cart.total }}</td>
</tr>
</table>
I use Silex Frame Work and I am trying to delete files in backend that listed in a table using the following code but fire bug is given me an error message "invalid regular expression flag a" And when i click on the DELETE link it goes to a white page.The code is:
<script type="text/javascript">
$(document).ready(function(){
$(".delete-file").live('click', function() {
itemRow = $(this).parent().parent().parent();
fileId = $(this).attr('file_id');
deleteURL = $(this).attr('href');
var html = "<div> Are you sure, you want to DELETE this file? </div>";
var dialog = $(html).dialog({
buttons: {
"Ok": function() {
$.ajax({
url : deleteURL,
type : 'DELETE',
success : function(data) {
itemRow.remove();
dialog.dialog("close");
},
error : function() {
dialog.dialog("close");
}
});
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
return false;
});
});
</script>
and i use:
{% for row in result %}
<tr class="content {{ cycle(['odd', 'even'], loop.index) }}">
<td> {{ row.name }} </td>
<td> {{ row.user.username }} </td>
<td class="url"> {{ row.path | truncate(30) }} </td>
<td> <img src="{{conf('base_url')}}/{{row.thumbnail}}"/> </td>
<td class="url"> {{ row.size | bytes_format}} </td>
<td> {{ row.description }} </td>
<td>
<span>DELETE</span>
</td>
</tr>
{% endfor %}
I found it. it's just because of giving wrong path to my .js files!!