JavaScript Math Operations and Inputting Into Text Field Live - javascript

I'm a little new to JS.
I'm attempting to take 3 text fields and add them and then multiply their value by a drop down field with a percentage in it. Once that's done I want it to populate the final text field with a value.
So far I haven't even been able to get the text to display in the final field much less add it together. I'd appreciate it if anyone could help point me in the right direction.
Our Buying Cost:
<input id="buying_cost" name="buying_cost" type="text" />
<br/>Our Shipping Cost:
<input id="shipping_cost" name="shipping_cost" type="text" />
<br/>Our Tax Cost:
<input id="tax_cost" name="tax_cost" type="text" />
<br/>Our Markup:
<select id="markup" name="markup" value="">
<option value="0">0%</option>
<option value="10">10%</option>
<option value="20">20%</option>
<option value="30">30%</option>
<option value="40">40%</option>
<option value="50">50%</option>
<option value="60">60%</option>
<option value="70">70%</option>
<option value="80">80%</option>
<option value="90">90%</option>
<option value="100">100%</option>
</select>
<br/>
<p>New Selling Price:</p>
<input type="text" id="new_sell_price" name="new_sell_price" value="">
$("#buying_cost,#shipping_cost,#tax_cost,#markup).change(function ()
{
var addressArray = [$("#buying_cost").val(), $("#shipping_cost").val(), $("#tax_cost").val(), $("#markup").val()];
$("#new_sell_price").text(addressArray.join(' '));//<--I would like this to be adding all the values
}
);
I've included the work here at this JSFiddle
jsfiddle.net/new2programming/hy99yu2m/
Thanks for any help!

Here a clean and simple solution for your problem: on JSFiddle
But pay attention, you should not copy-paste this code if you don't really understand what exactly it does!
First of all, register the events:
// I recommend jQuery.on(...) on the document
$(document).on('input', 'input', calculate);
$(document).on('change', 'select,input', calculate);
// use the 'input' event for a live update
// and the 'change' value for a secure update
(You can replace 'input' and 'select,input' with the jQuery-selector of your elements if you want so, read the documentation)
In the next step, you fill your array with all your values:
var values = [
$("#buying_cost").val(),
$("#shipping_cost").val(),
$("#tax_cost").val(),
$("#markup").val()
];
Now you can addition all the values in the array:
var total = eval( values.join('+') );
// the eval function calculates the given string (generated by the join function)
And for the last step, you set the calculated value:
$("#new_sell_price").val(total);
// use 'val(...)' and not 'text(...)' because you want to set the value and not the text!

Related

Put select value to input field and then submit using JS or jQuery

