I am trying to add values with the help of jquery But last value + in code again and again
The last value should be cleared when select new value from dropdown
var lastSelected;
$(document).ready(function() {
$("#selectchild1").on('change', function() {
$("div").remove("select");
var childvalue = this.value;
alert(childvalue);
var count = $(this).val();
newContent = "";
name = $(this).attr("name");
var j = 1;
var k = 0;
for (var i = 0; i < count; i++) {
newContent += $("#addedchild1").append("<div class='col-md-2 col-lg-2 text-center'><div class='form-group'>Child-" + j + " Age <select name='RoomTypes[" + k + "][]'><option value='0'>Age</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option><select></div></div>");
j++;
}
content.html(newContent);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectchild1" class="form-control">
<option value="0">00</option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
</select>
<div class="col-xs-3 col-sm-3 col-md-8 text-right">
<div id="addedchild1"></div>
</div>
I think you mean this
newContent += $("#addedchild1"). is not doing what you think it is
There is no content declared
You do not need to remove anything if you use .html() it replaces the HTML
I think you do not want addedChild1 but all the added children in the div I gave ID="wrapper" - if you want to nest in a addedChild, just change #wrapper to #addedChild1
$(function() {
$("#selectchild1").on('change', function() {
var count = +$(this).val();
name = $(this).attr("name");
const newContent = Array.from(Array(count+1).keys()) // cleate an array from 0 to count+1
.slice(1) // get rid of the `0` to use ${i} from `1`
.map(i => (`<div class='col-md-2 col-lg-2 text-center'><div class='form-group'>Child-${i} Age <select name='age'><option value='0'>Age</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option><select></div></div>`))
$("#wrapper").html(newContent.join("")); // add the array to the wrapper after joining it
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectchild1" class="form-control">
<option value="0">00</option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
</select>
<div id="wrapper" class="col-xs-3 col-sm-3 col-md-8 text-right">
</div>
First of all there is an error in your code. There is no variable named content.
Uncaught ReferenceError: content is not defined
You should add the following line to your code.
$('#addedchild1 div').remove();
I hope I understood your problem and I hope I was able to help you.
Check the example here: https://codepen.io/yasgo/pen/ExyqWvy
Related
So I'm getting a null error with my order form when I'm trying to calculate the total using javascript. I believe I have everything done. I get an error on line 13 below that starts with .innerHTML
<script type="text/javascript">
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var price = document.getElementById(strains[i] + priceStr).value;
var quantity = document.getElementById(strains[i] + quantityStr).value;
document.getElementById(strains[i] + subtotalStr)
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
document.getElementById("finaltotal").innerHTML = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
</script>
Here is the HTML that is associated just one example they are all the same with unique id and names.
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Full Example:
https://jsfiddle.net/dg260zxf/
Also if I could just make this work without the subtotal since I don't think it's necessary that would be awesome.
the problem is the array contains many Divs than not in HTML,
the first item 'guptakush_' only exist in html
so if you check if div exists before settings value it will resolve the problem
+
the finaltotal is input not html so put new value with .value not .inerHTML
Working demo:
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var priceInput = document.getElementById(strains[i] + priceStr);
var quantityInput = document.getElementById(strains[i] + quantityStr);
var subTotalDiv = document.getElementById(strains[i] + subtotalStr);
if(subTotalDiv) {
var price = priceInput.value;
var quantity = quantityInput.value;
subTotalDiv
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
}
document.getElementById("finaltotal").value = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Plenty of issues:
You hadn't defined subtotalStr, so that was null
You weren't executing your setup function because you didn't include parentheses
Your <strong> element doesn't seem to be populatable when selecting it by ID (not sure what was up w/that, but changing it to a div worked).
Check this: https://jsfiddle.net/mj1z9bvq/
In my version, I fixed the first two problems. And then for the first <strong> element, I replaced it with a <div> so you could see the output. You'll have to go through and do something similar for the others.
I'm pretty new to JS, and I want to add many options to multiple select. But the problem is that when I'm trying to show them only the last record is triggering the function (showing). But when I'm doing console.log it is showing every thing perfectly.
This is my HTML:
<form class="cart" method="post" action="{{ route('cart.add') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="product_size" class="grey">Model</label>
<span class="red">*</span>
<select class="form-control" id="productModel" name="product" onchange=" addRelatedproducts();">
<option value="">Wybierz model produktu...</option>
#foreach($productModels as $productModel)
<option value="{{$productModel->id}}">{{$productModel->modelName}} - {{$productModel->modelPrice}} #if($productModel->modelPriceCurrency === 1) PLN #else EUR #endif</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleSelect1">Ilość:</label>
<select class="form-control" id="exampleSelect1" name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div>
<div class="form-group" id="relatedProductsDiv" style="display: none;">
<label for="exampleSelect1">Produkty powiązane:</label>
<select id="select" multiple="multiple" class="relatedProducts" name="relatedProduct">
</select>
</div>
</div>
This is my JS:
function addRelatedproducts(){
var model = [
<?php foreach($productModels as $productModel):?>
<?=$productModel?>,
<?endforeach;?>
];
var relatedProducts = [
<?php foreach($relatedProductArray as $relatedProduct): ?>
<?=$relatedProduct ?>,
<?endforeach; ?>
];
var e = document.getElementById("productModel");
var selectedModelId = e.options[e.selectedIndex].value;
var select = document.getElementById("select");
for (var i = 0; i < relatedProducts.length + 1; i++) {
select.remove(relatedProducts[i].relatedProductName);
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
console.log(selectedModelId)
document.getElementById("relatedProductsDiv").style.display = "";
var option = document.createElement("option");
option.value = relatedProducts[i].id;
option.text = relatedProducts[i].relatedProductName;
select.add(option);
}
else{
document.getElementById("relatedProductsDiv").style.display = "none";
}
}
}
I don't really know why it isn't working. Can anybody help me with this problem?
select.remove(relatedProducts[i].relatedProductName);
select.remove expects an option index as an argument. And I suppose when it receives a product name string (probably not a number) apparently it evaluates it as NaN and just removes the very first option in the select on every step. So it comes up with an empty select in the end.
Maybe the better approach would be to clear all the select options right before iterating relatedProducts and then to populate only with the needed ones?
while(select.options.length) {
select.remove(0);
}
for (var i = 0; i < relatedProducts.length + 1; i++) {
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
// ....
I want to remove a specific value from an array.
For example:
var categories = ["Lenovo","Large","100"];
I displayed it like this
HTML CODE:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
How can I achieve this?
I tried it so many times but I failed because I cant get the value. You can check my code:
jQuery("#filter").val()
jQuery(function() {
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories = [];
if (brand) {
categories.push(brand);
}
if (screen_size) {
categories.push(screen_size);
}
if (cpu) {
categories.push(cpu);
}
if (memory) {
categories.push(memory);
}
if (price) {
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
var categories3 = "";
for (var i = 0; i < length; i++) {
var cat_id = "cat" + i;
categories3 += "<div class='filter_style'>" + categories[i] + "<a href='" + cat_id + "' id='" + cat_id + "' onclick='removeCat(event)'><span style='margin-left:15px;color:gray;' >x</span></a></div>";
jQuery("#filter").html(categories3);
}
});
});
function removeCat(evt) {
evt.preventDefault();
var catid = jQuery(this).attr('href');
var cat = jQuery(this).data("id");
//jQuery.grep(); maybe or indexOf first then slice() but I do not get the value
alert(catid);
}
You can simply remove element from array using below method
categories .splice( $.inArray(removeItem, categories), 1 );//removeItem is name of item which you want to remove from array
If you want to remove, for example, "Lenovo" from:
var categories = ["Lenovo","Large","100"];
do:
categories.splice(0)
Hello guys I'm doing a product filtering and I don't know how could I achieve it.
I used Javascript by getting the value of the selected values then alert it but the problem is that how could I display it also how can I remove the categories selected by clicking the x button. Here the sample page. Thank you very much for your help.
Here is my script code:
<script>
jQuery("#filter").val()
jQuery(function(){
jQuery( ".product-line" ).each(function( index ) {
var url = '<?php echo $upload_url; ?>';
var desc_id = jQuery(this).eq(0).find('.prod-desc').attr('id');
if(desc_id){
var file_url = url + desc_id + '/description.html';
jQuery('#'+desc_id).eq(0).load( file_url );
}
});
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories =[];
if(brand)
{
categories.push(brand);
}
if(screen_size)
{
categories.push(screen_size);
}
if(cpu)
{
categories.push(cpu);
}
if(memory)
{
categories.push(memory);
}
if(price)
{
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
alert(categories2);
var categories3="";
for(var i = 0; i < length; i++){
categories3 += "<div class='filter_style'>"+categories[i]+"<span style='margin-left:15px;color:gray;'>x</span></div>";
jQuery("#filter").html(categories3);
}
});
});
</script>
My HTML Code:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
</div>
There is possibilities, I will UPDATE the answer if it wasn't correct.
But first can you help what will you get after you run this code?
jQuery("#brand,#screen_size").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
console.log(brand);
console.log(screen_size);
});
I am trying calculate the amount on change of select dropdown. I need each row calculation front of that row i.e. subtotal and all subtotal will be at bottom at "Total Amount"
I am getting the calculations for first row, but there is issues somewhere, i cannot findout properly. Please help me.
My code is
jQuery(document).ready(function() {
var bookIndex = 1;
jQuery('#orderform')
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = jQuery('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.addClass('form-group')
.removeAttr('id')
.removeAttr('style')
.attr('id', "row"+bookIndex)
.attr('data-index', bookIndex)
.insertBefore($template);
jQuery("#row"+bookIndex+' .addprice span').addClass('item_price');
jQuery("#row"+bookIndex+' .addprice input').addClass('itemprice');
jQuery("#row"+bookIndex+' > div ').removeClass('addprice');
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = jQuery(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
// Remove element containing the fields
$row.remove();
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
});
jQuery(document).ready(function(){
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
jQuery(".dynamic-fields").each(function() {
var tpy = parseInt(jQuery(".service_type option:selected").val());
var clths = parseInt( jQuery(".cloths option:selected").val() );
var quantity = parseInt( jQuery(".quantity option:selected").val() );
var total;
total= tpy + clths * quantity;
jQuery("span.item_price").html(total);
jQuery("input.itemprice").attr('value', total);
});
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
var total = 0;
var id = jQuery(this).parent().parent().attr('id');
var index = jQuery(this).parent().parent().attr('data-index');
id = '#'+id+' '; //alert(id); //alert(index);
//jQuery('.form-group').each(function () {
var tpy = jQuery(id+'.service_type option:selected').val();
var clths = jQuery(id+'.cloths option:selected').val();
var quantity = jQuery(id+'.quantity option:selected').val();
total= ( parseInt(tpy) + parseInt(clths) ) * parseInt(quantity);
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
//});
var totalamount = 0;
var price =0;
jQuery('.accept-checkbox.dynamic-fields > div.form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form name="neworder" action="<?php the_permalink(); ?>" method="post" id="orderform">
<div class="accept-checkbox dynamic-fields">
<div class="form-group" id="row1" data-index="1">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2">
<span class="item_price">30</span>
<input type="hidden" class="itemprice" value="00"/>
</div>
<div class="col-sm-1">
<button class="btn btn-default addButton" type="button"><i class="fa fa-plus">+</i></button>
</div>
</div>
<!-- The template for adding new field -->
<div id="bookTemplate" class=" hide" style="display: none;">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2 addprice">
<span >30</span>
<input type="hidden" value="00"/>
</div>
<div class="col-xs-1">
<button class="btn btn-default removeButton" type="button"><i class="fa fa-minus"> - </i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-5 pull-right">
<span><strong>Total Amount : </strong></span><span id="totalamount"> <span>00.00</span>/- </span>
</div>
</div>
</form>
The added elements do not have an event handler.
To write one event handler for current and future elements, replace this:
jQuery('.dynamic-fields > div.form-group select').on("change", function () {
With:
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
Note that you still have many issues with your code. You should better keep your quantities, prices, etc.. (also) in variables, and not re-read them every time from html attributes.
For instance these lines are now wrong:
jQuery(".item_price").html(total);
jQuery("input.itemprice").attr('value', total);
You intended this:
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
... and there are more issues like that, but if I were you, I would refactor this code to rely less on the html attributes for calculating the total.
change the line
jQuery('.dynamic-fields > div.form-group select').on("change", function() { ...
to
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() { ...
because the EventListener change is bind once to the elements that are at the time in DOM the code is executed with selector .dynamic-fields > div.form-group select.
Now the EventListener is set to the document und the function is executed when event.target is .dynamic-fields > div.form-group select.