I have this code that adds ?prside=5 for example. However, if you change this and the url already is &prside=5, it just appends it again (&prside=5&prside=40).
How do i update it instead of appending it, if it's already present?
<select name="prside" onchange="document.location.href = document.location.href + \'&prside=\' + this.value">
<option>Annoncer pr. side</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="40">40</option>
</select>
EDIT:
There is other GET variables in the real URL too. And the above script does work, it's just not very pretty with multiple &prside
You could check for the existence of prside using the string indexOf method, then you could use a regular expression to replace the value if it exists:
href = document.location.href;
if(!~href.indexOf('prside'))
document.location.href = href + 'prside=' + this.value;
else
document.location.href = href.replace(/(prside=)\d+/, '$1' + this.value)
Here is a one liner if you want to put it straight into the HTML
document.location.href = !~document.location.href.indexOf('prside') ? document.location.href + 'prside=' + this.value : document.location.href.replace(/(prside=)\d+/, '$1' + this.value);
Related
I would like to use jquery to change a particular value in the query string by doing a find and replace of that value based on what is selected from a dropdown option on the page. For example:
Let's say we have the following query string on the current page: ?field1=value1&field2=value2&archived=yes
With the dropdown options being:
Non-Archived
Archived
if someone selects "Non-Archived" the jquery function should do a find and replace on the current query string and set archived=yes to archived=no and then refresh the page.
Here's some code that I have now but it doesn't do a find and replace, it just takes what value I select from the dropdown and then changes the page based on the option value set in the drop down html.
<script type="text/javascript" src="/js/jQuery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery("#dropdown").change(function(e){
window.location.href = jQuery("#dropdown").val();
});});
</script>
<select class="dropdown" id="dropdown">
<option value="#" selected="selected">Choose Type</option>
<option value="(set archived=no)">Non-Archived</option>
<option value="(set archived=yes)">Archived</option>
</select>
Any help would be greatly appreciated!
Try this
jQuery
jQuery(document).ready(function () {
jQuery("#dropdown").change(function (e) {
if (window.location.href.indexOf("archived") > -1) {
window.location.href.replace(/(archived=yes|archived=no)/g, "archived=" + jQuery("#dropdown ").val());
} else {
window.location.href += "archived=" + jQuery("#dropdown ").val();
}
});
});
HTML
<select class="dropdown" id="dropdown">
<option value="#" selected="selected">Choose Type</option>
<option value="no">Non-Archived</option>
<option value="yes">Archived</option>
</select>
This seems to work:
JSFiddle Demo
var href="?field1=value1&field2=value2&archived=yes";
var testUrl = $(location).attr('href');
alert('Current URL = ' + testUrl);
jQuery("#dropdown").change(function(e){
if($("#dropdown").val() == "(set archived=no)") {
href = href.replace("archived=yes", "archived=no");
} else if($("#dropdown").val() == "(set archived=yes)") {
href = href.replace("archived=no", "archived=yes");
}
alert(href);
window.location.href = href;
});
I have a URL that does a filter and spits out some products the structure looks like below:
/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=185,223
Now on this there is a sort function and if I was to use this with out filtering as above the URL would look like the below:
/Products/Catalogue.aspx?orderby=price&desc=1&psize=9
If I currently try and filter and then sort, the sort overwrites myfilter, so the filter becomes null and void.
So what I need it do is be aware that IF i have a filter then append the sorting after 'catfilter=' part in the URL so the URL would then look like
/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=8,188&orderby=man&desc=0&psize=36
The gotcha is that there is not always going to be a filter added in which case the URL would be:
/Products/Catalogue.aspx
<select id="listSort" class="NormalTextBox SortCatalogue" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listLength')[getElementById('listLength').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
<option value="?orderby=name&desc=0&">Sort by</option>
<option value="?orderby=price&desc=0">Lowest price</option>
<option value="?orderby=price&desc=1">Highest price</option>
<option value="?orderby=man&desc=0">Brand A-Z</option>
<option value="?orderby=man&desc=1">Brand Z-A</option>
<option value="?orderby=name&desc=0">Title A-Z</option>
<option value="?orderby=name&desc=1">Title Z-A</option>
<option value="?orderby=ref&desc=0">Code asc</option>
<option value="?orderby=ref&desc=1">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listSort')[getElementById('listSort').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
<option value="?psize=9&foo">Page size</option>
<option value="?psize=6">6 per page</option>
<option value="?psize=9">9 per page</option>
<option value="?psize=18">18 per page</option>
<option value="?psize=36">36 per page</option>
</select>
<script type="text/javascript">
var searchString = window.location.search.substring(1);
var i, val;
var params = searchString.replace('?','&').split('&');
var pgsize,pgorder,pdesc,searchstr;
pgsize = 9;
pgorder = 'name';
pdesc = 0;
searchstr='';
for (i=0;i<params.length;i++) {
val = params[i].split('=');
if(val[0]== "psize")
pgsize=val[1];
else if(val[0]== "orderby")
pgorder=val[1];
else if(val[0]== "desc")
pdesc=val[1];
else if((val[0]).toLowerCase()== "search") {
searchstr=val[1];
}
}
document.getElementById('listLength').value='?psize=' + pgsize;
document.getElementById('listSort').value ='?orderby=' + pgorder + '&desc=' + pdesc;
if(searchstr!='') {
searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
document.getElementById('searchtxthdrright').innerHTML= '"' ;
document.getElementById('searchtxt').innerHTML = searchstr;
}
</script>
Ok lets take a step back from the problem. I think you need to add a bit more structure instead of haphazardly adding and removing bits of url code here and there :)
You have tagged the post as jQuery so i'm going to use that although you haven't actually used it in your posted code.
The whole idea is going to be around creating a JavaScript object and using it as a lightweight dictionary, and the jQuery .param() function which will encode it for us at the end.
Lets change the markup to this:
<select id="listSort" class="NormalTextBox SortCatalogue">
<option value="nameDesc">Sort by</option>
<option value="priceAsc">Lowest price</option>
<option value="priceDesc">Highest price</option>
<option value="manAsc">Brand A-Z</option>
<option value="manDesc">Brand Z-A</option>
<option value="nameAsc">Title A-Z</option>
<option value="nameDesc">Title Z-A</option>
<option value="refAsc">Code asc</option>
<option value="refDesc">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength">
<option value="9">Page size</option>
<option value="6">6 per page</option>
<option value="9">9 per page</option>
<option value="18">18 per page</option>
<option value="36">36 per page</option>
</select>
<input type="text" id="searchstr">
<button id="searchbutton">Search!</button>
As you will see I've also thrown in a textbox and a button as you refer to searchstr in your code.
Instead of encoding and extracting we are just going to store some parseable values in the select options. We're also going to use an unobtrusive javascript technique by using the ID to attach an onchange handler rather than injecting the javascript into the markup (this will be added later on).
Now we need to write some JavaScript code that can build us a querystring. Instead of directly building a querystring though we will be making a javascript object. Then later on that will be used to generate the query string.
I've written a search function that just displays the query string we generated rather than redirect the user.
I've also added in some event handlers so this is triggered as your code was triggering.
function getFiltersAsQueryString() {
var $listSort = $("#listSort"),
$listLength = $("#listLength"),
$searchQuery = $("#searchstr");
queryStringDict = {};
// extract page size
queryStringDict["psize"] = $listLength.find("option:selected").val();
// extract sort order and direction
var selectedItem = $listSort.find("option:selected").val();
queryStringDict["orderby"] = /^[a-z]*/.exec(selectedItem)[0];
queryStringDict["desc"] = /Desc$/.exec(selectedItem) == "Desc" ? 1 : 0;
// extract search
queryStringDict["search"] = $searchQuery.val();
return $.param(queryStringDict);
}
function searchWithFilters() {
// normally you would do a window.location here to redirect
alert(getFiltersAsQueryString());
}
$(document).ready(function () {
// wire up our handlers
$("#listSort").change(searchWithFilters);
$("#listLength").change(searchWithFilters);
$("#searchbutton").click(searchWithFilters);
});
And then at the end of the day when you put all this together you get this:
http://jsfiddle.net/rtpHarry/pdhCF/3/
I don't think this is quite a complete solution yet.
Need to add in the cat filter
Probably want to preselect the controls based on the query string?
I just wanted to post this to see if its going in the right direction.
Hugly helpful thank you, ended up going with this some JS and Jquery in up to come up with the complete solution:
<script type="text/javascript">
var searchString = window.location.search.substring(1);
var i, val;
var params = searchString.replace('?','&').split('&');
var pgsize,pgorder,pdesc,searchstr,catfilter;
pgsize = 9;
pgorder = 'name';
pdesc = 0;
searchstr='';
for (i=0;i<params.length;i++) {
val = params[i].split('=');
if(val[0]== "psize")
pgsize=val[1];
else if(val[0]== "orderby")
pgorder=val[1];
else if(val[0]== "desc")
pdesc=val[1];
else if(val[0]== "catfilter")
catfilter=val[1];
else if((val[0]).toLowerCase()== "search")
{ searchstr=val[1]; }
}
document.getElementById('listLength').value='?psize=' + pgsize;
document.getElementById('listSort').value ='?orderby=' pgorder '&desc=' + pdesc;
if(searchstr!='')
{
searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
document.getElementById('searchtxthdrright').innerHTML= '"' ;
document.getElementById('searchtxt').innerHTML = searchstr;
}
if(catfilter)
{
document.getElementById('searchstrdiv').innerHTML= document.getElementById('searchstrdiv').innerHTML + '&catfilter=' + catfilter ;
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.SortCatalogue').removeAttr('onchange');
$('.SortCatalogue').change(function() {newURL();});
$('.PageLength').removeAttr('onchange');
$('.PageLength').change(function() {newURL();});
function newURL()
{
var newParams = document.getElementById('listSort') [document.getElementById('listSort').selectedIndex].value + '&' + document.getElementById('listLength') [document.getElementById('listLength').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');
var oldPathname = location.pathname;
oldPathname = oldPathname.replace('/desc/','/').replace('/orderby/', '/');
document.location.href = oldPathname + newParams;
}
});
</script>
i have a <select> tag
i want redirect user onchange
i got an code and it works fine
the code is
<select onchange="if (this.value) window.location.href=this.value">
<option value="&s=1">1</option>
<option value="&s=2">2</option>
<option value="&s=3">3</option>
<option value="&s=4">4</option>
</select>
The problem here is :
The current link is: http://anlink.com/page.php?categ=4&subc=2
when i change option
i got redirected to http://anlink.com/&s=1
but i want it redirect to
http://anlink.com/page.php?categ=4&subc=2&s=1
So, i want edit the javascript code to something like this
if (this.value) window.location.href=
http://anlink.com/page.php?categ=4&subc=2 + this.value
i did not try this code but i think it will fail
This should work for you:
<script type="text/javascript">
function changeLocation(field) {
loc = String(window.location);
newLoc = loc.replace(/\&s=\d$/gi, "") + field.value;
window.location = newLoc;
}
</script>
<select onchange="changeLocation(this)">
<option value="&s=1">1</option>
<option value="&s=2">2</option>
<option value="&s=3">3</option>
<option value="&s=4">4</option>
</select>
It replaces any instance of &s= with a digit after it with nothing. Then it adds the new value. The reason for this is in case a &s= doesn't already exist.
If you would like the "s" value to change based on the "s" in the URL (i.e. when you load the page you have &s=3 in the URL, you want the select to be on "3" as well), make the following changes:
add onload="adjustS()" to the body
add an id to the select (I used "s")
add the following function:
function adjustS() {
sLoc = String(String(window.location).match(/\&s=\d$/gi)).replace(/\&s=/gi, "");
document.getElementById("s").selectedIndex = Number(sLoc)-1;
}
Try with:
window.location.href += this.value
Edit:
var href = window.location.href;
var re = /&s\=\d$/;
if (re.test(href)) {
window.location.href = href.replace(re, this.value);
} else {
window.location.href += this.value;
}
<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
<option value="">Choose Make</option>
<option value="2063">Acura</option>
<option value="2064">Honda</option>
</select>
i have a dropdown. i have read the href attribute of the link and assigned it as the value to dropdown. but i want to take only the number from the link and assign it as value to dropdown how can i do it.
<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
<option value="">Choose Make</option>
<option value="http://store.teknotik.com/category-s/2063.htm">Acura</option>
<option value="http://store.teknotik.com/category-s/2064.htm">Honda</option>
</select>
i have used following jquery to get the link as value
$("#data a").each(function(index) {
if ($(this).attr("class") == "subcategory_link") {
//document.getElementsById("year").innerHTML="<option value="+$(this).attr("href")+">test</option>";
lnk[cnt] = $(this).attr("href");
cnt = cnt + 1;
//alert($(this).attr("href"));
}
});
but i want to have the dropdown value as:
<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
<option value="">Choose Make</option>
<option value="2063">Acura</option>
<option value="2064">Honda</option>
</select>
i want to have only the number before .htm in above dropdownho send as value. Please advise.
Easy way:
$('#vehicle_make option[value!=""]').each(function() {
this.value = this.value.replace(/\D/g, "");
});
Live DEMO
\d // Numerical char
\D // Not numerical char <===
g // Is a flag which means find all the occurrences, and not only the first.
Excellent regex cheat sheet.
So I'm looking for all the non numerical chars (with \D)and "replace" them with an empty string.
Seems like there are two parts here ... getting just the number you want:
lnk[cnt] = $(this).attr('href').substring($(this).attr('href').lastIndexOf('/')+1);
lnk[cnt]=lnk[cnt].replace('.htm','');
(not the most elegant solution, but should work)
Then setting the value:
$("#vehicle_make").val(lnk[cnt])
You can find it like below ;
var url = $(this).attr("href");
var urlTemp1 = url.split("/");
var urlTemp2 = (urlTemp1[urlTemp1.length -1]).split(".");
var yourNumber = urlTemp2[0];
alert(yourNumber);
Try:
$(document).ready(function() {
$("select[name='vehicle_make'] option[value!='']").each(function() {
this.value = this.value.split("/").pop().split(".")[0];
});
});
Hope it helps
try the .replace('', '') function
.replace('http://store.teknotik.com/category-s/','').replace('.htm','')
should leave you with just the numerical value
I have a select element wrapped by a span element. I am not allowed to use the select id but I am allowed to use the span id.
I am trying to write a javascript/jquery function in which the input is a number i, which is one of the values of the select's options. The function will turn the relevant option to selected.
<span id="span_id">
<select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
<option value="1">cleaning</option>
<option value="2">food-2</option>
<option value="3">toilet</option>
<option value="4">baby</option>
<option value="6">knick-knacks</option>
<option value="9">junk-2</option>
<option value="10">cosmetics</option>
</select>
</span>
I wrote something as follows (this does not completely work, which is why I am posting this question):
function select_option(i) {
options = $('#span_id').children('select').children('option');
//alert(options.length); //7
//alert(options[0]); //[object HTMLOptionElement]
//alert(options[0].val()); //not a jquery element
//alert(options[0].value); //1
//the following does not seem to work since the elements of options are DOM ones not jquery's
option = options.find("[value='" + i + "']");
//alert(option.attr("value")); //undefined
option.attr('selected', 'selected');
}
Thanks!
Here's the simplest solution with a clear selector:
function select_option(i) {
return $('span#span_id select option[value="' + i + '"]').html();
}
With jQuery > 1.6.1 should be better to use this syntax:
$('#span_id select option[value="' + some_value + '"]').prop('selected', true);
Just wrap your option in $(option) to make it act the way you want it to. You can also make the code shorter by doing
$('#span_id > select > option[value="input your i here"]').attr("selected", "selected")
options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option);
here is the fiddle http://jsfiddle.net/hRFYF/
You can use .val() to select the value, like the following:
function select_option(i) {
$("#span_id select").val(i);
}
Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/
To get the value just use this:
<select id ="ari_select" onchange = "getvalue()">
<option value = "1"></option>
<option value = "2"></option>
<option value = "3"></option>
<option value = "4"></option>
</select>
<script>
function getvalue()
{
alert($("#ari_select option:selected").val());
}
</script>
this will fetch the values
function select_option(index)
{
var optwewant;
for (opts in $('#span_id').children('select'))
{
if (opts.value() = index)
{
optwewant = opts;
break;
}
}
alert (optwewant);
}
You can change with simple javascript
document.querySelector('#h273yrjdfhgsfyiruwyiywer').value='4'
<span id="span_id">
<select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
<option value="1">cleaning</option>
<option value="2">food-2</option>
<option value="3">toilet</option>
<option value="4">baby</option>
<option value="6">knick-knacks</option>
<option value="9">junk-2</option>
<option value="10">cosmetics</option>
</select>
</span>
$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);