Jquery / JS - Update Drop Down - javascript

I've got this set up on JsFiddle: http://jsfiddle.net/melissal/FmEcw/
Now when I change the selection of the 'Quantity' dropdown, it changes the price of the paper (above). I want this to show in the 2nd drop down. So when you select the 'Paper' dropdown you see two options, 'Regular' and 'Premium (+ $XXX)', but I can't figure out how to get the new price to show up. Is that possible?
Here's the HTML:
Paper: $<span id="paper_div"></span><br />
<div id="product-options">
<form action="/cart/add" id="ProjectProductForm" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST"/>
</div>
<div id="product-options-qty">
<span class="text">Quantity: </span>
<span class="form">
<div class="input select">
<select name="field_6" class="text_select" id="field_6">
<option value="225">15 # $225.00</option>
<option value="240">20 # $240.00</option>
<option value="250">30 # $250.00</option>
<option value="270">40 # $270.00</option>
</select>
</div>
</span>
</div>
<div id="product-options-paper">
<span class="text">Paper: </span>
<span class="form">
<div class="input select">
<select name="field_6" class="text_select">
<option value="1">Regular</option>
<option value="2">Premium (+ $<span id="paper_div"></span>)</option>
</select>
</div>
</span>
</div>
</form>
And the JS:
$(document).ready(function() {
$("#field_6").change(function() {
var id = $(this).val();
$('#price_div').html($(this).val());
var premium_paper = id * .25;
var premium_paper = parseFloat(Math.round(premium_paper * 100) / 100).toFixed(2);
$('#paper_div').html(premium_paper);
}).change();
});

Try using $('#field_7 option:eq(1)').html('Premium (+ $'+premium_paper+')'):
Note that I added an ID to the second select. You may also want to give your drop downs different name attributes.
$(document).ready(function () {
$("#field_6").change(function () {
var id = $(this).val();
$('#price_div').html($(this).val());
var premium_paper = id * .25;
var premium_paper = parseFloat(Math.round(premium_paper * 100) / 100).toFixed(2);
$('#paper_div').html(premium_paper);
$('#field_7 option:eq(1)').html('Premium (+ $'+premium_paper+')')
}).change();
});
jsFiddle example

Related

each option in select tag disable a specific element in page

