HTML Autocomplete opens a webpage when pressing enter - javascript

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>

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

Change URL of pages according Dropdownlist SelectionIndexChanged event

I'm creating a website for my school project, which has two locations. I want to change the URL of pages according to that location on Dropdownlist SelectionIndexChanged event
You can use window.location = yoururl. This demo may be your requirement.
$('#location').on('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = url; // redirect
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="location">
<option value="" selected>Select a location</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.google.com.vn">Google Vietnam</option>
</select>

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

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

Use drop down list as query string

I have a drop-down list inside a form
<form id="myForm">
<select>
<option>ABC</option>
<option>xyz</option>
</select>
</form>
When an item is clicked, I want the user to be directed to a new page (i.e. 'newPage.aspx'), and this page will display the chosen option, e.g. inside a label (Label1)
I also have the 2 options stored in an array ->
myArray = new Array("ABC", "xyz"), if that helps
jQuery it:
$('select','#myForm').change(function() {
document.location.href = "/newPage.aspx?value=" + $(this).val();
});
Better solution (submitting the form, more friendly to search engines) would be:
HTML:
<form id="myForm" method="get" action="newPage.aspx">
<select name="mySelect">
<option value="ABC">ABC</option>
<option value="xyz">xyz</option>
</select>
</form>
javascript:
$('select','#myForm').change(function() {
$('#myForm').submit();
});
Make your drop-down list an ASP.NET server control (since you're using aspx)
In your codebehind, get the selected value from the dropdown list
In your codebehind, Response.Redirect to the URL (newpage.aspx?value=ABC)
Currently untested, but I think this should work:
var sel = document.getElementById('myForm').getElementsByTagName('select')[0];
sel.onchange() = function(){
var val = this.getElementsByTagName('option')[this.selectedIndex],
url = 'http://newPage.aspx?option=',
queryUrl = url + encodeURIComponent(val);
window.location = queryUrl;
});
References:
document.getElementById().
element.getElmentsByTagName().
element.onchange().
encodeURIComponent().
window.location.

Select box to change url

I want to use a select to change the query on the end of a url to change it's sort options. e.g:
<select id="sort">
<option value="?order_by=date">Recent</option>
<option value="?order_by=random">Popular</option>
<option value="?order_by=random">Random</option>
<option value="">Staff Picks</option>
</select>
so for example by default a list of posts will be shown by date and then if a user chooses an option it will reload the page with the query string on the end of the URL. If possible looking to use jQuery to achieve this. Thanks.
Attach a handler to the change event for the select box that adds the value of the selected option to the current window location with everything after the ? snipped off:
$('#sort').change(function(e){
var locAppend = $(this).find('option:selected').val(),
locSnip = window.location.href.split('?')[0];
window.location.href = locSnip + locAppend;
});
Here's an example ࢐ (it doesn't redirect, but you get the idea...)
To have the appropriate value selected on page load, you can run the following function before you bind the change handler:
function selectCurSort() {
var match = window.location.href.split('?')[1];
$('#sort').find('option[value$="'+match+'"]').attr('selected',true);
}
selectCurSort();
I'm not quite sure why you aren't just using something like:
<form method="GET">
<input type="hidden" name="query" value="..." />
<select id="sort" name="order_by">
<option value="date">Recent</option>
<option value="popular">Popular</option>
<option value="random">Random</option>
<option value="staff">Staff Picks</option>
</select>
<input type="submit" value="Sort" />
</form>
And, for the JS, if any, just:
$('#sort').change(function() {
$(this).parents('form').submit();
});
Then, you don't require anyone to have JavaScript enabled.
Like this?
$("#sort").change(function(){
window.location = $(this).find("option:selected").val();
});
Add
onchange="if (this.value && /^\?/.test(this.value)) location = location.path + this.value"
to your <select>.
You might want to put a blank option at the top too.
$(function() {
$("#sort").change(function() {
var myVal = $(this).val();
window.location = "www.mywebsite.com/"+ myVal;
});
var qs = window.location.pathname;
$("#sort option").each(function() {
if(qs.contains($(this).val()))
$(this).addAttr("selected","selected");
});
});
Try that.

Categories

Resources