Calculating price from selected options in jquery - javascript

My html code :
<select class="form-control B3 pricing" name="B3">
<option data-price="0" data-cheap="0">0</option>
<option data-price="20" data-cheap="30">1</option>
<option data-price="40" data-cheap="60">2</option>
<option data-price="60" data-cheap="90">3</option>
<option data-price="80" data-cheap="120">4</option>
<option data-price="100" data-cheap="150">5</option>
</select>
My jquery code :
$(document).ready(function () {
var cheap=false;
$('.day1').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = optionSelected.val();
if(valueSelected=="Saturday")
{
cheap=true;
alert(cheap);
}else{
cheap=false;
alert(cheap);
}
});
$('.pricing').change(function(){
var price = parseFloat($('.total').data('base-price'));
$('.pricing').each(function(i, el) {
if(cheap==false){
price += parseFloat($('option:selected', el).data('price'));
}else{
price+= parseFloat($('option:selected').data('cheap'));
}
});
$('.total').val('$'+price.toFixed(2));
});
});
I want that when the day is selected as Saturday the data-cheap has to be taken and when other days are selected data-price should be calculated. Any help?

The only problem I could see is you are not passing the context to the cheap query
$(document).ready(function () {
var cheap = false;
$('.day1').on('change', function (e) {
cheap = $(this).val() == "Saturday";
});
$('.pricing').change(function () {
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing').each(function (i, el) {
price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
console.log('x', price)
$('.total').val('$' + price.toFixed(2));
});
});
});
Demo: Fiddle

Related

How to remove duplicate values coming from option tag

