Jquery send result of SUM to div - javascript

I want to:
Get value from select, sum with other values, and place it inside a span.
Can I send the result of a value to a div/span without having to submit with a button? Is that possible?
please look at my fiddle: https://jsfiddle.net/groseler/3mq1ye1y/
HTML
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
});
$("#result").html(resultSum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
Result should appear here ---> <span id="result" ></span></div>

Your code works after a bit change. You have only some typo. You need to add the $("#result").html(resultSum) into the change callback.
You don't need to submit anything. Submit is for the forms and after submitting the data almost always go to the server side code
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
$("#result").html(resultSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
<span id="result" ></span></div>

Put $("#result").html(resultSum); inside the function
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
$("#result").html(resultSum);
});
});
JSFIDDLE

The mistake you have done is that you put $("#result").html(resultSum); this outside the change event of dropdown.

Move $("#result").html(resultSum); statement to within .change() so the the sum can be changed every time the value of the select element changes.
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
$("#result").html(resultSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
Result should appear here ---> <span id="result" ></span></div>

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

get multiple var in a function by find()

I am trying to create a calculation with two selected option and input. Like when you select 'a' and 'd' then input=1 it give result 75. I wrote a jquery code but it doesn't work . I can't find any error on console .Please check it below :
$(window).load(function(){
function doStuff() {
var uone= $("#ud").children(":selected").attr("id") == 'a';
var utwo= $("#ud").children(":selected").attr("id") == 'b';
var uthree= $("#ud").children(":selected").attr("id") == 'c';
var bone= $("#bt").children(":selected").attr("id") == 'd';
var btwo= $("#bt").children(":selected").attr("id") == 'e';
var getvalue;
if ($(uone).find(bone)) {
getvalue = 75;
}
if ($(uone).find(btwo)) {
getvalue = 70;
}
if ($(utwo).find(bone)) {
getvalue = 81;
}
if ($(uthree).find(bone)) {
getvalue = 79;
}
var shw = $('#inputamount').val();
var total = getvalue * shw ;
$("#totalop").html(total);
}
$("#inputamount").on('keyup', doStuff);
$("#ud").on('change', doStuff);
$("#bt").on('change', doStuff);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<select name="sucompn" id="ud">
<option id="a">a</option>
<option id="b">b</option>
<option id="c">c</option>
</select>
<select name="ducompn" id="bt">
<option id="d">d</option>
<option id="e">e</option>
</select>
<input autocomplete="off" name="inputamount" id="inputamount" value="" type="text">
<span id="totalop"></span>
don't use id use value for the options
<select name="sucompn" id="ud">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select name="ducompn" id="bt">
<option value="d">d</option>
<option value="e">e</option>
</select>
then you can get the values like
var selectedUd = $("#ud").val();
var selectedBt = $("#bt").val();
then you can do:
var uone = selectedUd== 'a';
var utwo = selectedUd == 'b';
var uthree = selectedUd == 'c';
var bone =selectedBt == 'd';
var btwo =selectedBt== 'e';
then (I don't really know what you wanted to do here ) but you could do things like
var getValue;
if(uone && bone) getvALUE =75;
else if(uone && btwo) getValue = 70;
else if(utwo && bone) getValue = 81;
...here rthe rest of posibilities
var shw = $('#inputamount').val();
var total = getvalue * shw;
$("#totalop").html(total);
Here is the Plunker - Sample
You have defined var getValue;, but use in code another variable getvalue = 75;(getValue and getvalue are not the same). Probably you have undefined variable and this problem usually yields no console info.

How can i save this script to Local Storage

I want simply save changes that i've made with main text heading, changed color/font-size/font using Local Storage. So after page reload changes will stay at browser. How could i make this?
Html:
<div class="main_text">
<h1>Change Headings</h1>
</div>
<select id="selection">
<option value="h1">H1</option>
<option value="h2">H2</option>
<option value="h3">H3</option>
<option value="h4">H4</option>
<option value="h5">H5</option>
</select>
<div class="color_picker">
<h3>Choose Text Color</h3>
<input type="color" id="color_picker">
</div>
<div class="change_font">
<h3>Change Font</h3>
<select id="select_font">
<option value="Sans-serif">Sans-serif</option>
<option value="Monospace">Monospace</option>
<option value="Serif">Serif</option>
<option value="Fantasy">Fantasy</option>
<option value="Verdana">Verdana</option>
<option value="Impact">Impact</option>
</select>
</div>
<div class="change_size">
<h3>Font Size</h3>
<select id="change_font_size">
<option value="14">14</option>
<option value="18">18</option>
<option value="22">22</option>
<option value="24">24</option>
<option value="26">26</option>
</select>
</div>
JQuery:
$('#selection').change(function () {
var tag = $(this).val();
$(".main_text").html("<" + tag + ">Change Headings</" + tag + ">");
});
$('#color_picker').change(function() {
var color_p = $(this).val();
$('.main_text').css("color", color_p);
});
$('#select_font').change(function () {
var change_font = $(this).val();
$(".main_text").css("font-family", change_font);
});
$("#change_font_size").change(function() {
var font_size = $(this).val();
$('.main_text > *').css("font-size", font_size + "px");
});
JSfiddle
DEMO
$(document).ready(function () {
var tag = localStorage.tag || $('#selection').val();
var color = localStorage.color || $('#color_picker').val();
var font = localStorage.font || $('#select_font').val();
var size = localStorage.font_size || $('#change_font_size').val();
$('.main_text').css({
"color": color,
"font-family": font,
"font-size": size
}).html("<" + tag + ">Change Headings</" + tag + ">");
$('#selection').val(tag);
$('#color_picker').val(color);
$('#select_font').val(font);
$('#change_font_size').val(size);
$('#selection').change(function () {
var tag = $(this).val();
localStorage.tag = tag;
$(".main_text").html("<" + tag + ">Change Headings</" + tag + ">");
});
$('#color_picker').change(function () {
var color_p = $(this).val();
localStorage.color = color_p;
$('.main_text').css("color", color_p);
});
$('#select_font').change(function () {
var change_font = $(this).val();
localStorage.font = change_font;
$(".main_text").css("font-family", change_font);
});
$("#change_font_size").change(function () {
var font_size = $(this).val();
localStorage.font_size = font_size;
$('.main_text > *').css("font-size", font_size + "px");
});
});
Add this code after your JS code:
$(document).ready(function () {
//load values if found
if (localStorage.getItem("selection") != null) {
$('#selection').val(localStorage.getItem("selection")).trigger("change");
}
if (localStorage.getItem("color_picker") != null) {
$('#color_picker').val(localStorage.getItem("color_picker")).trigger("change");
}
if (localStorage.getItem("select_font") != null) {
$('#select_font').val(localStorage.getItem("select_font")).trigger("change");
}
if (localStorage.getItem("change_font_size") != null) {
$('#change_font_size').val(localStorage.getItem("change_font_size")).trigger("change");
}
});
Here is the JSFiddle demo

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

change event in jquery

I need the total price from ( the base value + logo value + material value )
I had tried this code mycode
condition
1) if select the logo type and material type i need to get the total value.
2) if i selected both the value, now am changing the logo value i need to get the correct total
3) total to be displayed after selecting each option dynamical
4) no submit button to be used.
HTML
<p class="logotype left customLabel"><span>base price :</span>1000</p>
<p class="logotype left customLabel"><span>Logo Type :</span></p>
<form class="left margin0" name="logotypeform" method="post">
<select name="logoprice" id="logotypeprice">
<option value="">--</option>
<option value="50">Default logo</option>
<option value="100">Imported logo</option>
<option value="25">Text</option>
<option value="0">None</option>
</select>
</form>
<input class="logoTypeVal" type="" value="">
<p class="Material left customLabel"><span>Material :</span></p>
<form class="left margin0" name="priceform" method="post">
<select name="price" id="materialprice">
<option value="">--</option>
<option value="10">Nylon</option>
<option value="20">Sticker</option>
<option value="30">Printed</option>
<option value="30">Embroiding</option>
<option value="0">None</option>
</select>
</form>
<input class="materialVal" type="" value="">
<p class="Material left customLabel"><span>Total Value :</span></p><input class="totalVal" type="" value="total value">
JS
jQuery(document).ready(function(){
var baseValue = 1000;
jQuery('#logotypeprice').change(function(){
var logotypeprice = jQuery(this).val();
jQuery('input.logoTypeVal').val(logotypeprice);
});
jQuery('#materialprice').change(function(){
var materialprice = jQuery(this).val();
jQuery('input.materialVal').val(materialprice);
var baseprice = "<?php echo $basePrice ?>";
var logoval = logotypeprice;
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logoval);
alert(totalprice);
jQuery('input.totalVal').val(totalprice);
});
});
Update:
Since you need the total value to update based on changing each select you should calculate the total on both handlers. Like below
var baseValue = 1000,
logotypeprice = 0,
materialprice = 0;
$(document).ready(function () {
$('#logotypeprice').change(function () {
logotypeprice = jQuery(this).val();
$('input.logoTypeVal').val(logotypeprice);
calculateTotal();
});
$('#materialprice').change(function () {
materialprice = $(this).val();
$('input.materialVal').val(materialprice);
calculateTotal();
});
});
function calculateTotal() {
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logotypeprice);
$('input.totalVal').val(totalprice);
}
Here is an updated demo
PS: Instead of writing jQuery for each element you can use the short version $
You are trying to access logotypeprice variable which is not accessible inside materialprice change handler
Either declare logotypeprice globally like this
var baseValue = 1000;
var logotypeprice;
jQuery('#logotypeprice').change(function(){
logotypeprice = jQuery(this).val();
jQuery('input.logoTypeVal').val(logotypeprice);
});
jQuery('#materialprice').change(function(){
var materialprice = jQuery(this).val();
jQuery('input.materialVal').val(materialprice);
var baseprice = "100";
var logoval = logotypeprice;
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logoval);
alert(totalprice);
jQuery('input.totalVal').val(totalprice);
});
Or
access logo value from input.logoTypeVal or #logotypeprice value like this
jQuery('#materialprice').change(function(){
var materialprice = jQuery(this).val();
jQuery('input.materialVal').val(materialprice);
var baseprice = "100";
var logoval = jQuery('input.logoTypeVal').val(); // OR logoval = jQuery('#logotypeprice').val();
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logoval);
alert(totalprice);
jQuery('input.totalVal').val(totalprice);
});
Here is a demo

Categories

Resources