Automaticly setting default texts in select dropdown - javascript

I have a very simple select dropdown with urls that direct users to respective pages
<select>
<option value="url1">title1 </option>
<option value="url2">title2 </option>
<option value="url3">title3 </option>
.........
</select>
I will have this drop down in all these (url1, url2, url3...) serving for navigation. Would it be possible to set the default text in the selection box based on my urls? Say if I am currently on url2, my default text in the selection box will be title2. I know manually you can just use
<option selected="selected" value="url2">title2</option>
But is there a way I can use javascript to do because I have hundreds of pages? All the urls and titles are stored in an array that I can retrieve.
Thanks for your help!

Assuming you want to match the url in the window location (such as http://www.example.com/some/page.html) with the URL to the page found in your dropdown:
var dropdown = document.getElementById( 'dropdown' );
for ( var i = 0; i < dropdown.childElementCount; ++i ) {
if ( dropdown.children[i].value === document.location.href) {
dropdown.selectedIndex = i;
break;
}
}
Where 'dropdown' contains the ID of your <select> element. Jsfiddle: http://jsfiddle.net/RhZy6/

You should be able to use this:
var path = decodeURIComponent(window.location.pathname.replace(/\/$/, ""));
$("option").each(function () {
var url = $(this).val();
if (path.substring(0, url.length) === url) {
$(this).prop('selected', true);
}
});
Path is the end of the URL. The next block of code loops through the option elements and looks to see if the option value matches the path, and if it does, sets the selected property to true.

You can get the current URL using document.URL and on document ready you can use ,
$("#selectId option[value=" + document.URL + "]").prop('selected', true);
However document.URL contains full path , so you need to truncate the unnecessary part like http:// https:/ , if it is not present in value of select.
And , here is the working fiddle
P.S The Fiddle will work second time only. It is shwoing diffrent URL on first time. Gotta be a JSFiddle personal thing.

Say you have
<form name="MyForm">
<select name="SelectBox1">
<option>One
<option>Two
<option>Three
</select>
.. etc .. rest of form/page ..
then in your javascript code ..
var el=document.forms.MyForm.SelectBox1;
el.selectedIndex=2; // sets option to "Three" in Select box, because first option is number 0, second =1, third = 2 etc
Or to set it to a value use a function like this .. pass in the Select field name and the value it should be
function setSelect(sFieldName, sValue) {
var el=document.getElementsByName(sFieldName)[0] // returns array of all elements with that name so use [0] to get 1st one
for (var i=0;i<el.options.length;
if (el.options[i].value == sValue) { // if they match...
el.selectedIndex=i; // then this should be the default
}
}
call it usiong something like
setSelect("SelectBox1","http://ectetc")

Related

Auto pre-select dropdown value from URL address

I'm using the dropdown select menu which redirects users to selected cities. I have searched for this topic everywhere and tried many solutions found on stackoverflow but each of them did not work. In many cases it even disabled the redirection of my dropdown. So I am posting a new question. Hopefully that someone could solve my problem.
Problem: When I visit URL I see select delivery city - non value option. It should show the selected city based on URL address.
My URL looks like this /kategoria-produktu/CITY U SELECT (/kategoria-produktu/cadca/)
To sum up: When u visit url /kategoria-produktu/cadca the dropdown should be preselect on current url and display Čadca.
Any ideas how could I solve this?
Thank you very much!
CODE
JS
if(location.href.indexOf(localStorage.country) == -1){
location.href = localStorage.country
}
function formChanged(form) {
var val = form.options[form.selectedIndex].value;
if (val !== 'non-value') {
if (localStorage) {
localStorage.country = val;
}
if (!location.href.indexOf(val)) {
location = val;
}
}
}
HTML
<form name="form1">
<select id="saleTerm" onchange="formChanged(this); location =
this.options[this.selectedIndex].value;" NAME="country" SIZE="1">
<OPTION VALUE="non-value">Select delivery city</option>
<OPTION VALUE="/kategoria-produktu/cadca/">Čadca</option>
<OPTION VALUE="/kategoria-produktu/brno/">Brno</option>
<OPTION id="bratislava" VALUE="/kategoria-produktu/bratislava/">Bratislava</option>
</select>
</form>
So a bunch of little things need to change here for you to get what you want. I'll try to write them all down:
You should access localStorage using getItem and setItem like in the localStorage MDN documentation
Use an event listener instead of the inline onchange attribute, it's much cleaner.
You probably want to use includes instead of indexOf since you are looking for a substring (country) in a string (href), indexOf won't do this for you.
I used location.pathname since you really only care about the path, there are better ways to get the exact path parameter you want.
No need to use a <form/> as far as I can see from the code you shared.
I removed /kategoria-produktu/ from the option's value attribute since its repetitive and just placed it once in the js
You should change the value of the select to the city you want as the default selected. You can do this by parsing out the city from the path and setting it as the value attribute on the select
I think that's it, here is an example using those points above.
const PREFIX = "kategoria-produktu";
window.addEventListener('load', function() {
let countryInStorage = localStorage.getItem("country");
if (countryInStorage && !location.pathname.includes(countryInStorage)) {
location.href = `/${PREFIX}/${countryInStorage}`;
}
document.getElementById("saleTerm").addEventListener("change", formChanged);
setDefaultOption();
})
function setDefaultOption() {
let countryPath = location.pathname.split("/")[2];
if (countryPath) {
document.getElementById("saleTerm").value = countryPath;
}
}
function formChanged() {
let selectedCountry = this.value;
if (selectedCountry !== "non-value") {
if (localStorage) {
localStorage.setItem("country", selectedCountry);
}
if (!location.pathname.includes(selectedCountry)) {
location.href = `/${PREFIX}/${selectedCountry}`;
}
}
}
<select id="saleTerm" name="country">
<option value="non-value">Select delivery city</option>
<option value="cadca">Čadca</option>
<option value="brno">Brno</option>
<option value="bratislava">Bratislava</option>
</select>
If I understand it correctly, you are looking onto showing the proper option from the select element based on the URL.
Look at the example below. It basically runs a process on page load and when the DOM is ready (hence DOMContentLoaded) to check if an option based on URL exists in the select options and picks that. You may have to update your logic depending on the URL structure. The example below assumes your URL is always formatted like http://your.domain.com/kategoria-produktu/<city>/.
document.addEventListener("DOMContentLoaded", function() {
// find the option based on the URL.
let option = document.querySelector("#saleTerm > option[value='" + location.pathname + "']");
// assign the option value to the select element if such exists.
if (option) {
document.querySelector("#saleTerm").value = option.value;
}
});

small javascript to output options to a select doesnt work

Im making a small webpage. The goal is simple. I have a select with a few options; it is planet names; and their sizes are placed in the value bracket of each option. What i want to do is upon selecting an option ( a planet ), a javascript code will take the choice's size, and give new options to another select bracket. So depending on the first select , the second select bracket will be given new options.
The code is simple and ive overwatched it but theres no error.
I just dont get what's not working. Here's the code:
<select id="selectedplanet" name="selectedplanet" onchange="jcab3();">
<?php
while($fetch28a3=mysqli_fetch_array($query28a3)){
echo('<option value="'.$fetch28a3[1].'">'.$fetch28a3[0].'</option>');
}?>
</select><br/>
<p>Location: </p><br/><br/><p>X:</p><select id="locationx" name="locationX"></select><br/><p>Y:</p><select id="locationy" name="locationY"></select>
This is the html/php side. As you can see , I summon a php that fetch some datas from a mysql table. It assign new options on a select bracket. The select has an 'onchange' , which summon the javascript function 'jcab3' upon changing the select . Then here's the javascript:
function jcab3(){
var final2="";
var final3="";
var prima=parseInt(document.getElementById("selectedplanet").value);
for(i31=0;i31<prima;i31++){
final2=final2+'<option value="'+i31+'">'+i31+'</option>';
}
for(i32=0;i32<prima;i32++){
final3=final3+'<option value="'+i32+'">'+i32+'</option>';
}
document.getElementById("locationx").innerHTML=final2;
document.getElementById("locationy").innerHTML=final3;
}
basically, it takes the size of the planet, then give out new options from 0 to the planet's size , and should place these new options under 2 differents select brackets ( 'locationx' and 'locationy'). But , it just doesnt work.
can anyone help ?
thanks
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="myplanet">
<option value="4">Earth</option>
<option value="5">Mars</option>
<option value="6">JUpiter</option>
</select>
<p>X:</p>
<select id="locationx" name="locationX"></select><br/>
<p>Y:</p>
<select id="locationy" name="locationY"></select>
<script>
document.getElementById("myplanet").addEventListener('change', function(){
var e = document.getElementById("myplanet");
var value = e.options[e.selectedIndex].value;
var prima = parseInt( value )
var final2="";
var final3="";
for(i31=0;i31<prima;i31++){
final2=final2+'<option value="'+i31+'">'+i31+'</option>';
}
for(i32=0;i32<prima;i32++){
final3=final3+'<option value="'+i32+'">'+i32+'</option>';
}
document.getElementById("locationx").innerHTML = final2
document.getElementById("locationy").innerHTML = final3
})
</script>
</body>
</html>
How many new <option>s tags are you adding into your <select>s?
Consider that as saying by #Michael Bogwardt in his comment about what innerHTML is doing in javascript?:
However, DOM manipulations using innerHTML are slower and more
failure-prone than manipulations based on individual DOM objects.
Would be better to create your <option>s tags by using element.appendChild() and element.setAttribute() functions. Your code could look like this:
function jcab3(){
var prima=parseInt(document.getElementById("selectedplanet").value);
var x = document.getElementById("locationx");
var y = document.getElementById("locationy");
for(i31=0;i31<prima;i31++){
var option = x.appendChild("OPTION");
option.setAttribute("value", i31);
}
for(i32=0;i32<prima;i32++){
var option = y.appendChild("OPTION");
option.setAttribute("value", i32);
}
}

get list of selected items from select box in javascript

i am using a multi select box in javascript as given here:
i want to get the list of selected items in the multi select text box (the left list)
what can i do to achieve that?
my select box is as follows:
<select id="userList" class="multiselect" multiple="multiple" name="users[]" style="width: 75px;">
//List
</select>
i guess users[] stores the selected users at a point in time. but i can't figure out how to retrieve that variable.
Doing this will work:
$('[name="user[]"]').val()
PS: You need to have jQuery included in your webpage.
from the demo at http://www.quasipartikel.at/multiselect/, doing $('[name="countries[]"]').val() will give sample output:
["ARM", "AUS", "AUT"]
Get a list of values with jQuery:
var values = $select.find('option:checked').map(function() {
return this.value || this.text;
});
// or $select.val() of course, like lemarc says
// => ['ABC', 'DEF']
var prefix = encodeURIComponent($select.attr('name')) + '=';
var httpQuery = values.length ? prefix + values.map(function() {
return encodeURIComponent(this);
}).join('&' + prefix);
// => users[]=ABC&users[]=DEF
I didn't test it.
This will return array of selected values
$('#userList').val();
DEMO
You can directly target $(".multiselect") Object, by doing this:
$("input[type='submit']").click(function(e){
e.preventDefault();
_selValue = $(".multiselect").val(); //You will have variable of selected values
for(var i=0;i<_selValue.length;i++){
alert(_selValue[i]);
//You can iterate it individually in loop
}
});

How to select option value from select tag using jquery

sorry guys, previously I didn't mention the my dropdown list is made with bootstrap. based on #rps suggestion I asked to my colleague(who is made template) he said it's made with bootstrap.
I am putting basic html dropdown code,so I think you guys can understand How bootstrap code will be.
html code:
<select name="primary" class="select-block" id="select_alert">
<option "selected">Choose Alert T</option>
<option value="T1">T1</option>
<option value="T2">T2</option>
<option value="T3">T3</option>
<option value="T4">T4</option>
</select>
Initially i am getting the select menu in the following way.
for my conformation,I am finding the menu value in the following way.
i/p: document.getElementById('select_alert').value
o/p: "choose Alert T"
Now using javascript or jquery, I want to change select option in the follwoing way.For this I tried the below it's not working
document.getElementById('select_alert').value="T1";
Again If I check the value of select menu,it should be "T1".
Thanks
you can try this
// Get the value from a dropdown select
$( "#select_alert option:selected").val();
$( "#select_alert option:selected" ).text();
My reading of the question is ambiguous, but if you're trying to set the value, or set the selected-option, to T1:
$('#select_alert option[value="T1"]').prop('selected',true);
JS Fiddle demo.
If you're trying to retrieve the value of the selected option:
$('#select_alert option:selected').val();
Using jQuery you can just do this:
$('#select_alert').val('T1');
Demo : Fiddle
use as follows :
$('#select_alert').val('T1'); // in jquery
also your javascript code is correct, there must be some other error on the page.
without jquery you can use
document.getElementById('select_alert').selectedIndex = 1
http://jsfiddle.net/uzqZA/1/
if you want to find out the option index by given value try this
var sel = document.getElementById('select_alert'),
selopt = sel.options,
searchidx;
//alert(selopt[sel.selectedIndex].value);
//sel.selectedIndex = 1;
//alert(selopt[sel.selectedIndex].value);
//alert(sel.value)
// search for the index
searchidx = getoptidx(selopt, "T3");
if (searchidx !== false) {
sel.selectedIndex = searchidx;
alert(selopt[sel.selectedIndex].value);
} else {
alert("index not found")
}
/**
* returns the index of a value
* #todo optimize search?
*/
function getoptidx(opts, searchterm) {
for (var i in opts) {
if (opts[i].text === searchterm) return i;
}
return false;
}
the fiddle: http://jsfiddle.net/uzqZA/6/
Try to do it this way :
$('#select_alert').val("T3");
$("#select_alert").selectmenu();
$("#select_alert").selectmenu("refresh");

customize java script function from particular page when that method is used by many pages

I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>

Categories

Resources