I have an Select tag with multiple options.On button click every selected option creates an li with innerText set to text value of the option. How would i make a function that i cant add the same element twice?
$(".btn").on("click", function () {
let selectedItems = $("#node-input-options option:selected");
selectedItems.each(function (i, el) {
// console.log(el, i);
let text = $(el).text();
let val = $(el).val();
var li = $("<li>").text(text).val(val).attr("title", val);
list.append(li);
li.on("dblclick", function () {
li.remove();
});
});
This is my code in jquery.
This is and example on fiddle => https://jsfiddle.net/nah062ck/11/
> You can use Jquery contains selector to check if a selected item already exists in the list.
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i,el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).val(val).attr('title', val).attr("size",10);
li.size = 10;
var exists=$('.list li:contains('+text+')');
if(exists.length > 0){
alert('The Selected Word already exists');
return
}
list.append(li);
});
});
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i, el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).val(val).attr('title', val).attr("size", 10);
li.size = 10
let c = 0
if ($(".list li").length === 0) {
list.append(li)
// if list is empty fill it
} else {
$(".list li").each(function(i, el2) {
$(el2).text() == text ? c = "x" : null
// if not empty, check if text exists in list under each li
})
}
c === 0 ? list.append(li) : console.log(false)
// do according
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="7" name="cars" id="cars" multiple>
<option value="cup">Cupcake</option>
<option value="cupas">Cunut</option>
<option value="cup124">Eclair</option>
<option value="cup2512">Froyo</option>
<option>Gingerbread</option>
</select>
<button id="b1">Click me</button>
<ul class="list"></ul>
After you append to list you can disable and unselect using .prop({'disabled': true, selected:false})
Then in your remove process look for that same option and enable it again.
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i, el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).attr('title', val);
list.append(li);
}).prop({disabled: true, selected: false});
});
$('.list').on('dblclick', 'li', function() {
const $li = $(this),
title = $li.attr('title');
$("#cars option[value='" + title + "']").prop('disabled', false)
$li.remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="7" name="cars" id="cars" multiple>
<option value="cup">Cupcake</option>
<option value="cupas">Cunut</option>
<option value="cup124">Eclair</option>
<option value="cup2512">Froyo</option>
<option>Gingerbread</option>
</select>
<button id="b1">Click me</button>
<ul class="list"></ul>
let addEl = document.getElementById("add-country");
let containerList = document.getElementById("country-list");
let countries = [];
addEl.onclick = function(e) {
e.preventDefault();
let selectEl = document.getElementById("country").value;
if (!(countries.includes(selectEl))) {
countries.push(selectEl);
let createElLi = document.createElement("LI");
createElLi.innerHTML = selectEl;
containerList.appendChild(createElLi);
}
}
<form method="get" accept-charset="utf-8">
<select name="country" id="country">
<option>Japan</option>
<option>USA</option>
<option>India</option>
<option>Bangladesh</option>
<option>Canada</option>
<option>Pakistan</option>
</select>
<input type="submit" value="Add" id="add-country">
</form>
<ul id="country-list"></ul>
Code :
<html>
<head>
<title>Remove Duplicate Options</title>
</head>
<body>
<select id='mylist'>
<option value='php'>PHP</option>
<option value='css'>CSS</option>
<option value='php'>PHP</option>
<option value='sql'>SQL</option>
<option value='js'>JS</option>
<option value='css'>CSS</option>
<option value='js'>JS</option>
</select>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
<script>
function removeduplicate()
{
var mycode = {};
$("select[id='mylist'] > option").each(function () {
if(mycode[this.text]) {
$(this).remove();
} else {
mycode[this.text] = this.value;
}
});
}
</script>
<button onClick='removeduplicate()'>Remove Duplicate</button>
</body>
</html
Reference : Narendra Dwivedi - Remove Duplicate DropDown Option

Update the value of a variable

When "Add to Cart" is clicked, the value is added to ".total-cart", and after an option is chosen in , the option value is added to the total cart value and displayed in ". total-all ". But when you click "Add to cart" again, the value of ".total-all" does not change. It is only updated when another option is selected within . Is there a way to update the value of ".total-all" automatically?
● DEMO
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script> //Select with Fees
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1lyCo_s17CxGzI2n83_H2IKTTE-ot9Pam1ZyC8t6qZmE/2/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#selectID").append(
'<option hidden="hidden" selected="selected" value="0">Choose</option><option value="' + this.gsx$price.$t.replace(/,/, '.') + '">' + this.gsx$name.$t + ' $ ' + this.gsx$price.$t + '</option>'
);
});
});
});
</script>
<script>
var shoppingCart = (function() {
cart = [];
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
var obj = {};
// Add to cart
obj.addItemToCart = function(name, price, count) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count ++;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
}
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
return obj;
})();
$(document).ready(function() {
var sheetURL4 = "https://spreadsheets.google.com/feeds/list/1lyCo_s17CxGzI2n83_H2IKTTE-ot9Pam1ZyC8t6qZmE/1/public/values?alt=json";
$.getJSON(sheetURL4, function(data4) {
var entryData4 = data4.feed.entry;
console.log(data4);
jQuery.each(entryData4, function() {
$("#content").append(
this.gsx$name.$t + '<br> $ ' + this.gsx$price.$t +'<br>Add to cart<br>'
);
});
});
$.getJSON(sheetURL4, function(data4) {
$('.add-to-cart').click(function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = +$(this).data('price').replace(/,/, '.');
console.log(price);
// console.log($(this).data('price'));
shoppingCart.addItemToCart(name, price, 1);
displayCart();
});
});
});
function displayCart() {
var total = shoppingCart.totalCart();
$("#selectID").change(function() {
var totalWithTax = $(this).val();
$('.total-tax').html(totalWithTax);
var sumTotalAll = total + +totalWithTax;
$('.total-all').html(sumTotalAll.toFixed(2));
});
$('.total-cart').html(total.toFixed(2));
}
displayCart();
</script>
<div id="content"></div>
<br>
<select id="selectID" style="width:200px" value="0"></select>
<p>Subtotal: $ <span class="total-cart"></span></p>
<p>Tax Value: $ <span class="total-tax"></span></p>
<p><strong>Total: $ <span class="total-all"></span></strong></p>
You can call your change event on select-box whenever any item is added to cart using $("#selectID").trigger('change') so that total value will get updated .
Demo Code:
var shoppingCart = (function() {
cart = [];
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
var obj = {};
// Add to cart
obj.addItemToCart = function(name, price, count) {
for (var item in cart) {
if (cart[item].name === name) {
cart[item].count++;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
}
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for (var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
return obj;
})();
$(document).on('click', '.add-to-cart', function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = +$(this).data('price').replace(/,/, '.');
shoppingCart.addItemToCart(name, price, 1);
$("#selectID").trigger('change') //call select
});
//use like this because select-box are dynamically created
$(document).on('change', '#selectID', function() {
var total = shoppingCart.totalCart();
var totalWithTax = $(this).val();
$('.total-tax').html(totalWithTax);
var sumTotalAll = total + +totalWithTax;
$('.total-all').html(sumTotalAll.toFixed(2));
$('.total-cart').html(total.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">item 1<br> $ 10<br>Add to cart<br>item 2<br> $ 20<br>Add to cart<br>item
3
<br> $ 30<br>Add to cart<br></div>
<br>
<select id="selectID" style="width:200px" value="0">
<option hidden="hidden" selected="selected" value="0">Choose</option>
<option value="1">tax 1 $ 1</option>
<option hidden="hidden" selected="selected" value="0">Choose</option>
<option value="2">tax 2 $ 2</option>
<option hidden="hidden" selected="selected" value="0">Choose</option>
<option value="3">tax 3 $ 3</option>
</select>
<p>Subtotal: $ <span class="total-cart"></span></p>
<p>Tax Value: $ <span class="total-tax"></span></p>
<p><strong>Total: $ <span class="total-all"></span></strong></p>
Try this -
$.getJSON(sheetURL4, function (data4) {
$('.add-to-cart').click(function (event) {
...
shoppingCart.addItemToCart(name, price, 1);
$('.total-all').html((shoppingCart.totalCart() + Number($("#selectID").val())).toFixed(2)); // add this, it will update total amount
displayCart();
});
});

How to get the value from N dynamic inputs

I have a select with an options, this options have the number of inputs that user want to draw, after that user can type information in that inputs and finally they have to click a button to display that values, right now I'm doing this like this:
var value1 = $('#Input1').val();
The problem here is that the user can create a maximum of 200 inputs, so if I keep doing this in the above way I'll need to do that with the 200 inputs and it's a lot of code lines, my question is if exits a way to get the value of N inputs, I draw the inputs dynamically with a for loop, so all the input ID is something like Input(MyForVariable), Input1, Input2... etc, so maybe I'm thinking in create another loop to get the value of that inputs, here is my code:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
if (total == 2) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
alert(val1 + val2);
}
if (total == 3) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
var val3 = $('#Imput3').val();
alert(val1 + val2 + val3);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
Put all your inputs inside a container, and loop through them:
$('#add').on('click', function () {
$('<input />').appendTo('#myinputs');
});
$('#get').on('click', function () {
var values = [];
$('#myinputs input').each(function () {
values.push(this.value);
});
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myinputs">
<input />
</div>
<button id="add">Add another input</button>
<hr />
<button id="get">Get values</button>
You can set some attribute and get all elements that has it:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" to-count />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
var sum = "";
var inputs = $('[to-count]');
console.log(inputs.length);
for (let i=0; i < inputs.length ; i++){
sum += inputs[i].value;
}
alert(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
You can get the values for each of the Select options by using the following code:
$("#sel option").each(function() {
console.log($(this).val());
});
You can always loop throw your inputs like this:
var myInputArray = [];
$('input[type="text"]').each(function(){
myInputArray.push($(this).val());
}
Then you can get your values by locking in the array:
alert(myInputArray[0]) //The first value of the array => first input

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

How to find Currently Selected value from this Custom HTML form Tag?

I have an element which is text box but its value is populated from another hidden select element.
<input type="text" id="autocompleteu_17605833" style="box-shadow: none; width: 119px;" class="mobileLookupInput ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<select id="u_17605833" name="u_17605833" style="visibility: hidden">
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
var mySelObju_17605833 = document.getElementById("u_17605833");
$(function () {
var availableTagsu_17605833 = new Array();
for (var i = 0; i < mySelObju_17605833.options.length; i++) {
if (mySelObju_17605833.options[i].text != 'Other') {
availableTagsu_17605833[i] = mySelObju_17605833.options[i].text;
}
}
$("#autocompleteu_17605833").width($(mySelObju_17605833).width() + 5);
availableTagsu_17605833 = $.map(availableTagsu_17605833, function (v) {
return v === "" ? null : v;
});
$("#autocompleteu_17605833").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var a = $.grep(availableTagsu_17605833, function (item, index) {
var items = item.split(" ");
for (i = 0; i < items.length; i++) {
if (matcher.test(items[i])) return matcher.test(items[i]);
}
return matcher.test(item);
});
response(a);
},
close: function (event, ui) {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
}
});
});
$("#autocompleteArrowu_17605833").click(function () {
$("#autocompleteu_17605833").autocomplete("search");
$("#autocompleteu_17605833").focus();
});
$("#autocompleteu_17605833").focusout(function () {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
//$(this).autocomplete("close");
});
I want to find value selected in the hidden select box!
I tried to do the following
$("#autocompleteu_17605833").on("click", function (event) {
$((this.id).substring((this.id).indexOf("_") - 1)).attr("onchange", function (event) {
var selece = this.value;
alert(selece);
});
});
$("#autocompleteu_17605833").next().on("click", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Click on Arrow" + selectedValue);
});
$("#autocompleteu_17605833").on("change", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Changing the value" + selectedValue);
});
what I'm getting is older value where as I need the current assigned value.
How to achieve this??
WORKING DEMO
If am not wrong you want the selected value for this you can use select method
select:function(event,ui) {
alert("You have selected "+ui.item.label);
alert("You have selected "+ui.item.value);
}
This is a simple piece of code that will work as you required.
function result(){
document.getElementById("result").innerHTML= document.getElementById("u_17605833").value;
}
<html>
<head>
</head>
<body>
<div>
<select id="u_17605833" name="u_17605833" >
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
<input type="button" value="Show the result" onclick="result()"/>
</div>
<div id="result"></div>
</body>
</html>

Categories

Resources