I'm trying to implement a form in which you choose a shape from a select tag and it calculates the area and perimeter.
I just want when I select the Square option from the select, radius input disabled like the image.
Please do not use JQuery
Please do not use JQuery
Please do not use JQuery
here is my form please help me with .js file
<div class="container">
<hr class="lighter">
<label for="shapes">Shapes :</label>
<select name="shapes" id="shapes">
<option value="rectangle">Rectangle</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
<option value="cylindrical">Cylindrical</option>
</select>
<br><br>
<lable for="radius">Radius : </lable>
<input type="number" id="radius" disabled><br>
<lable for="shapeWidth">Widht : </lable>
<input type="number" id="shapeWidth"><br>
<lable for="shapeHeight">Height :</lable>
<input type="number" id="shapeHeight">
<hr>
<label for="area" id="area_result">Area :</label>
<label for="area_result"></label>
<br>
<label for="primiter" id="primiter_result">Primiter :</label>
<label for="primiter_result"></label>
</div>
const eleId = document.getElementById("shapes");
const radiusId = document.getElementById("radius");
eleId.addEventListener(
"change",
function () {
if (this.value === "square") {
radiusId.disabled = true;
} else {
radiusId.disabled = false;
}
},
)
<div class="container">
<hr class="lighter" />
<label for="shapes">Shapes :</label>
<select name="shapes" id="shapes">
<option value="rectangle">Rectangle</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
<option value="cylindrical">Cylindrical</option>
</select>
<br /><br />
<lable for="radius">Radius : </lable>
<input type="number" id="radius" /><br />
<lable for="shapeWidth">Widht : </lable>
<input type="number" id="shapeWidth" /><br />
<lable for="shapeHeight">Height :</lable>
<input type="number" id="shapeHeight" />
<hr />
<label for="area" id="area_result">Area :</label>
<label for="area_result"></label>
<br />
<label for="primiter" id="primiter_result">Primiter :</label>
<label for="primiter_result"></label>
</div>
Her is a vanilla JS version
I fixed some spelling and added a "please select"
window.addEventListener("DOMContentLoaded", () => { // when the page has loaded
document.getElementById("shapes").addEventListener("change", function() { // when the select is changed
document.getElementById("radius").disabled = ["rectangle","square"].includes(this.value); // disable if square or rectangle.
})
});
<div class="container">
<hr class="lighter">
<label for="shapes">Shapes :</label>
<select name="shapes" id="shapes">
<option value="">Please select</option>
<option value="rectangle">Rectangle</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
<option value="cylindrical">Cylindrical</option>
</select>
<br><br>
<label for="radius">Radius : </label>
<input type="number" id="radius" ><br>
<label for="shapeWidth">Width : </label>
<input type="number" id="shapeWidth"><br>
<label for="shapeHeight">Height :</label>
<input type="number" id="shapeHeight">
<hr>
<label for="area" id="area_result">Area :</label>
<label for="area_result"></label>
<br>
<label for="perimeter" id="perimeter_result">Perimeter :</label>
<label for="perimeter_result"></label>
</div>
A label element should not be treated like the majority of other HTML elements in that it is not supposed to be used without being referenced to an input element of some type. So you should not use them to present content such as the calculation results as you do!
If you use a form around these various input controls you can use the often overlooked dotted notation to access these various form elements ( though many browsers permit accessing elements directly by ID without even requiring document.getElementById these days since HTML5 ) which is useful within any routines to perform the calculations as it reduces the code required.
// precision for floats
const precision=3;
const d=document;
// get reference to the parent form
const f=d.forms.calculator;
// event handler
const evthandler=function(e){
// ensure all disabled elements are re-enabled
f.querySelectorAll('input:disabled').forEach( input => input.disabled=false );
// named form inputs/outputs etc
let oSel=f.shapes;
let oArea=f.area;
let oPer=f.perimeter;
let oRad=f.radius;
let oWidth=f.shapeWidth;
let oHeight=f.shapeHeight;
// The currently selected `option`
let option=oSel.options[ oSel.options.selectedIndex ];
// access a named dataset to identify which elements to disable.
if( option.dataset.disable!=null ){
f[ option.dataset.disable ].disabled=true;
}
// do the calculations and show the results...
oArea.textContent=area( oSel.value, oWidth.value, oHeight.value, oRad.value );
oPer.textContent=perimeter( oSel.value, oWidth.value, oHeight.value, oRad.value );
};
const area=(shape,w,h,r)=>{
switch( shape ){
case 'square':
case 'rectangle':return w * h;
case 'circle':return ( Math.PI * Math.pow( r, 2 ) ).toFixed(precision);
case 'cylindrical':return ( 2 * Math.PI * Math.pow( r, 2 ) + 2 * Math.PI * r * h ).toFixed(precision);
}
};
const perimeter=(shape,w,h,r)=>{
switch( shape ){
case 'square':return 4 * Math.min(w,h);
case 'rectangle':return ( 2 * w ) + ( 2 * h );
case 'circle':return ( Math.PI * r * 2 ).toFixed(precision);
case 'cylindrical': return ( 2 * ( Math.PI * ( r * 2 ) ) ).toFixed(precision);
}
};
// assign the delegated event handler to respond to any change events
f.addEventListener('change', evthandler )
label{display:block;width:40%;clear:both;padding:0.5rem;}
label input,label select{float:right;width:60%;padding:0.25rem}
hr{margin:1rem 0}
output{color:green}
<div class='container'>
<hr class='lighter'>
<!--
Form added to group together form elements and allow
named access using dot notation.
labels correctly spelled and inputs nested within
so that <br /> tags can be replaced with CSS blocks
Added a dataset ( data-disable )
-->
<form name='calculator'>
<label>Shapes :
<select name='shapes'>
<option disabled hidden selected>Please select
<option data-disable='radius' value='rectangle'>Rectangle</option>
<option data-disable='radius' value='square'>Square</option>
<option value='circle'>Circle</option>
<option value='cylindrical'>Cylindrical</option>
</select>
</label>
<label>Radius: <input type='number' name='radius' min=0 step=1></label>
<label>Width: <input type='number' name='shapeWidth' min=0 step=1></label>
<label>Height: <input type='number' name='shapeHeight' min=0 step=1></label>
<hr />
<!--
output tags for displaying output rather than labels.
-->
<label>Area: <output name='area'></output></label>
<label>Perimeter: <output name='perimeter'></output></label>
</form>
</div>

