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];
};
Related
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();
I have a basic GET form in my project that is used to filter through posts created by users. When I submit the form the values from the multiple select input are appended to the url like so:
project.dev/?maps[]=1&maps[]=2&maps[]=3
As you can see, the values are passed to the url via three separate key value pairs... However, I would like to know how to append the values to the url in the following format:
project.dev/?maps=1,2,3
Thanks in advance.
Assuming you're trying to send an array, how about Array.prototype.join?
var arr = [1, 2, 3];
console.log(arr.join(','));
// result: 1,2,3
I found a solution to this and thought I'd share it in hopes to help others overcome the same problem in the future.
HTML
<select id="region" name="region" multiple>
<option value="1">Region 1</option>
<option value="2">Region 2</option>
<option value="3">Region 3</option>
</select>
<select id="maps" name="maps[]" multiple>
<option value="1">Map 1</option>
<option value="2">Map 2</option>
<option value="3">Map 3</option>
</select>
<button id="search">Search</button>
JavaScript
<script>
$(function() {
$("#search").click(function() {
var params = {};
var getSelect = ['region', 'maps'];
$.each(getSelect, function(index, value) {
var select = $('#' + value);
if (select.val() != '') {
var selected = select.val();
if (select.attr('multiple'))
selected = selected.join(',');
params[value] = selected;
}
});
if (!$.isEmptyObject(params)) {
var url = [location.protocol, '//', location.host, location.pathname].join('');
window.location.href = url + '?' + $.param(params);
}
});
});
</script>
I'm having a problem get this piece of code to work:
$(document).ready(function(){
$('#ButtonAluguel').click(function(){
{
var id = $(this).attr('name');
var str = "";
$("option:selected").each(function () {
switch(id=='Trololo'){
case true:
var option = $(this);
str += '?tid_1[]='+ option.attr('value');
break;
case false:
var option = $(this);
str += '?tid[]='+ option.attr('value');break;
}
});
window.location = "localhost/aluguel"+ str;
}});
});
I need it to keep adding stuff to "str" based on the name of a multiple select, identified above as id. Long story short, if the name of the select is "Trololo", id adds tid_1[], if not, it adds tid[] to the str. Any help is appreciated.
Edit:
The multiple select code is as follows(Forgot to put it in the first place, the question doesn't make much sense without it)
<form >
<select class="SelectTipoAluguel" multiple="true" data-placeholder="Tipo de Imóvel" style="width:200px;">
<option value="1">Aasdasdasd</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<select name="Trololo" class="SelectBairroAluguel" id="trololo" multiple="true" data-placeholder="Bairro" style="width:200px;">
<option value="1">Aadasd</option>
<option value="2">Basda</option>
<option value="3">Casda</option>
<option value="4">Dasda</option>
</select>
<input class="ButtonSubmitHome" id="ButtonAluguel" value="Pesquisar" >
</form>
To explain it more clearly, the user must fill the form and choose between the options, so when he clicks the "ButtonAluguel", every option from the select "SelectTipoAluguel" is added to the URL as tid[] and the ones from "SelectBairroAluguel" is added to the URL as tid_1[]
Code edited to reference updated question and OP's comments.
$(document).ready(function() {
var id;
var str = "";
$('#ButtonAluguel').click(function() {
var option = [];
$('select option:selected').each(function(i, selected) {
id = $(this).parent().attr('name');
option[i] = $(selected).val();
if (id == 'Trololo') {
str += '?tid_1[]=' + option[i];
} else {
str += '?tid[]=' + option[i];
}
});
var url = "localhost/aluguel" + str;
console.log(url);
//window.location = "localhost/aluguel" + str;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="SelectTipoAluguel" multiple="true" data-placeholder="Tipo de Imóvel" style="width:200px;">
<option value="1">Aasdasdasd</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<select name="Trololo" class="SelectBairroAluguel" id="trololo" multiple="true" data-placeholder="Bairro" style="width:200px;">
<option value="1">Aadasd</option>
<option value="2">Basda</option>
<option value="3">Casda</option>
<option value="4">Dasda</option>
</select>
<input class="ButtonSubmitHome" id="ButtonAluguel" value="Pesquisar">
I do have two select box like this.
<select class="" id="sender" name="sender">
<option value="">---Select sender ---</option>
<option value="1">Corliss Barrie</option>
<option value="2">Marcie Nava</option>
<option value="3">Weston Bryand</option>
<option value="4">Osvaldo Lasker</option>
<option value="5">Regan Ruckman</option>
</select>
<select class="" id="reciever" name="reciever">
<option value="">---Select sender ---</option>
<option value="1">Araceli Scheff</option>
<option value="2">Assunta Marsch</option>
<option value="3">Yang Wengerd</option>
<option value="4">Branden Purtee</option>
<option value="5">Krystal Fresquez</option>
</select>
My question is I need to update the url with this two select box values, only if both dropdown selected.
I can do it for one dropdown like below, but not sure how to do it with two drop down.
$('#sender').change(function(){
var url = "?sender="+$(this).val();
window.location = url;
});
But my expected url is something similar to this:
?sender=value&reciever=value
Hope somebody may help me out.
Thank you.
you can pretty easy outsource the logic into one function that only changes url if both values are given
$('#sender, #receiver').change(changeUrl);
function changeUrl(){
if($('#receiver').val() != "" && $('#sender').val() != "" ){
url = "?sender="+$('#sender').val()+"&receiver="+$('#receiver').val();
window.location = url;
}
}
Just add another event listener and a conditional:
function changeURL(){
if($('#sender').val()!="" &&$('#receiver').val()!=""){
var url = "?sender="+$(this).val()+'&receiver="+$('#receiver').val();
window.location = url;
}
}
$('#sender').change(changeURL);
$('#receiver').change(changeURL);
Here is a working fiddle. Added a common class url to both select element. And then do functionality on change event.
$('.url').change(function(){
var sender = $('#sender').val();
var receiver = $('#reciever').val();
if(sender !== '' && receiver !== '') {
var url = "?sender=" + sender + "&reciever=" + receiver;
window.location = url;
}
});
Use it like this:
<select class="changeurl" id="sender" name="sender">
<option value="0">---Select sender ---</option>
<option value="1">Corliss Barrie</option>
<option value="2">Marcie Nava</option>
<option value="3">Weston Bryand</option>
<option value="4">Osvaldo Lasker</option>
<option value="5">Regan Ruckman</option>
</select>
<select class="changeurl" id="reciever" name="reciever">
<option value="0">---Select reciever ---</option>
<option value="1">Araceli Scheff</option>
<option value="2">Assunta Marsch</option>
<option value="3">Yang Wengerd</option>
<option value="4">Branden Purtee</option>
<option value="5">Krystal Fresquez</option>
</select>
And your jquery code will like this:
$('.changeurl').on('change', function (e) {
if( $('#sender').val()!="0" && $('#reciever').val()!="0" ){
var newURLString = window.location.href + "?sender=" + $('#sender').val() + "&reciever=" + $('#reciever').val();
window.location.href = newURLString;
}
});
I have two drop downs with exactly the same values.
I want the drop down 2 to display the values based on the selection of items of drop down 1.
So the selected index of drop down 2 will be equal to or more than the selected index of drop down 1.
document.getElementById("SELECTB").selectedIndex >= document.getElementById("SELECTA").selectedIndex
So if B is selected in Drop down 1 then selectable options in drop down 2 will be B,C and D. (A will be not selectable item)
http://jsfiddle.net/xxyhm78t/1/
Solution working with pure Javascript:
var select1 = document.getElementById("SELECTA");
var select2 = document.getElementById("SELECTB");
select1.onchange = function () {
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = select1.selectedIndex; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
select2.appendChild(o);
}
}
Fiddle
Reference: This is an adjusted solution from javascript Change the Dropdown values based on other dropdown
Update: Like asked in the comment - to disable the options instead of removing them:
var select1 = document.getElementById("SELECTA");
var select2 = document.getElementById("SELECTB");
select1.onchange = function () {
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = 0; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
(i <= select1.selectedIndex)
? o.disabled = true
: o.disabled = false ;
select2.appendChild(o);
}
}
Adjusted Fiddle
Update 2: Like asked in the comment if it's possible to adjust this to use class names instead of ids - yes, by using getElementsByClassName(). I've adjusted in this Fiddle both selects to have class="SELECTA" and class="SELECTB" instead of the previously used id. The according adjustment for the Javascript is only the declaration of the variables:
var select1 = document.getElementsByClassName("SELECTA")[0];
var select2 = document.getElementsByClassName("SELECTB")[0];
As you already know, an id is a unique attribute, therefore it's possible to get a single element using getElementById(). getElementsByClassName() returns a collection of HTML elements instead, even if there's only a single element having the class. So it's - in this example - necessary to address the 1st element of this collection. As counting starts by 0, the first (and only) element having the class "SELECTA" is getElementsByClassName("SELECTA")[0].
Reference: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName#Syntax
You can do this using selectedIndex with the following piece of code:
$("#SELECTA").change(function() {
var selIndex = this.selectedIndex;
$("#SELECTB").find("option").each(function(k,v) {
$(this).attr("disabled", selIndex > k);
});
});
Depending on what it is you are after, you may need to reset #SELECTB if one of the disabled values is selected.
I think this is what you are looking for:
$("select").on("change", function (e) {
var sel = this.selectedIndex;
$("#SELECTB option").each(function (i, e) {
$(this).prop("disabled", sel > i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECTA">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
And this can be even more general:
$("select").on("change", function (e) {
var sel = this.selectedIndex;
var nextSelect = $(this).parent().find("select").not(this);
$(nextSelect).children().each(function (i, e) {
$(this).prop("disabled", sel > i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECTA">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>