How to count option values from different select options? - javascript

I have searched the web for answers and find none that I needed. So to the question. I am making a submit form (user selects fields and types an input number to determine the price of an order) which have 2 different select option fields and 1 input field.
<input type="text" id="number" placeholder="please enter a number">
(user entered 35 for example)</input>
<select id="firstpick">
<option value="50">Option 1</option>
<option value="150">Option 2</option>
<option value="100">Option 3</option>
</select>
<select id="secondpick">
<option value="10">Option 4</option>
<option value="15">Option 5</option>
<option value="20">Option 6</option>
</select>
<input disabled="disabled" type="text">(The total sum)</input>
I want to count sum of values for example: firstpick.option3 + (secondpick.option4 * number.35). In other meaning: 100 + (10 * 35) = 450. And I want to get that sum in a different disabled input field, so I can save it in database and show it to the user what is the total cost of an order by fields he selected and by number he typed in.
EDIT: The working code for you (the visitor)! http://jsfiddle.net/LoLd748n/4/

I am not entirely sure what you goal is, but this might be close. jQuery will be helpful.
function getSum() {
first = $("#firstpick").val();
second = $("#secondpick").val();
sum = first + second
return sum
}
It may be a good idea to add an event listener to your selects. This way your field will automatically update.
You do not have to have a disabled input, it could be type="hidden" instead. Then it will not show up on the page.
$("#firstpick").on("change", function() {
sum = getSum();
$("#my-hidden-input").val(sum);
});
$("#secondpick").on("change", function() {
sum = getSum();
$("#my-hidden-input").val(sum);
});

Related

How do you add data to an option tag?

I'd like to add a data value to an option tag in a select element. For example data-price but my problem is that I have multiple select tags. So how do I get JavaScript to grab the data value of that option that the user selects?
How I want it to work:
Select element #1 contains:
<select onchange="updatePrice()">
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
Select element #2 contains:
<select onchange="updatePrice()">
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
Then I'm honestly not sure what to do in the JS... But I want it to grab what the user selected, get the data-price then calculate the total (just by adding select1 + select2).
EDIT: My answer is different than this question because my question is more specific and requires different methods. Even though this is specific it could help a developer in the future by the answers it gets. Therefore it is not a duplicate but a more specific question than the other. Though that question has a simpler answer that could be plugged in if the developer knows how to.
Here is some code matching your discription. A few notes: Use the value attribute to get direct access to the option value from the select element. The unary operator (+) converts the two values from strings to a operatable numbers. The third div is just to show the output total value.
function updatePrice(){
var s1 = document.getElementById("option1");
var s2 = document.getElementById("option2");
var total = +s1.value + +s2.value;
document.getElementById("price").innerHTML = "Total: $" + total
// to get the text within the selected option
var h1 = s1.options[s1.selectedIndex].text;
return total;
}
<select id="option1" onchange="updatePrice()">
<option value="1">Apple $1</option>
<option value="2">Potato $2</option>
<option value="3">Bag of Grapes $3</option>
</select>
<select id="option2" onchange="updatePrice()">
<option value="5">Really good cake</option>
<option value="15">Super Good Cake</option>
</select>
<div id="price"></div>
Let me know if you need any further explanation. Cheers.
This is a bit tricky. You need to give an identifier so our code won't get confused.
<select id="goods1" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
<select id="goods2" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
First, add a global variable to storing current price. Second, store the identifier and the price value. Finally, manipulate the current price.
<script>
let price = 0;
let stored = {};
const updatePrice = elm => {
const id = elm.id;
const selectedPrice = parseInt(
Array.from(
elm.children
).filter(x => x.selected)[0].dataset.price
);
price = 0;
stored[id] = selectedPrice;
Object.keys(stored).forEach(key => price += stored[key]);
console.log(`Price: ${price}`);
};
</script>
Add some unique class to all selectbox whos valued need to be involved in total calculation like mul_ck
//when even a single selectbox change it will trigger re-calculation
$('.mul_ck').change(function(){
var total = 0;
//grab all _mul_ck_ and loop over them
$('.mul_ck').each(function(){
var selectValue = $(this).find(":selected").attr('data-price');
total += parseFloat(selectValue);
});
alert(total);
});

Count how many options a user chooses from multple selects

