Reload page after user clicks on combobox (with some rules) - javascript

I'm new in javascript and need I to reload the current page after user clicks on the options of combobox, but I have some rules.
The two comboboxes:
<select onChange="Refresh(this.value)" name="comboA">
<option value="0">0</option>
<option value="1">1</option>
</select>
<select onChange="Refresh2(this.value)" name="comboB">
<option value="2">2</option>
<option value="3">3</option>
</select>
Rules:
user clicks on "0" in the first combobox, reload to comboA=0.
user clicks on "1" in the first combobox, replaces "0" to "1" and reload to comboA=1
user clicks on "2" in the second combobox, concatenate and reload to comboA=1 & comboB=2
user clicks on "3" in the second combobox, replaces "2" to "3" and reload to comboA=1 comboB=3
The steps above need to be done in sequence.
How the functions "Refresh" and "Refresh2" should be?
Thanks.

I won't give you the code directly, but I can help you research your answer so that you can learn JavaScript as you go along.
You can use jQuery so help you out but specifically .change() function to detect if the combo box is changed: http://api.jquery.com/change/
To actually refresh the page, or change to another page, you can use the window.location function to direct the user to a page. Window.location.href and Window.open () methods in JavaScript
To actually change elements on the page, without reloading the page, you can use jQuery ajax to post changes to PHP if you need to. http://api.jquery.com/jquery.ajax/
I hope this helps you out in your quest to learn more JavaScript

The first function would simply have to navigate to a the same url followed by ?comboA= then the first argument, like this:
function Refresh(value) {
URL = window.location.href.split("?")[0];
window.location.replace(URL + "?comboA=" + value);
}
The second function would have to keep the ?comboA=value part so it would split after the first & instead:
function Refresh2(value) {
URL = window.location.href.split("&")[0];
window.location.replace(URL + "&comboB=" + value);
}

Try below code in javascript
function Refresh()
{
var e = document.getElementById("comboA");
var selectedOption = e.options[e.selectedIndex].value;
if(selectedOption == "0")
{
// your logic goes here
}
else if (selectedOption == "1")
{
// your logic goes here
}
}
Write same function for other combo box.
I hope these will help you out!!
Let me know if you have any question

you can do it like following:
var url = "http://www.mypage.com?"
$("select[name=comboA]").on("change",function(){
window.location.href = url + $(this).attr("name") + "=" + $(this).val();
});
and for second select
var url2 = "http://www.mypage.com?comboA=1&"
$("select[name=comboB]").on("change",function(){
window.location.href = url2 + $(this).attr("name") + "=" + $(this).val();
});

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

Get script on option select with this value

I am using a select box to pull some data that is built into the site. However there are a few modules that run a script , and using the select option , that script is not firing when its selected. Do i have to run the full script within my option function , or can it be called to execute again when its selected.
Here is my script and html. Option Value "MESSAGE12" - needs a script to run when selected.
if(unescape(location.href).indexOf("http://football")!=-1||unescape(location.href).indexOf("http://6")!=-1) {
var currentServer=baseURLDynamic;
xmlBaseURL = baseURLDynamic + '/fflnetdynamic' + year + '/';
} else {
var currentServer=baseURLStatic;
}
function getHomePageModule(thisSelection) {
if(thisSelection=="")
document.getElementById("homePageModule").innerHTML = "Your selected module will appear here!";
else {
var url = currentServer + "/" + year + "/home/" + league_id + "?MODULE=" + thisSelection.toUpperCase();
$.get(url, function(data){
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
});
}
}
<select onchange="getHomePageModule(this.value)">
<option value="default">Select A Module</option>
<option value="MESSAGE12" >Get HPM#12</option>
<option value="LIVESCORING" >Link To Live Scoring</option>
<option value="LIVESCORING_SUMMARY" >Live Scoring Summary</option>
</select>
<div id="homePageModule">Your selected module will appear here!</div>
Here is a link to my demo select box - http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE11
And a link to the MESSAGE12 content i'm wanting to fire up in the select box
http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE12
Any advice appreciated
Instead of using innerHTML (which doesn't evaluate <scripts>), you could try using jQuery's .append() method.
Change:
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
to:
$("#homePageModule").append($(data).find('#pageContent').html());
(This also replaces the call to getElementById with a jQuery selector.)
If that doesn't work, you might need to take a look at the content returned by the call to $(data).find('#pageContent').html() and make sure your scripts are there, and/or move the scripts into a function that can be called after the .append() finishes.

HTML Autocomplete opens a webpage when pressing enter

I have an autocomplete page which gives me a text value, but I want the same text value to open a webpage when hitting enter or selecting the suggested value.
E.g. when I search for india, I type "ind" and "india" automatically comes up, but and I want "india" to open a webpage (like "domain.com/india") when selecting the value or hitting enter
The code is as follows:
<datalist id="countries">
<select>
<select id="dynamic-select">
<option value="www.blahblah.com">Blah</option>
<option value="www.something.com">something</option>
<script>
$('#dynamic-select').bind('change', function () { // bind change event to select
var url = $(this).val(); // get selected value
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
});
</script>
</datalist>
It pulls out the value but it doesn't open a webpage for me. Can someone help me with this please?
Change
window.location = url;
To
window.location.href= url;
You need to use correct URL syntax. You're missing the // prefix, so it's treating the URL as a filename on your website, not the address of another website.
$('#dynamic-select').bind('change', function() { // bind change event to select
var url = $(this).val(); // get selected value
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dynamic-select">
<option value="">Please choose</option>
<option value="//www.blahblah.com">Blah</option>
<option value="//www.something.com">something</option>
</select>

Automaticly setting default texts in select dropdown

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

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