I am working on a calculator tax.
I wanted to receive the selected values of that was redirected to the url value, so that I could for example send someone a link to the values that I have chosen, so it does not have to set them again only to be had when you start link.
http://kalkulator.atrocki.pl/calculator/index.html
<div class="styled-select">
<h1>Vat</h1>
<select id="vat">
<option value='0'>0%</option>
<option value='0.08'>8%</option>
<option value='0.23'>23%</option>
<option value="other">Add another VAT value..</option>
</select>
<input type="text" class="vatInput" id="vatInputId" placeholder="Vat w %">
</div>
<div class="styled-select">
<h1>tax 2</h1>
<select id="tax">
<option value="0">0%</option>
<option value='0.18'>18%</option>
<option value='0.19'>19%</option>
<option value='0.32'>32%</option>
<option value="other">Add another TAX value..</option>
</select>
JavaScript has no built in function for handling query string parameters.
It's very easy to do this with whatever back-end language you are using in your server.
If you absolutely must do this with Javascript, check this question:
How to get the value from the GET parameters?
You can parse the query string into a nice object, then look for the key value pair you want.
function parseQuery() {
var query = {};
var indexOfQ = window.location.href.indexOf("?");
if (indexOfQ < 0)
return null;
var a = window.location.href.substr(indexOfQ + 1).split('&');
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
}
return query;
}
function loadQueryString() {
var query = parseQuery();
if (!query) return;
if (typeof query['val'] !== 'undefined') {
var newSelection = $("<option>", { value: query['val'], text: (Math.floor(parseFloat(query['val']) * 100)) + '%'});
$('select').prepend(newSelection);
}
}
loadQueryString();
Related
I have the follow form and a Js code to get current urls from "logodiv" divs and append data form submitted by user into url inside that divs:
<select id="type1form" onchange="myFunction()">
<option value="000">000</option>
<option value="111">111</option>
<option value="222">222</option>
</select>
<select id="type2form" onchange="myFunction()">
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
</select>
<div id="logodiv">
<img src="logo1.jpg">
</div>
<div id="logodiv">
<img src="logo2.jpg">
</div>
<script>
function myFunction() {
var mylinks = [];
var mylogo = document.querySelectorAll("#logodiv");
for(var j = 0; j < mylogo.length; j++) {
mylinks[j] = mylogo[j].childNodes[1].href;
}
var type1 = document.getElementById("type1form").value;
var type2 = document.getElementById("type2form").value;
for(var i = 0; i < mylogo.length; i++) {
mylogo[i].childNodes[1].href = mylinks[i] + "&type1=" + type1form + "&type2=" + type2form;
}
}
</script>
My problem is in that last loop code, each time I click on form the url is not changed, but it is appended by form data. So instead url becomes like:
test.com/redir.php?type1=000&type2=AAA
if select fields are clicked twice or more, the url becomes like:
test.com/redir.php?type1=000&type2=AAA&type1=111&type2=BBB
I want url becames with only last type1 and type2 parameters submitted by user, not appending the parameters at end of url infinitely.
Can you help me?
Did a few modifications to make it work, you can check them here :
https://jsfiddle.net/x07cqd3z/1/
First, id are supposed to be unique, so logodiv is now a class.
Second, you had some error in your code that have been fixed.
My work around is taking the url base everytime (everything before "?") to append the parameter only once.
Code :
<select id="type1" onchange="myFunction()">
<option value="000">000</option>
<option value="111">111</option>
<option value="222">222</option>
</select>
<select id="type2" onchange="myFunction()">
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
</select>
<div class="logodiv">
<img src="logo1.jpg">
</div>
<div class="logodiv">
<img src="logo2.jpg">
</div>
<script>
function myFunction() {
var mylinks = [];
var mylogo = document.querySelectorAll(".logodiv");
for(var j = 0; j < mylogo.length; j++) {
mylinks[j] = mylogo[j].childNodes[1].href;
}
var type1 = document.getElementById("type1").value;
var type2 = document.getElementById("type2").value;
for(var i = 0; i < mylogo.length; i++) {
mylogo[i].childNodes[1].href = mylinks[i].substring(0, mylinks[i].indexOf('?') + 1) + "&type1=" + type1 + "&type2=" + type2;
}
}
</script>
I'm building a quote generator, and there is a product field where a user can select a product, select the quantity, then add another if they wish.
I'm using an each function to loop through all the products they add to sum the price.
For regular values, my JS is running great, but I want to add a second price (minimum price) that the product can be sold for. I've added the data as an attribute and i'm trying to use the same method to pull the price from the attribute, but it just keeps returning 'undefined'!!!!
HTML
<select class="form-control onChangePrice system1" name="SystemModel">
<option value="">Select...</option>
<option value="3300" data-min-price="3000">System 1</option>
<option value="4500" data-min-price="4000">System 2</option>
<option value="6000" data-min-price="5500">System 3</option>
<option value="6000" data-min-price="5500">System 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice systemNumber" type="number" name="SystemModelAmount" value="1">
</div>
JS
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("minPrice");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
The code works flawlessly for the regular value of the option, i just cant get it to repeat for the data attribute!
Thanks
You're doing a couple of things slightly wrong here:
$('.system1').each(function(){
should be:
$('.system1 option').each(function(){
and
systemEachMin = $(this).data("minPrice");
should be:
systemEachMin = $(this).data("min-price");
So in full:
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1 option').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("min-price");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
$(this).data("minPrice"); refers to the select tag and not the options tag, there is no data-min-price on the select tag.
this.options will return all the options in an array
or you could use the following for the selected options data attribute
$(this).find('option:selected').data("minPrice")
or
$("option:selected", this).data("minPrice")
I am trying to get my code to read a value based off the selected item from a select list in my form, but it says it's undefined. When I simply give the function a value and tell it to return the value, it reads, but won't take values from the form.
The following is the code I'm using
for the form (in html):
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost()">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
and the javascript reads
function calculateCost()
{
var orderPrice = getItemPrice();
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
function getItemPrice()
{
var itemPrice = 0;
var theForm = document.forms["orderForm"];
var selectedItem = theForm.elements["item"];
itemPrice = item_prices[selectedItem.value];
return itemPrice;
}
HTMLCollection.item() is method of HTML select element Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
theForm.elements["item"] will return function expression of the HTMLCollection.item and which is causing the undefined value as theForm.elements["item"] does not have property value
Either pass this in inline-event or use other id and name attribute to select element than item
function calculateCost(elem) {
var orderPrice = getItemPrice(elem.value);
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices = [];
item_prices["None"] = 0;
item_prices["Candlestick"] = 10;
item_prices["Bowl"] = 10;
item_prices["Burl_Bowl"] = 20;
item_prices["Clock"] = 15;
item_prices["Vase"] = 5;
item_prices["Pen"] = 2;
item_prices["Top"] = 1;
function getItemPrice(val) {
var itemPrice = 0;
itemPrice = item_prices[val];
return itemPrice;
}
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost(this)">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
Edit: Or just use getElementById => var selectedItem = document.getElementById('item'); to access the select element.Fiddle here
This entire operation could be simplified a bit as well.
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
EDIT, you should use an object here if you want to be correct.
item_prices = {
None: 0,
Candlestick: 10
};
// etc...
document.getElementById('item').addEventListener('change', function (event) {
document.getElementById('totalPrice').innerHTML = item_prices[event.target.value];
});
I am using the following code to grab information from the URL to pre-fill forms, however, I am trying to get this to work with a multiple select if multiple options are provided.
$(function() {
//grab the entire query string
var query = document.location.search.replace('?', '');
//extract each field/value pair
query = query.split('&');
//run through each pair
for (var i = 0; i < query.length; i++) {
//split up the field/value pair into an array
var field = query[i].split("=");
//target the field and assign its value
$("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(field[1]));
}
});
Multiple Select Example
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
I would like to be able to do http://www.example.com?strings=Test,Prof or something similar. I am new to JQuery and not sure of this.
You can pass an array as the value to set multiple select values.
A simple approach, looking for the presence of , to indicate multiple values (so do something smarter if , is a valid character in other fields' values):
var query = 'strings=Test,Prof';
//extract each field/value pair
query = query.split('&');
//run through each pair
for (var i = 0; i < query.length; i++) {
//split up the field/value pair into an array
var field = query[i].split("=");
//target the field and assign its value
var parts = field[1].split(',');
if (parts.length > 1)
$("select[name='" + field[0] + "']").val(parts);
else
$("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(field[1]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name='strings' id="strings" multiple style="width: 100px">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
you can use javascript as in this fiddle: http://jsfiddle.net/yqh5u762/
document.getElementById("strings")[2].selected = true;
document.getElementById("strings")[1].selected = true;
You can't tell the box to change it's value because only one is allowed, but you can tell the individual options to show selected. This does require you to use the index number involved with the array of options.
I have a select list on a page like this:
<select name='elements'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
EDIT: When a user makes a selection, the current page is refreshed, but how do I keep the user's selection visible in the list after the page refresh? In other words, I don't want the list to rollback to its default selected value.
Help please
Here is a Javascript-only solution.
<select name='elements' id='elements' onChange='window.location="yoururl.html?value=" + this.value;'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
Then you use this function to see if the value parameter is set and get it and you can use jQuery to set it as selected.
$("#elements option[value='" + result_of_gup + "']").attr("selected","selected") ;
<select name='elements' onChange='window.location="yoururl.php?value=" + this.value;'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
Doing it without jQuery:
Create window.location.getParameter() function (see here from Anatoly Mironov) then:
<select name='elements' id='elements' onChange='window.location="yoururl.html?elements=" + this.selectedIndex;'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
<script type="text/javascript">
els = document.getElementById('elements');
selIndex = window.location.getParameter('elements') || 0;
els[selIndex].selected = true;
</script>
For ease of reference, I reproduce Anatoly's excellent .getParameter function below:
window.location.getParameter = function(key) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[key];
};