Let's say i've got 5 selects in an html form but you can only choose options from 3 of them. I need to accomplish the following: 1. calculate a total price, 2. dynamically pass set variables (that will eventually get passed to json for PHP) equal to the name attr of the selected options.
The problem i'm having is that i'm using value ="1" on every option. Then defining the price which is updated each time they select another option by statically assigning the variable with an if else. In what i'm doing each select has many options to choose from.
Where i'm stuck:
Either i'm going to use the name attribute and pass over 5 variables (using option:selected) or there is a way to accomplish this so my database only needs 3 columns to store to the database instead of 5.
I was hoping to accomplish this in the script on the page, rather than in the PHP. Can you do this dynamically and only send over 3 variables for JSON to pass off to the php or is this just going to be easier and faster to send over 5? Yes i'm very new to javascript and jquery :)
<form id = "testform" name = "testform" method="POST" action="test.php">
<select class = "choose" id="choice1">
<option value="0" selected=""></option>
<option value="1"> Choice 1.a</option>
</select>
<select class = "choose" id="choice2">
<option value="0" selected=""></option>
<option value="1"> Choice 1.b</option>
</select>
<select class = "choose" id="choice3">
<option value="0" selected=""></option>
<option value="1"> Choice 1.c</option>
</select>
<select class = "choose" id="choice4">
<option value="0" selected=""></option>
<option value="1"> Choice 1.d</option>
</select>
<select class = "choose" id="choice5">
<option value="0" selected=""></option>
<option value="1"> Choice 1.b</option>
</select>
<label><h4>Total:$</h4> <input style="" type="number" class="num" name="amount" value="0.00" readonly="readonly" /></label>
<script type="text/javascript">
$('select').change(function(){
var form = this.form;
var sum = 0;
var price;
$('select :selected').each(function() {
sum += Number($(this).val());
});
if (sum > 3) {
alert("You can only choose 3 classes");
$('select.choose').each(function() {
$('.choose').val(0);
});
}
if (sum == 1){
price = 80;
}
else if (sum == 2) {
price = 130;
}
else if (sum == 3) {
price = 180;
}
$(".num").val(price);
form.elements['total'] = price;
});
Check how many selects have a value of something other than 0, make sure it's not more than 3, then get the name of those selects
$('select').on('change', function(){
var selected = $('select').filter(function() {
return parseInt(this.value, 10) !== 0;
}),
sum = selected.length,
price = [80, 130, 180][sum - 1],
names = selected.map(function() {
return this.id; // selects don't seem to have names ?
}).get();
if (sum > 3) {
alert("You can only choose 3 classes");
} else {
$('.num').val(price);
}
console.log(names, sum)
});
FIDDLE

jquery show different value from the dropdown list

I having a dropdown like this
<select name="phoneCallingCode" id="phoneCallingCode" class="input">
<option value="93">Afghanistan (+ 93)</option>
<option value="355">Albania (+ 355)</option>
<option value="213">Algeria (+ 213)</option>
</select>
when I select a value Afghanistan (+ 93), I just want to show +93 in the display, it that possible through jquery.
Thanks in advance.
Okay from my understanding you want to show number when anyone selects country in drop down.
So you can do something like this:
$('#phoneCallingCode').change(function() {
$("option:selected", this).text($("option:selected", this).val());
});
But remember this will change selected option text too, so user may have hard time finding country name again.
Fiddle: http://jsfiddle.net/NyHts/
Working demo
Code
//For starting of page
valNum=$("#phoneCallingCode").val();
$("#nmbr").val(valNum);
$("#phoneCallingCode").change(function(){
valNum=$(this).val();
$("#nmbr").val(valNum);
});
It means,Get value of selected Drop down option and Set the value of Textbox by the value in valNum variable.
And when document is ready , u need contry Number in textbox so The code //For starting of page
Use as below
$('#phoneCallingCode').change(function() {
$("#ShowNumber").val("+" +$("#phoneCallingCode option:selected").val())
});
HTML
<select name="phoneCallingCode" id="phoneCallingCode" class="input">
<option value="93">Afghanistan (+ 93)</option>
<option value="355">Albania (+ 355)</option>
<option value="213">Algeria (+ 213)</option>
</select>
<input type="text" id="ShowNumber"/>
DEMO
$('#phoneCallingCode').change(function(){
var selectedOptionVal = $(this).val();
var temp = "[value='"+selectedOptionVal+"']";
var selected = $(temp).html();
if (selected.indexOf("(+") != -1) {
var selectedString = selected.substring(selected.indexOf("(+")+1,selected.length-1);
$(temp).html(selectedString);
}
});
You can accomplish this task using HTML5 data attribute as below:
<select name="phoneCallingCode" id="phoneCallingCode" class="input" onclick="resetPhoneCallingCode()" onblur="displayContryCode();">
<option value="93" data-text="Afghanistan (+ 93)">Afghanistan (+ 93)</option>
<option value="355" data-text="Albania (+ 355)">Albania (+ 355)</option>
<option value="213" data-text="Algeria (+ 213)">Algeria (+ 213)</option>
</select>
<script>
function resetPhoneCallingCode() {
$("#phoneCallingCode option").each(function () {
$(this).text($(this).attr('data-text'));
});
}
function displayContryCode() {
$("#phoneCallingCode option:selected").text("+" + $("#phoneCallingCode").val());
}
</script>

