I have set up a function to take care of my metric conversion an it's not so seamless. I would like to convert lbs to kg and kg to lbs. The problem that i am having is using the jquery change function. It's causing the conversion to only happen on a change but sometimes i just want to due back to back conversions from lbs to kg and it gets stuck and convert the lbs to more lbs or kg to more kg. Any help is appreciated. here is my code below
$("#wUnits").change(function () {
var approx = 2.2;
if ($(this).val() == "lbs") {
value = $("#txtWeight").val() / approx;
$('#wValue').val(value.toFixed(2));
} else if ($(this).val() == "kg") {
value = $("#txtWeight").val() * approx;
$('#wValue').val(value.toFixed(2));
} else {
var value = "";
$('#wValue').val(value);
}
});
and below is my markup
<select id="wUnits">
<option value="">--</option>
<option value="lbs">lbs</option>
<option value="kg">kg</option>
</select>
Ideally what i would like to acheive is a seamless transition between conversions using a dropdown.
What I understand is that you want the conversion to happen not just when you change the value of the <select>
I changed your code a little, it's good to cache the variables in this case, also, I separated the function code to a function named conversion that is triggered on both the <select> change and on keyup or change on your #txtWeight input.
EDIT, implementing Jason Sperske's idea, and added an extra <span> with the resulting units, to avoid confusion. It should be:
HTML:
Convert <input type="text" id="txtWeight" />
<select id="wUnits"><br>
<option value="0">--</option>
<option value="0.45359237">lbs</option>
<option value="2.2">kg</option>
</select><br>
Result: <input type="text" id="wValue" /><span id='rUnits'
JS:
var $units = $("#wUnits");
var $wvalue = $('#wValue');
var $txtweight = $("#txtWeight");
var $runits = $('#rUnits');
$units.change(conversion);
$txtweight.on('keyup change',conversion);
function conversion () {
var value = $txtweight.val() * $units.val();
if(value !== 0) {
$wvalue.val(value.toFixed(2));
$runits.text($units.children(':gt(0):not(:selected)').text());
} else {
$wvalue.val("");
$runits.text('');
}
}
JSBin Demo
Related
I have the code for a form with some drop down menus with different options in it and I have also create alert pop up message so that they cannot select same planet now. I also have disable one input on one textbox for input because I only can put one input.
My question is how do I calculate the weight of the planet based on the dropdown box I selected? And also print/ display it on the input type means if I select earth and my input type (weight) is 60N, if my second select is Venus it will calculate the weight for me and print / display it to input type.
Below is roughly my HTML code and JavaScript code. I'm new to JavaScript.
html :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">Earth</option>
<option value="1">Venus</option>
<option value="2">Mars</option>
<option value="3">Jupiter</option>
<input type="text" name="123" id="text1"
onchange="process_selection(this)" placeholder=""> N
</select>
<br>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">Earth</option>
<option value="1">Venus</option>
<option value="2">Mars</option>
<option value="3">Jupiter</option>
<input type="text" name = "123" id="text2"
onchange="process_selection(this)" placeholder=""> N
</select>
javascript :
<script type="text/javascript">
function process_selection(obj)
{
var input1 = document.getElementById("select1").value;
var input2 = document.getElementById("select2").value;
var texta = document.getElementById("text1");
var textb = document.getElementById("text2");
if(input1 == input2)
{
alert("Please select other planet");
}
if(texta.value != "")
{
document.getElementById("text2").disabled = true ;
}
if(textb.value != "")
{
document.getElementById("text1").disabled = true ;
}
// var xx = input1.options[input1.selectedIndex].value;
var SurfaceGravityEarth = 1;
var SurfaceGravityVenus= 0.907;
var SurfaceGravityMars= 0.377;
var SurfaceGravityJupiter= 2.364;
var weight1 , weight2;
// var sg1;
// var sg2;
if (input1 == "0" )
{
weight1 = document.getElementById("text1") * SurfaceGravityEarth;
}
if (input2 == "1" )
{
weight2 = document.getElementById("text1") * SurfaceGravityVenus ;
document.getElementById("text2").value= weight2 ;
}
}
I'm stuck at the calculation part.
first, get the value of textbox and convert it to number type (integer, float etc).
Try the following code:
weight1 = parseInt(document.getElementById("text1").value) * SurfaceGravityEarth;
use parseInt() to convert to integer type.
if you want to convert to float type use parseFloat()
or you can simply use Number() method for both integer and floating point numbers
Good day.
I need to copy what's being typed into a textbox to multiple other text boxes.
The catch is that there is a dropdown which must determine this.
The process: User will enter a "Commodity" into the "Commodity" text box.
After this, they will then select from a dropdown the number of "Delivery Places". If they choose "1"; textbox "Commodity1" will have the same contents as the main "Commodity" textbox.
If they choose "2" as "DeliveryPlaces", both "Commodity1" & "Commodity2" will have the contents typed into "Commodity". This process should follow until "5" for "DeliveryPlaces".
The reason I want it done like this is that most of our clients will only order one type of commodity, even though it will be transported to multiple locations;
function copy(){
if (document.getElementById("DeliveryPlaces").value = "1")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "2")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "3")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "4")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
document.getElementById("Commodity4").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "5")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
document.getElementById("Commodity4").value=document.getElementById("Commodity").value;
document.getElementById("Commodity5").value=document.getElementById("Commodity").value;
}
else
{
document.getElementById("Commodity1").value="";
document.getElementById("Commodity2").value="";
document.getElementById("Commodity3").value="";
document.getElementById("Commodity4").value="";
document.getElementById("Commodity5").value="";
}
}
<p>
Commodity
</p><input type="textbox" id="Commodity" onkeyinput="copy();">
<p>
Commodity1
</p><input type="textbox" id="Commodity1">
<p>
Commodity2
</p><input type="textbox" id="Commodity2">
<p>
Commodity3
</p><input type="textbox" id="Commodity3">
<p>
Commodity4
</p><input type="textbox" id="Commodity4">
<p>
Commodity5
</p><input type="textbox" id="Commodity5">
<p>
Delivery Places
</p>
<select style="width:50px;" id="DeliveryPlaces">
<option value="-">-</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>
</select>
so by filling it in automatically we save the user some time.
I managed to get it working without the if conditions, that was simple enough. Now, however, it's only filling in "Commodity1" even though I choose a "DeliveryPlace" which IS NOT "1".
Any help would be appreciated.
Switch:
if (document.getElementById("DeliveryPlaces").value = "1")
to
if (document.getElementById("DeliveryPlaces").value == "1")
The code is actually switching DeliveryPlaces to 1 in your statement
Try using:
var e = document.getElementById("DeliveryPlaces")
var selection = e.options[e.selectedIndex].value;
Then do your condition based on the value in selection.
you are currently selecting the value of the Select element not the option you have actually selected.
Edit: it may be text rather than value you need on your selection, but give it a go!
I would do it like this:
function copy() {
var e = document.getElementById("DeliveryPlaces")
var selection = parseInt(e.options[e.selectedIndex].value);
var input = document.getElementById("Commodity").value;
var field;
for (var i = 1; i < 6; i++) {
field = "Commodity" + i;
if (i <= selection) {
document.getElementById(field).value = input;
} else {
document.getElementById(field).value = "";
}
}
}
This way, you can clear the other commodities, when you change to a lower delivery place + you can easily add more by editing the for loop.
Your function should receive the number of the dropdown. That is, if you selected 2 copy (2) so you can use a for and go through the ones you want to fill
for (i = item.length; i = 0; i--) {
document.getElementById("Commodity"+i).value=document.getElementById("Commodity").value;
}
The for will go from low to high until it reaches 0. that means that it will count if it is 5. 5,4,3,2,1 and will fill all the fields that you want. This avoids the amount of spaghetti code you have in your structure.
I understand that you are using pure javascript. But you could use jquery and it would make the job easier.
I have a specialized e-commerce cart I built where the customer selects how many of rooms, floors, etc. from a table and then it calculates the value live.
Html table entries for each drop down option looks like this
<table>
<td><select onchange="calculateall()" id="roomsclear1" 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>
</select> </td>
</table>
<h1> Total:<h1> <p id="total"> Final Value goes here after calculation of all 20 options</p>
Each type of cleaning service unfortunately has a different price point so I tried this switch statement.
var selectedt = document.getElementsByTagName('select');
function calculateall() {
for (var i = 0; i < selectedt.length; ++i) {
var calcit = selectedt.options[selectedt[i].selectedIndex].value;
var typeid = selectedt[i].id;
switch (typeid) {
case 'roomsclean1':
calcit = calcit * 65;
break;
}
document.getElementById("total").innerHTML = calcit;
}
}
Questions:
I'm only getting a 0 or 1 value written to total in HTML no matter what option I select from the table. I assume I'm screwing up on the Javascript.
Is a switch statement the most efficient option? 20+ options each with different pricing per # of rooms selected
I put an example of the cart on a temporary page here(slow!):
52.11.14.57:9000/#
JSfiddle: https://jsfiddle.net/mvc1poad/
The ID in the example correspondes to carpet cleaning tabs: rooms(clean)
Edit: Rakesh_Kumar is correct, the issue is the lack of parseInt. Adding that should address the issue when calculating values.
You mentioned you can output the actual values (which I'd recommend since it will simplify your script slightly). Personally, I would wrap an element around your select element(s) and allow a change event to bubble up (rather than an inline event handler like calculateall - just cleans up your HTML).
Something like:
<form id="ourForm">
<select id="cleaning">
<option value="0">Select cleaning</option>
<option value="0">No cleaning</option>
<option value="10">Cleaning final day only</option>
<option value="50">Cleaning 5 days</option>
</select>
<!-- additional elements here -->
</form>
And a simple JS event listener like this:
document.forms[0].addEventListener('change', function(e) {
var i = 0,
query = this.querySelectorAll('select'),
len = query.length,
total = 0;
for(; i < len; i++) {
if (parseInt(query[i].value, 10) > 0) {
total += parseInt(query[i].options[query[i].selectedIndex].value, 10);
}
}
// Do something with total here
}, true);
Here's a demo fiddle: http://jsfiddle.net/sj9o6Lnb/
If you're interested in using a multiplier, you could create a map which you then multiply the values by. Something like:
var price_map {
rooms_clean: 65,
breakfast: 100
}
Which you then reference the price by an id (or some other attribute)
for(; i < len; i++) {
total += price_map[query[i].id] * parseInt(query[i].options[query[i].selectedIndex].value, 10);
}
http://jsfiddle.net/sj9o6Lnb/1/
Here's an updated fiddle based on your site (with the four options and clean/protect): http://jsfiddle.net/sj9o6Lnb/2/
And an edited fiddle that you created: https://jsfiddle.net/mvc1poad/1/ (this one here just calculates based on a data attribute, which you would need to add)
You have made a silly mistake, because of which you are not getting expected output.
Instead of doing like:
//selectedt is HTMLCollection having list of all elements with tag "select"
//& typeof calcit is String, which you need to make a number before multiplying with 65
var calcit = selectedt.options[selectedt[i].selectedIndex].value;
do,
var calcit = parseInt(selectedt[i].options[selectedt[i].selectedIndex].value);
And, apart from switch usage, what other approach you are thinking to take. For Obvious reasons, switch is more preferable than if-else.
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>
Quick question on the .data() in jQuery: My variable "valone" reaches into a dropdown menu within some HTML for the "data-whatever" value in the dropdown and then plugs it into the jQuery equation. But it also seems to be getting the "option value" value from the dropdown and includes it into the math somehow, even though I don't specify it to do so...
var valone = $('#os0 option:selected').data('whatever');
Am I missing something in this .data() function? Or do I have something extra that is not necessary?
(I have the complete jQuery and HTML below.)
jQuery
$(document).ready(function(){
var valone = $('#os0 option:selected').data('whatever');
var valtwo = $('#os1').val();
var valthree = $('#os2').val();
var total = ((valone * 1) * (valtwo * 1) * (valthree * 1));
$('.calc').each(function(){
if($(this).val() != '')
{
total += parseInt($(this).val());
}
});
HTML
<select style="width: 190px;" class="calc"
name="os0" id="os0" type="text">
<option value="250" data-whatever="5">250
</option>
<option value="500" data-whatever="6">500 </option>
<option value="1000" data-whatever="7">1000
</option>
<option value="2000" data-whatever="8">2000
</option>
<option value="5000" data-whatever="9">5000
</option>
</select>
Any help or advice would be greatly appreciated!
.data is retrieving the correct value. The problem occurs with this piece:
$('.calc').each(function(){
if($(this).val() != '')
{
total += parseInt($(this).val());
}
});
The variable total is computed above this point is what you expect. .each is iterating over each select element again and adding the selected value to the total.
In answer to your question, you are missing nothing. Data stores one thing, the value set to it, either the hardcoded value in the element attribute, or the one set via jquery. What is the point in doing valone * 1, why not just valone? you are over complicating it. It should be
var total = valone * valtwo * valthree;
or
var total = (valone * valtwo) * valthree`; //valone will be multiplied with valtwo first before multiplying that total with valthree
Depending on what you are calculating.