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;
}
});
Related
This a sample of the dropdowns using select that I have
<label class="form__label" for="country"> Country Of Residence</label>
<select id="country" class="form__input" name="country"/>
<option value="null">Select Country</option>
<option value="United Arab Emirates">United Arab Emirates</option>
<option value="Bahrain">Bahrain</option>
<option value="Kuwait">Kuwait</option>
<option value="Oman">Oman</option>
</select>
The value is stored in the database as a 'String'.
I would appreciate some help in understanding the best way forward for 2 things
On Load
The string value from the database should be the option displayed in my dropdown. And if for some reason the string value in the database does not match, then the 'Select Country' option should be displayed.
On Change
The selected value should be the value that's sent to the database as a String. The functionality for this is already implemented but earlier I was using a input of type=text .. So what type of changes are needed to send this value now from a select field.
I've researched on the net but the more I research the more I get confused. And most answers seem to be jQuery solutions. I am looking for some help with Vanilla Javascript. Somethings I need to get clarity on is 'Do I need to have a hidden field to store the value and send and receive from database?' .. I am really confused with the information I've researched.
Any help would be appreciated.
Get select element value on event using pure JavaScript, Try this and get value.
var select_element = document.getElementById('country');
select_element.onchange = function() {
var elem = (typeof this.selectedIndex === "undefined" ? window.event.srcElement : this);
var value = elem.value || elem.options[elem.selectedIndex].value;
alert(value);
// your another required code set!
}
After a couple of days of struggling, I am using this solution. If this is overkill and there's a simpler approach, please do share in comments.
So I first identified the select element
const country = document.getElementById('country');
Then created a function as below
const displayCountry = function() {
//CREATE ARRAY OF ALL OPTIONS
const optionsArray = Object.entries(country.children);
console.log(optionsArray);
// GET NAME OF COUNTRY FROM SELECT FIELD
const nameOfCountry = country.getAttribute("value");
console.log(nameOfCountry);
// FIND OPTION WITH THE SAME COUNTRY NAME
const option = optionsArray.find(
(option) => option[1].value === nameOfCountry
);
// UPDATE OPTION FIELD BY SETTING ATTRIBUTE OF SELECTED
option[1].setAttribute("selected", true);
console.log(option[1]);
};
It can be shortened as below
const displayCountryShortened = function() {
Object.entries(country.children)
.find((option) => option[1].value === country.getAttribute("value"))[1]
.setAttribute("selected", true);
};
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")
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>
I have a drop down box in which allows for a "category" to be selected, if it is changed it loads the new category as shown in the code below. I have since introduced a "Sub-Category" system and am in need of modifying this code slightly. I found the following information to be very helpful:
How to attach different events on multiple selectors through .on function in jquery?.
However, it doesn't quite solve my problem... I could use that to run two separate events for each selector within the same function but I need to run both simultaneously in the event both a "category" and "sub-category" are selected. Though they need to also be capable of running separate, in the event only one is selected. I'm fairly new to js/jquery so the more info you can provide the better! Thank you very much!
<script type='text/javascript'>
$(document).ready(function()
{
$('select#selectCategory').change(function()
{
var cat = $('select#selectCategory').val();
var subcat
if(cat > 0)
{
var param = '&category_id=' + cat;
}else{
var param = '';
}
var href = './videoroom.php?action=video_gallery'+ param +'&page=1';
window.location.href = href;
});
});
</script>
Here is the HTML section related to the already written jquery code:
<select style="min-weight:100px;" name="filter_by_cat" id="selectCategory">
<option value="0">All</option>
<option value="9">Wizard101</option>
<option value="10">Pirate101</option>
<option value="11">Pet Derby</option>
<option value="14">Misc/Fun</option>
</select>
And here is the new bit I added for the newly created Sub-Category:
<select style="min-weight:100px;" name="filter_by_subcat" id="selectSubCategory">
<option value="0">All</option>
<option value="21">General PvP</option>
<option value="22">PvPC Matches</option>
<option value="23">PvP Guides</option>
<option value="24">Miscellaneous</option>
</select>
Add the event listener to both dropdowns and check both of them when either is changed:
jsFiddle
$('#selectCategory, #selectSubCategory').change(function() {
var cat = $('#selectCategory').val();
var subcat = $('#selectSubCategory').val();
var params = [
'action=video_gallery',
'page=1'
];
if (cat > 0) {
params.push('category_id='+ cat);
if (subcat > 0) {
params.push('subcategory_id='+ subcat);
}
}
var href = './videoroom.php?'+ params.join('&');
window.location.href = href;
});
I'm assuming you only want the subcategory choice to be taken into account when the main category is selected. If that's not the case, move the second if-statement outside the first one.
I also refactored your code a little to make it more easily extensible and (IMO) cleaner. I'm adding all the params to an array and them just joining them at the end. If you need to add any more params, just put them in the array as well.
We have two dropdowns that according to your selection it changes part of the string in some div containers. The purpose of this is to return URLs to give to clients.
This is a sample of the code
<select name="lstLanguage" id="lstLanguage">
<OPTION VALUE="">-- Generic default ---</OPTION>
<OPTION ID="Arabic" VALUE="AR">Arabic</OPTION>
<OPTION ID="German" VALUE="D">German</OPTION>
</select>
<select name="lstTemplate" id="lstTemplate">
<OPTION VALUE="">-- Generic default ---</OPTION>
<OPTION VALUE="1">Member</OPTION>
<OPTION VALUE="2">NonMember</OPTION>
</select>
<div id='Ind_URL'>http://example.com/Registration.asp?Language_Code=?Role=</div>
<div id='Ind_W_URL'>http://example.com/Registration.asp?Language_Code=?Role=</div>
<div id='Login_URL'>http://example.com/?Language_Code=</div>
And this is the jQuery we currently have, which was provided by irama.
$(function(){
divIDs = [
'Ind_URL',
'Ind_W_URL',
'Login_URL',
];
$('#lstTemplate').bind('change', function(){
role = $(this).find('option:selected').val();
updateURLDivs(langCode=null, role);
});
$('#lstLanguage').bind('change', function(){
langCode = $(this).find('option:selected').val();
updateURLDivs(langCode, role=null);
});
updateURLDivs = function (langCode, role) {
for (i in divIDs) {
currentDiv = $('#'+divIDs[i]);
if (langCode !== null) {
currentDiv.data('Language_Code', langCode);
}
if (role !== null) {
currentDiv.data('role', role);
}
// Cache original div contents, so that the select menu can be changed more than once.
if (typeof currentDiv.data('contents') == 'undefined') {
divContents = currentDiv .html();
currentDiv .data('contents', divContents);
} else {
divContents = currentDiv .data('contents');
}
currentDiv.empty().append(
divContents
.replace('role=','role='+currentDiv.data('role'))
.replace('Language_Code=','Language_Code='+currentDiv.data('Language_Code'))
);
}
}
});
This is working fine, but this morning we found a few issues
It is currently updating both parameters, no matter if you change one or both. We need it to update if you change the template, just the template and if you change the language just the language.
If nothing is selected we need it to replace it with a blank not with undefined as it is currently doing
If we change the Template it also needs to replace Registration.asp to PersonImport.asp from the URLs
This is how it should work
The div containers need to have the default URLs in them
If I change the language (lstLanguage) it should just change the Language_Code on the DIV containers. Then if I select the language option with no value ("Generic default") the Language_Code should be blank ''
If I change the template (lstTemplate) it should change the Role on the DIV containers. Also should change Registration.asp to PersonImport.asp. Then if I select the template option with no value ("Generic Default) the Role should be blank '' and PersonImport.asp should go back to Registration.asp.
I'm not a good coder on this, but it would be great if any of you can give me a hand with this.
Thanks in advance
Federico
I have create a fiddle with a lot of improvement in your code. Take a look.
Working demo