Trying to create a drop-down of form fields, that is based on a number

Good afternoon!
I am building a contact form in Contact Form 7 in Wordpress. And I need a functionality where one of the form fields is a number selector (for example, 1-10) and I need the number that is selected to be calculated and drop down the number of fields to be inputted.
I'll try to explain the best I can. So if someone types in the 4...I need a drop down of four input fields.
I have looked for some jquery script for this functionality, but I'm basically at a deadend. If anyone has any suggestions, I would much appreciate it!
Here's an option using jQuery (jsFiddle)
HTML
Number of inputs:
<select class="numInputs" onChange="buildInputs(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div class="inputs"></div>
Javascript (jQuery)
$(document).ready(function () {
// set onchange event for the select box.
$('.numInputs').change(function () {
// clear any inputs added to the div.
$('.inputs').empty();
// get number of inputs to add from select box.
var num = $('.numInputs option:selected').text();
// build the inputs.
for (var i = 1; i <= num; i++) {
$('<input type="text"/><br/>').appendTo('.inputs');
}
})
});
You would use javascript, I wrote a simple sample for you. I haven't ever worked with wordpress, but this just works on it's own, and I would think you should be able to just put it in.
Javascript
<script type="text/javascript">
function thing(){
var num = document.getElementById("number").value; //Get the number out of the number field
document.getElementById("select").innerHTML = ''; //Get rid of the placeholder, or the old ones
for (var i = 0; i < num; i++){
var newOpt = document.createElement('option');
newOpt.innerHTML = i; //It'll just have a dropdown for 0 to the number
newOpt.value = i;
document.getElementById("select").appendChild(newOpt);
}
}
</script>
HTML
<form>
Number: <input type="number" name="number" id="number" onblur="thing();">
<select id="select">
<option value="no">Enter a number first</option>
</select>
<input type="submit" value="Submit">
</form>
Also, instead of using onblur, you could use onkeyup or something. onblur is for when it loses focus.

Multiply text values and display result

i am using below three fields need to multiply the Word Count Values through PHP. ANy Help ? Code as -- 1 have to select the first dropdown from here..
<select name="sp" id="sp">
<option value="" selected>Please Select...</option>
<option value="Editing">Editing</option>
<option value="Writing">Writing</option>
</select>
Then i have a text box in which the number would be provide,like word 100 200 300, as
<input type="text" name="Word_Count" id="Word_Count" size="10">
and third field would be where the price would be calculated on behalf on word from above row (100 200 300 word), as
<input type="text" name="price" id="price" value="" readonly="" size="20">
Now if the user will select the Editing from select box, the price would be calculated as 100 x 0.02, 200 x 0.02, 300 x 0.02 like and the user will select the Writing, the price would be calculated at 100 x 0.04, 200 x 0.04, 300 x 0.04.
HOw can i make the sense to get the output more efficiently ? Any help ?
There are many complication that you will have to handle.
1) Check that the string entered in Word_Count is number. (Never trust user input. Apply validation techniques)
2) call a javascript function on Onkeyup event of Word_Count.
<input type="text" name="Word_Count" id="Word_Count" size="10" onkeyup="return somefunction()">
I have shown you, how to call a function by mentioning it in element. You can also bing jquery function on pageload. Better check-out official documentation if you want it that way.
Html select
<select name="sp" id="sp">
<option value="" selected>Please Select...</option>
<option value="0.02">Editing</option>
<option value="0.04">Writing</option>
</select>
Changed the value of options.
javascript/jquery function
function somefunction(){
//take value of Word_Count in one variable
var valWC = $("#Word_Count").val()
//take value of Word_Count in one variable
var valDP = $("#sp").val()
//sumd will hold the product of two numbers
var sumd = 0;
//apply validation technique
//multiply both values valWC and valDP
//sumd will have the product
sumd=Number(valWC)*Number(valDP);
//show it in third box
$("#price").val(sumd);
}
you can do this in Jquery itself.. What you have to do is,
$("#sp").change(function() {
// get the word count field value;
// split the values by using " " character and store it into an array
// loop the array [ inside the loop do your calculation according to the selection of the choice ]
// display the final value in the price field..
});
There are the steps to achieve it.

Categories