how to display a generated select option based on its row in a dynamic select box

I have some problem with displaying a select option after i add a new one in dynamic select box. So the one i have here display the result of first row select box. While i change the qty and click order it will change the price result but after changing the option it will display result under the first one. For the result i need to change this code so when i click order button the result will display like this: if i have 3 rows of select boxes, the result will display each of it into 3 rows. Any help would be appreciated!
example
This is the example when i click order the first select box row, it display name=price*qty (this is the result i need for each select box)
This is the example when i change the first select box row option, it display a new result under the first result instead changing it
code
$(document).ready(function () {
var selectMenu = {};
$('.order').click(function () {
var itemName = $("#type_select option:selected").attr('label');
var price = Number($("#type_select option:selected").data('price'));
var count = Number($("#num").val());
var total = price * count;
selectMenu[itemName] = total
var result = JSON.stringify(selectMenu).replace(/,/g, '<br>').replace(/\{|\}|"/g, "")
//the result in the first row change price based on qty, but when option is changed the result display under the first one
$('.result').html(result);
Here is the link for full code: jsbin
I've done a bit of refactoring, because you were using same ids on multiple elements, so I changed them to classes. Full code: jsbin
$(document).ready(function () {
var selectMenu = {};
$('.order').click(function () {
selectMenu = {};
$('.menu-position').each(function (i) {
var category = $(this).find('.category-select').val()
var $selectedItem = $(this).find('.type-select :selected')
var name = $selectedItem.attr('label')
var price = $selectedItem.data('price')
var qty = +$(this).find('.qty').val()
var total = price * qty
selectMenu[name] = total
})
var result = JSON.stringify(selectMenu).replace(/,/g, '<br>').replace(/\{|\}|"/g, "")
$('.result').html(result);
});
});
Your order function had two errors:
You were processing only the first menu row.
You you were using the same "selectMenu" object instead of creating a new one.
You can use each loop because you might be having mutliple select-boxes for each row . Then , get price & quantity from each row and add save same inside JSON Object . Now, to show them use .each loop again and append new rows inside some divs.
I have created JSON structure like this :
{
//here 0 is first row
"0": {
"total": 0, //this is total for first row
"itemname": "Fried Rice" //this is price for first row
}
//same for other rows as well only changing 1 ,2..etc
}
Demo Code :
$(document).ready(function() {
$('.order').click(function() {
var selectMenu = {};
//loop through type select
$("select.type").each(function(i) {
selectMenu[i] = {} //create array
//get label value
var text = $(this).find("option:selected").attr('label');
//get price
var price = Number($(this).find("option:selected").data('price'));
//get qty
var qty = Number($(this).closest(".row").find(".qty").val())
//push same in array
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html(""); //clear tbody
$.each(selectMenu, function(index, data) {
//add tr inside tbody
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
})
});
});
.orders {
color: green;
font-weight: bold;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<!--added class cat -->
<select class="form-select form-select-lg mb-3 cat" id="category_select" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<!--added class type -->
<select class="form-select form-select-lg mb-3 type" id="type_select">
<option value="1" label="Fried Rice" data-price="10000"></option>
<option value="2" label="Fried Noodle" data-price="9000"></option>
<option value="3" label="Pancake" data-price="8500"></option>
<option value="4" label="French Fries" data-price="7500"></option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" id="num" placeholder="Qty" min="0">
</div>
</div>
<div class="row">
<div class="col-md-3">
<button type="button" class="btn btn-danger btn-lg ">Delete</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type">
<option value="1" label="Fried Rice" data-price="10000"></option>
<option value="2" label="Fried Noodle" data-price="9000"></option>
<option value="3" label="Pancake" data-price="8500"></option>
<option value="4" label="French Fries" data-price="7500"></option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" id="num" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="button" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th>Item name </th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

Add off option value in JS and html

I want to add off option value in my page
For example, you come in my shop page and choose a package, I want to add an option field for the Discount and when you enter a text that is available on s.txt you receive a discount offer.
For example, you enter a StackOverflow code and in s.txt:
stackoverflow--20
Then the price will be reduced by %20 and displayed.
My source code follows.
JavaScript:
$("#payBtn").click(function() {
$("#count").html($("#member").val());
var price = $("#member").val();
price = price * 5;
location.href = 'https://zarinp.al/levicoder/' + price;
});
$("#name").keyup(function() {
$("#payerName").html($("#name").val());
});
$("#channelInput").keyup(function() {
$("#channel").html($("#channelInput").val());
});
$("#discount").keyup(function() {
$("#disdis").html($("#discount").val());
});
$("#member").click(function() {
$("#count").html($("#member").val());
var price = $("#member").val();
price = price * 5;
$("#amount").html(price);
});
Html:
<div class="box shadow_box purchase_cm_box" >
<h4>Order</h4>
<hr>
<input type="text" class="form-control" id="name" placeholder="Your name"><br>
<input type="text" class="form-control" id="channelInput" placeholder="Your Id"><br>
<input type="text" class="form-control" id="discount" placeholder="discount code"><br>
<div class="form-group">
<select class="form-control" id="member">
<option value="9000">9000 Value</option>
<option value="2000">2000 Value</option>
</select>
<br>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 pull-left" id="leftmenu">
<div class="box shadow_box purchase_cm_box" >
<h4>Factor</h4>
<hr>
Your Name : <label id="payerName">don't entered</label><br>
Your id : <label id="channel"></label><br>
discount code : <label id="disdis"></label><br>
Pay Count
<label id="amount">7,000</label>
$
<br><br>
<button class="getBtn" id="payBtn">Pay</button><br>
<p id="payStatus"></p>
</div>
</div>
I tried not to officially answer this question because I am unsure what LeVi needs. But as a result of our conversation in the comments, I was asked to provide code.
Here's my best guess of what LeVi is asking:
let inputCode = "stackoverflow";
let savedCode = "stackoverflow--20"; // derived from file s.txt
let splitSavedCode = savedCode.split('--'); // this will return ['stackoverflow', '20']
if( inputCode == splitSavedCode[0] ) {
// edited after further discussion in comments
let discountPercentage = splitSavedCode[1] / 100;
let discountAmount = price * discountPercentage;
$('#discount').val(discountAmount);
}

Change Function return NaN Value

I have the following structure in my page:
Fieldset:
Size
Options
That shows Was, Now and You Save Price
Then I have JQuery in place that convert the above into float and shows the Save Price in percentage. It all works as intended until I change for instance the Size and the Options. To overcome this I've tried to use .change(function(). However when I change the value from the selected menu and it returns NaN.
Can you please help?
Here is my JS Code:
$(".product-options").change(function() {
var oldPrice = parseFloat(jQuery('.old-price-item .price .price').text().replace('£', ''), 10);
var savePrice = parseFloat(jQuery('.special-price .price .price').text().replace('£', ''), 10);
var youSave = savePrice / (oldPrice / 100);
var n = parseFloat(youSave).toFixed(2);
$('div.ratio-div').html('<p>' + n + ' % OFF</p>');
$('div.save-price-div').html('<p>£' + savePrice + ' OFF</p>');
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="options-container-big">
<fieldset class="product-options" id="product-options-wrapper">
<dl class="attribute-list">
<dt id="attribute122_row" style="position: relative;"><label class=
"required product-options__label" for=
"attribute122">Size</label></dt>
<dd>
<div class="input-select input-select--alternate">
<select class="validate-select super-attribute-select validation-passed" data-attribute="item-size" data-choosetxt="Size" data-role="none" id="attribute122" name="super_attribute[122]">
<option value="">
Size
</option>
<option value="235">
Single
</option>
<option value="238">
Double
</option>
<option value="239">
King
</option>
</select>
</div><span class="item-size-warning" id="attribute122-warning" style="display:none;"></span>
</dd>
<dt id="attribute129_row" style="position: relative;"><label class=
"required product-options__label" for=
"attribute129">Storage</label></dt>
<dd class="last">
<div class="input-select input-select--alternate">
<select class="validate-select super-attribute-select" data-attribute="storage" data-choosetxt="Storage" data-role="none" id="attribute129" name="super_attribute[129]">
<option value="">
Storage
</option>
<option value="310">
No Drawers
</option>
<option value="312">
2 Drawers
</option>
<option value="313">
4 Drawers
</option>
</select>
</div>
</dd>
</dl>
</fieldset>
<div class="product-options-bottom">
<div class="add-to-cart">
<div class="price-box">
<div class="old-price">
<ul id="old-price-15511">
<li class="old-price-item">
<div class="line-through">
</div><span class="price-label">Was</span>
<span class="price"><span class=
"currency">£</span></span>
</li>
<li class="old-price-item">
<div class="line-through">
</div><span class="price-label">Was</span>
<span class="price"><span class=
"currency">£</span></span>
</li>
</ul>
</div>
<p class="special-price"><span class="price-label">You
Save</span> <span class="currency-special-price">£</span>
<span class="price" id="price-excluding-tax-15511"></span>
</p><span class="regular-price" itemprop="offers" itemscope itemtype="http://schema.org/Offer"></span>
<meta content="GBP">
</div>
<div class="product-stock-status">
<div class="product-stock-status__wrapper">
<span class="title">In Stock</span>
</div>
</div>
</div>
</div>
</div>
Please note The fieldset provide different price for Size only or Size + different option.
Based on the HTML provided, it looks like you have incorrectly doubled up the class selector called "price" in the jQuery selectors.
Try these instead:
var oldPrice = parseFloat(jQuery('.old-price-item .price .currency').last().text().replace('£', ''), 10);
var savePrice = parseFloat(jQuery('.special-price .price').text().replace('£', ''), 10);
It is difficult to know for certain because the html is missing the numbers. I guess you either edited the price out, or it is generated dynamically by some other script not shown.
Here is a cut down version of the html to illustrate what your selectors are choosing:
http://jsbin.com/heduju/5/edit?html,js,console,output
Update
Just noticed that there are multiple matches to the first selector so I added .last() to the selector as well (assuming that the last was price is used for the calculation).
http://jsbin.com/jegeqe/17/edit?html,js,console,output
jQuery('.old-price-item .price .price').text() returns "" (empty string), so parseFloat() is NaN.

jquery hiddenbox and listbox discount calculation

I want to use jQuery to calculate value from listbox and hidden
<input type="hidden" id="val1" name="albania" value="100000" />
<select class="span6 chosen" id="val2" name="discount" data-placeholder="Choose a Discount" tabindex="1">
<option value="" />
<option value="10" />10
<option value="20" />20
</select>
and I want to write a value in span
<div class="control-group">
<label class="control-label" >Total Value After Discount</label>
<div class="controls">
<span class="help-inline" id="yaz"></span>
</div>
</div>
Basicly I need to calculate discount from the price and show it for the customers. I tried this code:
<script>
$('input["#val2"]').keyup(function() {
var a = $('input["#val1"]').val();
var b = $(this).val();
$("#yaz").text((a * b) / 100 + a);
});
</script>
but it didnt work.
Try This,
$('#val2').change(function() {
var a = $('#val1').val();
var b = $(this).val();
$("#yaz").text((parseInt(a) * parseInt(b)) / 100 + parseInt(a));
});
You should use change event instead of keyup
Example
You Need to use parseInt
$("#yaz").text((parseInt(a) * parseInt(b)) / 100 + parseInt(a));

Categories