Setting Multiple Select from URL - javascript

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.

Related

Two dynamic select boxes with data attribute in both and dependant on them

How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>

Using jquery data attributes with each function

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")

How to add option value to url

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();

Hide dropdown options with Javascript based on keyword in the URL

I need to hide certain options for a product based on the URL they came from. However its a bit tricky for me since I cant target the option value in this situation.
Example URL: http://www.website.com/department/alabama/shirt.html
<select id="select_135">
<option value="">-- Please Select --</option>
<option value="1849" selected="selected">NONE </option>
<option value="1850">Alabama 1</option>
<option value="1851">Alabama 2</option>
<option value="1852">Arizona</option>
<option value="1853">California</option>
<option value="1854">Texas</option>
</select>
Is this case I want to hide all options that DONT have the word Alabama, without using the value number. The goal is for this to work site wide, so if they are on another category, it will do the same thing but with the new URL.
So for the next state: http://www.website.com/department/texas/shirt3434.html , it will do the same thing but for the word Texas.
Any ideas on how I can do that?
use below code . check DEMO
$( document ).ready(function(){
var url = " http://www.website.com/department/alabama/shirt.html";
// to get URL use below code
// var url = window.location.href;
url = url.split('/');
var word = url[url.length-2];
$("#select_135 option").each(function(){
if($(this).text().toLowerCase().indexOf(word) == -1){
$(this).hide();
}
});
});
Use indexOf to check the occurance of a substring.
var url = "http://www.website.com/department/alabama/shirt.html";
var s = $('#select_135 option');
var pieces = url.split("/");
var state = pieces[pieces.length-2];
for(var i = 0; i < s.length; i++) {
if(s[i].text.toLowerCase().indexOf(state) > -1) $(s[i]).show();
else $(s[i]).hide();
}

How to find the index of a dropdown for the given text

How can I find the index of a dropdown for a given value using jQuery?
Here is my dropdown with three values:
admin
mananger
employee
I'm able to get the index of the selected value like below
var index = $("#mydropdown").find("option:selected").val();
But I need to know the index of manager by passing manager as an argument to a jQuery function to get the index
I tried like this but it's not working
var index = $("#mydropdown").find("manager").val();
I think you need something like this:
js
$("select option[value='manager']").index()
html
<select>
<option value="admin">admin</option>
<option value="manager">mananger</option>
<option value="employee">employee</option>
</select>
fiddle
You can either use :contains or .filter(). I personally prefer .filter():
var index = $("#mydropdown").find(":contains(manager)").val();
//Or
var index = $("#mydropdown").filter(function(){
return $.trim($(this).text()) === "manager";
}).val();
This assume your drop down look like this :
<select>
<option value="1">admin</option>
<option value="2">manager</option>
<option value="3">employee</option>
</select>
Note: If you need to force the user to make a selection use an empty option and then have code check for a value ='0' or an index of zero respectively. I have added an empty option in both implementations below for this purpose.
Implementation #1:
function optionchanged()
{
var i = $("#option1").val();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
}
Assign index to value property in each option allows you greater control over the value returned.
<select id="option1" onchange="optionchanged();">
<option value="0"></option>
<option value="1">Admin</option>
<option value="2">Manager</option>
<option value="3">Employee</option>
</select>
The Console Output looks like this:
Selecting 'Admin' produces:
The Index of option selected is: 1
The Text of option selected is: Admin
Selecting 'Employee' produces:
The Index of option selected is: 3
The Text of option selected is: Employee
Implementation #2:
If you don't want to add the index to value you can reference the index directly in jQuery like this:
function optionchanged()
{
//var i = $("#option1 ").val();
var i = $("#option1 option:selected").index();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
//alert("Value of option 1 is: " + index);
}
<select id="option1" onchange="optionchanged();">
<option></option>
<option>Admin</option>
<option>Manager</option>
<option>Employee</option>
</select>
The console output will look the same as above.

Categories