remove the ? and name= in get method html - javascript

I made a quick code in html and js. The thing i want to do is via method get, to send the <select> into the url but without the ? symbol, and also the names in the select attributes. For example if I click the button, the url will appear
https://mytesting.com/?marca=HEREGOESTHESELECTEDITEM&modelo=HEREGOESTHESELECTEDITEM&ano=HEREGOESTHESELECTEDITEM`
What i want to do, is just to remove the ? and the names marca= &modelo= and &ano= and only show the selected items. For example:
`https://mytesting.com/Firstelement-Secondelement-Thirdelement
This is my html code
<form name="marcas" action="https://mytesting.com">
<select name="marca" onchange="relation()">
<option value="-">Marca</option>
<option value="vw">VW</option>
<option value="nissan">Nissan</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="buick">Buick</option>
<option value="chevrolet">Chevrolet</option>
</select>
<select name="modelo">
<option value="modelo">Modelo</option>"
</select>
<select name="ano">
<option value="ano">Año</option>
</select>
<button class="button1" id="send" type="submit" method="GET">Buscar</button>
</form>
And the javascript I made, just shows the corresponding items that are in an array.

You'll need to use JavaScript to intercept the submit event and craft the new URL
document.querySelector("form[name=marcas]").addEventListener("submit", (e) => {
e.preventDefault(); // stop the normal form submit action
const data = new FormData(e.target); // capture all the fields
const url = new URL(e.target.action); // start with the form action
// create the pathname by joining together all the field values
url.pathname = Array.from(data, ([_, val]) => val).join("-");
// now redirect to the new URL
location.href = url;
});

Related

How to change URL based on option selected so that the new url will go to page with that option pre-selected?

For instance if I have a page with two options and I click option on option two. I want to create a new url where option 2 has already been selected.
<select>
<option>Opttion 1</option>
<option >Option 2</option>
</select>
To keep it simple you can use URL Search params for that. URL Search Params can for example look like this yourlocation.com/?param1=value param1, in that case, will be your parameter and value is its value.
You can read the param value through javascript like so:
let params = new URL(document.location).searchParams;
let selectedOption = params.get("option");
console.log(selectedOption);
For your example you can change the HTML Code like so:
<select>
<option id="option1">Option 1</option>
<option id="option2">Option 2</option>
</select>
and add some javascript:
let params = new URL(document.location).searchParams;
let selectedOption = params.get("option");
document
.getElementById("option" + selectedOption)
.setAttribute("selected", true);
This code will set the selected Option to the one in the search query.

Pre-select a dropdown in a form from an external URL link

I have this form, and I can't change anything about it (ids, vals, etc) because its auto generated by my website builder. Is it possible to use code or even better, just use the URL to auto select an option? For example, use the URL
https://mywebsite.com/GCValue=50/
to select the 50 option in the form below, instead of the 10 that it will default on? I'm a beginner with JS and JQuery, so I'm happy to use those and learn a little bit about it during the process, if its possible.
<select id=GCValue>
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select> <br />
Any help or external links pointing me in the right direction appreciated.
Using Just One Variable from JS Document Pathname
Use window.location.pathname to get the path of the current page, then use a simple regex.exec(url) to capture anything that matches /=([0-9])+/. This will match anything in the format of "=12345", and return "12345" as the match.
var url = "https://mywebsite.com/GCValue=50/";
// in reality, use this:
// var url = window.location.pathname;
var regex = /=([0-9]+)/g;
var match = regex.exec(url);
document.getElementById("GCValue").value = match[1];
<select id="GCValue">
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select> <br />
Using Many Variables from JS Document Pathname
If you wanted to use many parameters, just extend the same logic. For instance, imagine: /GCValue=50/Page=765/Index=42/...
var url = "https://mywebsite.com/GCValue=50/Page=765/Index=42/";
// in reality, use this:
// var url = window.location.pathname;
var regex = /([A-Za-z0-9]+)=([0-9]+)/g;
var match;
while ((match = regex.exec(url)) != null) {
document.getElementById(match[1]).value = match[2];
}
<select id="GCValue">
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select> <br />
<input id="Page" type="text"><br>
<input id="Index" type="text">
UPDATED
Here is a solution using url query parameters.
// Your link should look like this: https://www.boothemusic.com/gift-card/?price=50
const selectList = document.getElementById('GCValue');
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const price = urlParams.get('price'); // change "price" to anything you want.
for (let option of selectList.options) {
let chosen = option.value;
if(chosen === price) {
selectList.value = price;
}
}
<select id="GCValue">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="250">250</option>
</select>
const price = urlParams.get('price'); assigns the value associated with the given search parameter to price (Check this article to learn more about URLSearchParams).
Then for-of loop skims through select options and looks for a match for price variable. If any of the options match price (50 in this case), then its value is set as price hence selecting 50 on your dropdown.

ASP.NET MVC4 with Razor - Filtering dropdownlist by value selected from another dropdownlist

I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});

Post URL from multiple <select> elements

I have a page with isotope filter. It's using the combination filters with hash history. So whenever multiple filters are selected it updates the URL like this:
example.com/portfolio/#.filter1&.filter4&.filter6
Then I have a search form with multiple 'select' elements:
<form id="search-form" method="post">
<select>
<option value="filter1">Filter Name</option>
<option value="filter2">Filter Name</option>
<option value="filter3">Filter Name</option>
</select>
<select>
<option value="filter4">Filter Name</option>
<option value="filter5">Filter Name</option>
<option value="filter6">Filter Name</option>
</select>
...
<input type="submit" value="Search" />
</form>
I would like to combine the values from all the selected options of each 'select' element into the single URL and redirect to isotope ('portfolio') page with that combined value.
What would be the best way to achieve that? I'm unable to figure it out.
Try this in your js:
var data = { 'filters' : arrayHere };
$.ajax({
type: 'POST',
url: 'your url here',
data: data,
success: function(re) {
console.log('this is your return', re);
}
})
Make an array using $.each, and populate all values inside the array, then post it view ajax call.
1) Keep the selects out of the form and use IDs to access the selected values.
2) Create a hidden input field in the form
3) use onsubmit="mergeSelects()" javascript event.
4) create a function in js
function mergeSelects(){
//get all the values of selects
// append then and generate a string may be
var mergedStringVal = ""; // <--- store values here
// Set it in the hidden input field created in the form and submit them
document.getElementById("mergedSelects").val(mergedStringVal);
}

Sorting via dropdown and updating the querystring

For paging I have this code which enables me to update the querystring without losing any elements in the querystring.
var tRVD = new RouteValueDictionary(ViewContext.RouteData.Values);
foreach (string key in Request.QueryString.Keys)
{
tRVD[key] = Request.QueryString[key];
}
tRVD["page"] = #i;
#Html.ActionLink(#i.ToString(CultureInfo.InvariantCulture), "Index", tRVD);
I need to do the same with sorting. I have the following code but of course the querystring is overwritten by sortby. What I need is the same as I have for paging, something that just adds sortby to the querstring if it is not there and updates it if it is. How is this possible?
<form name="sortbyformtop">
<select onchange="location.href=this.options[this.selectedIndex].value" name="sortbyselecttop">
<option value=""></option>
<option value="sortby=accommodationtype">Accommodation type</option>
<option value="sortby=mostreviewed">Most reviewed</option>
<option value="sortby=lowestprice">Lowest price</option>
</select>
</form>
So, what I'm trying to achieve is setting the querystring to the same value as it is now plus sortby.
You need to add an <input type="hidden"> to your form for each value in the querystring.

Categories