I have a form in the CMS which has only one input (text type) and I cannot add additional fields to it (I don't have access to the DB), so what I want is to create select options near the field and add selected options values to the input field.
Let say I have this code:
<input type="text" placeholder="Your name" />
<select id="yourAge">
<option disabled>your age</option>
<option value="18">18</option>
<option value="19">19</option>
</select>
<select id="yourHeight">
<option disabled>height</option>
<option value="180 cm">180 cm</option>
<option value="190 cm">190 cm</option>
</select>
And this is how it must display after submition. The form submits the posts and works fine. This select tags should not touch any DB part or anything else. It only needs to get the values, insert to that inout text field and then show it.
And is it possible to show the values in special order like this?:
Name: Bla Bla
Age: 18
Height: 180 cm
Or at least like this:
Bla Bla, age 18 years old, height 180 cm
How can I do this using JavaScript or jQuery?
By the way my APP works based on nodeJS and MongoDB.
Thanks in advance.
Are you trying to get all of the fields to get added to the name field? It would be a good idea to create another input for the name and give it a unique identifier to distinguish it from the other input where you will be adding all of the information to.
I would create a function that handles transfering the values from your input and select fields to the input field provided. I would call this function on submit, adding the values to the provided input before the form submission.
Here it is on Codepen:
https://codepen.io/MattStillwater/pen/pogVeRp
This is the setField() function that I created for adding the values to the provided field:
function setField() {
var nameVal = jQuery('#yourName').val() +', ';
var ageSelectVal = jQuery('#yourAge').val() +', ';
var heightSelectVal = jQuery('#yourHeight').val();
var inputField = jQuery('input[type=text]').not(document.getElementById('yourName'));
inputField.val(nameVal + ageSelectVal + heightSelectVal);
}
This is the HTML that I am using:
<div class="section" id="yourField">
<input type="text" placeholder="Your name" id="yourName" />
<select id="yourAge">
<option>your age</option>
<option value="18">18</option>
<option value="19">19</option>
</select>
<select id="yourHeight">
<option>height</option>
<option value="180 cm">180 cm</option>
<option value="190 cm">190 cm</option>
</select>
</div>
<form action="#" class="section" id="formFields">
<input type="text" /> <!-- The endpoint -->
<input type="submit" value="Submit" />
</form>
The function is being called on submit event:
jQuery('input[type=submit]').submit(function() {
setField();
});
Welcome to SO, this is not a writing service website, so please next time do your own research first and ask when you get stuck. Combination of this things I wrote is all over this website with examples.
You could have searched for exactly what you need:
-How to get values of HTML elements.
-How to add values to elements.
-How to do this on some event.
var input = document.getElementById("in");
var sel1 = document.getElementById("yourAge");
var sel2 = document.getElementById("yourHeight");
sel1.onclick = function(){
sel1 = document.getElementById("yourAge");
var selected = sel1.options[sel1.selectedIndex].value;
input = document.getElementById("in");
input.value="Name: "+input.value+", Age: "+selected;
};
sel2.onclick = function(){
sel2 = document.getElementById("yourHeight");
var selected = sel2.options[sel2.selectedIndex].value;
input = document.getElementById("in");
input.value=input.value+", Height: "+selected;
};
<input type="text" id="in" placeholder="Your name" size="35"/>
<select id="yourAge">
<option disabled>your age</option>
<option value="18">18</option>
<option value="19">19</option>
</select>
<select id="yourHeight">
<option disabled>height</option>
<option value="180 cm">180 cm</option>
<option value="190 cm">190 cm</option>
</select>

Select-List displays Keys instead of values

I have a stange phenomenon where I'm stuck at the moment as I don't know where the error comes from.
My code is like this:
<input id="selectClassInput" name="selectClass" list="selectClass" type="text" >
<datalist id="selectClass">
<option value="DUMMY1">0</option>
<option value="s">24</option>
<option value="d">25</option>
</datalist>
My problem is with displaying the datalist. If I click on the arrow I'm getting only the numbers like here:
After selecting for example '25' I'm getting the value 'd'. That is correct BUT I don't want to display the numbers. Instead I want to display the value of this datalist in this drop-down field.
If I do something like this:
<input id="selectClassInput" name="selectClass" list="selectClass" type="text" >
<datalist id="selectClass">
<option value="DUMMY1">DUMMY1</option>
<option value="s">s</option>
<option value="d">d</option>
</datalist>
I'd naturally get the correct display, but I would like to add the ID, so that I can bind the click event with the ID of the selection and not the label.
You can make use of data attribute to find the id of option clicked from the list and keep value as labels,
see below code
$(function(){
$('#selectClassInput').on('change', function(e){
var val = $(this).val();
var id = $('#selectClass').find('option[value="' + val + '"]').data('id');
console.log(id);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="selectClassInput" name="selectClass" list="selectClass" type="text" >
<datalist id="selectClass">
<option value="DUMMY1" data-id="0">DUMMY1</option>
<option value="s" data-id="24">s</option>
<option value="d" data-id="25">d</option>
</datalist>

JavaScript - output value from dropdown menu more than once?

I'm in the middle of the process to create a very simple tool that allows my group to select a conference place. I'm getting some issues and hope I can receive some suggestions and help from you.
I have a dropdown menu, it allows user to select the conference location and it will display in text. For example:
HTML
<select onchange="changed('list_1')" id="list_1" class="travel" />
<option selected disabled>Select Place</option>
<option value="New York">New York</option>
<option value="Pennsylvania"> Pennsylvania</option>
<option value="Boston">Boston</option>
<option value="Washigton DC">Washigton DC</option>
</select>
JavaScript
function changed(listId) {
var list = document.getElementById(listId);
document.getElementById("val_"+listId).innerHTML = list.value;
}
document.getElementById("val_list_1").innerHTML = document.getElementById("list_1").value;
Below is the output I am looking for:
You select New York as the conference location. Please make sure you confirm with supervisor before you attend the conference in New York.
When selecting "New York", the value is successfully displayed between You select "Value" as the conference location. Unfortunately because document.getElementById can only be used once, so I'm unable to get the same value "New York" to output in the second sentence.
I was wondering if any of you can show me an example or give me some ideas of how I can select the value only once from dropdown but the value will display in multiple areas?
Any help would be greatly appreciated
You don't have a limit of using the value of an element, here is a simple solution to your problem :
Use a simple template for the text you want to display :
var textTemplate = 'You select {CITY} as the conference location. Please make sure you confirm with supervisor before you attend the conference in {CITY}.';
function changed(list_id){
var cityName = document.getElementById(list_id).value;
document.getElementById('outputTest').innerHTML = textTemplate.split('{CITY}').join(cityName);
}
this suppose you have an html code like :
<select onchange="changed('list_1')" id="list_1" class="travel" />
<option selected disabled>Select Place</option>
<option value="New York">New York</option>
<option value="Pennsylvania"> Pennsylvania</option>
<option value="Boston">Boston</option>
<option value="Washigton DC">Washigton DC</option>
</select>
<p id="outputTest"></p>
Well, first off you are mistaken about only being able to use document.getElementById once, there is no such restrictions and I have no idea why you would think there was.
That said, the way to get the value and then use it more than once is to store it in a variable.
Fix the opening tag so it is not self closing. Also change the onchange function to take this as an argument, referring to itself.
<select onchange="changed(this)" id="list_1" class="travel">
Rewrite the changed function to include any select as a parameter. You may refer to the value of the select element with its value property. This property is reusable as many times as you desire. Store it in a variable if you prefer. Example:
function changed(select) {
console.log('Visiting ' + select.value + '? Enjoy your trip to ' + select.value + '.');
}
<select onchange="changed(this)" id="list_1" class="travel" >
<option selected disabled>Select Place</option>
<option value="New York">New York</option>
<option value="Pennsylvania"> Pennsylvania</option>
<option value="Boston">Boston</option>
<option value="Washigton DC">Washigton DC</option>
</select>

Javascript producing a value into a form textbox on selection

Trying to figure out how I can produce text dynamically in a text box of a form using javascript.
I want to select a type of event from a dropdown list which I have made and on that selection a value be input in to the textbox of the form for eventprice.
So far this is what I have but I have no value being produced in the textbox any help appreciated.
function totalprice(){
if($('#type').val() == '3'){
$('#eventprice') == ("45");
}
}
<input type="text" disabled="" id="eventprice" onChange="totalprice();" name="eventprice" class="form-input" />
If you don't mind using jQuery, it is going to be a breeze: you'll simply need to add the data attribute price to every option. What this function does is:
Compares the value of all options to the value currently visible in the select box when the value is changed.
If the values are the same, copies the data-attribute to the other input.
Working demo: http://jsbin.com/acuyux/6/edit
The HTML
<select id="type">
<option data-price="25">Party</option>
<option data-price="35">Meeting</option>
<option data-price="45">Lounge</option>
</select>
<input type="text" id="eventprice" name="eventprice" disabled="" class="form-input" />
The JS
$('#type').change(function totalprice(){
$('option').each(function() {
if($(this).val() === $('#type').val()) {
$('#eventprice').val($(this).data('price'));
}
});
});
I would recommend using jQuery due to its efficient code.
HTML:
<input type="text" disabled id="eventprice" />
<select id="select">
<option data-cost="5">Event 1</option>
<option data-cost="10">Event 2</option>
</select>
jQuery:
$('#select').change(function () {
var str = $(this).find('option:selected').data('cost');
$('#eventprice').val(str);
});
// This code can be used to run it on load
// $('#select').trigger('change');
Code in action:
http://jsfiddle.net/LkaWn/
Hope this helps :)
Modify the 3rd/4th line of your code to be $('#eventprice').val("45"); as suggested, except that the suggestion had a syntax error.

Sending both the value and key of an option box as parameters?

I want to send both the value and key of the option box when I submit a form. I feel like this should be pretty simple, but I'm unsure how to do it. Below is a snippet from my form to demonstrate what I'm referencing:
<form name='form' onSubmit="return checkForm();" action="../servlet/AccountRequest">
<select name="type1">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
<br/><input type="button" id="Submit" onclick="checkForm(this.form)" value="Request" />
<input type="reset" value="Cancel"/>
</form>
​
In a normal scenario, if I selected "Option A" in the drop-down box, I would want to send the value, or "1". However, I want to actually send the value AND key of the selection, in this case both "1" and "Option A".
In my case, I call a checkForm() JavaScript function that validates form input (there are other fields, like First Name, Last Name, Email Address, and Password), which then forwards the parameters to a Java class (AccountRequest). I'm sure there is a way to store the key as a variable when the "Request" button is clicked, I just don't know how.
Any help would be much appreciated!
You could play with a jSON representation of your data:
<select name="type1">
<option value="{'1':'Option A'}">Option A</option>
<option value="{'2':'Option B'}">Option B</option>
</select>
It might not be the approach you were expecting, but you could send the key/value pair as your value and parse it when you receive it server-side.
<select name="type1">
<option value="1,Option A">Option A</option>
<option value="2,Option B">Option B</option>
</select>
In HTML, this is impossible: the data contributed by a select element is defined to be the value attribute of the selected option, when present (otherwise the content of the selected option element).
In JavaScript, it would be pretty easy, once you have decided how the content (“key” in your description) should be passed. At the simplest, you could append the content to the value attribute, with some separator between the strings; then you would have to parse that server-side, but that would be simple too.
However, it is part of the very idea of option elements that the content is the visible string in the user interface, understandable to the user, and the value attribute is the machine-readable easily processable data. In good design, they are kept as separate, not combined; the server should only need the data from the value attribute; otherwise there is a design flaw that should be fixed.
You could add this code to get the text of your selected <option> tag in your checkform function:
var select = document.getElementsByName("type1")[0]; // get select element - simpler if it has an ID because you can use the getElementById method
var options = select.getElementsByTagName("option"); // get all option tags within the select
for (i = 0; i < options.length; i++) { // iterate through all option tags
if (options[i].value == select.value){ // if this option is selected
var key = options[i].innerHTML; // store key of selected option here
}
}
DEMO, which tells you the key that's selected
Use a compound value, then parse it out on the server:
<option value="1_A">Option A</option>
you can send the value with an input type hidden
1.-choose the default value:
<input type="hidden" id="theValue" name="type1Value" value="Option A"/>
2.-add onChange function to your select, which changes previous hidden value
<select id="type1" name="type1" onChange="updateValue()">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
assuming you are using jQuery:
function updateValue(){
var value= $('#type1').find(":selected").text();
$('#theValue').val(value);
}
so the value of the select will be sent in type1Value variable, EASY!!
using React js
I want to get two values from the option at the same time
so, I use the Split method
var string = "0,1";
var array = string.split(",");
alert(array[0]);
I create a sting on option
const getKioskSelectedUsageType=(e)=>{
let sl = e.target.value
let array = sl.split(",")
console.log("check :- ",array[1] )
}
<select
id=""
className="form-control"
value={kioskSelect}
aria-label="kioskSelect"
name="kioskSelect"
title="kioskSelect"
onChange={(e) => getKioskSelectedUsageType(e)}
style={{ color: "#495057" }}
>
<option value="">Select Kiosk</option>
{kioskConfiData.map((item, i) => {
return (
<React.Fragment key={i}>
<option value={`${item.kioskid},${item.language}`}>
{item.location}
</option>
</React.Fragment>
);
})}
</select>

Categories

Resources