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>
Related
I'm using ajax function to send select values to my php script, it is working fine but i have issue when there user add multiple data, i have option to add multiple add child in the form, user can add as many fields.
I need a each loop here. This is my code.
<select class="firstpiller" name="firstpiller">
<option value="0">0</option>
<option value="1">1</option>
</select>
<select class="thirdpiller" name="thirdpiller">
<option value="2">2</option>
<option value="3">3</option>
</select>
if (document.querySelector('[name=firstpiller]') != null){
var firstpiller = document.querySelector('[name=firstpiller]').value;
} else {
var firstpiller = null;
}
if (document.querySelector('[name=thirdpiller]') != null){
var thirdpiller = document.querySelector('[name=thirdpiller]').value;
} else {
var thirdpiller = null;
}
var stepVar = firstpiller + "--" + thirdpiller;
Can anyone help how should i write each loop here?
Thanks in advance.
add a common class to the select say you are given a class .myselect, now you can do something like below
var stepvar = '';
$('.myselect').each(function(value){
stepvar += '--' + value.val();
});
alert(stepvar);
This is literally the first time I've worked with jQuery and I've read the entire chapter in my textbook but am finding a hard time wrapping my head around it. I'm attempting to convert a JavaScript function (a simple option selection drop-down list) to jQuery. I've attempted a few lines of code that I've gotten from the book or from w3schools and api.query but to no avail. I'll try to make this quick and simple, I just cannot understand jQuery for some reason.
What I've attempted usually doesn't work. Before my option list works fine, then I tried experimenting but I didn't get too far.
I also apolgize for the vagueness of the question, I'd appreciate any help!
Here's something I've tried:
$(document).ready( function () {
var c = ???
if ($(c...
calc.js and index.html below it
function selectedCountry() {
var c = document.getElementById("countryChooser").value;
var message;
if (c == "nothing") { //if they selected the default option, error pops up.
alert("Please select a country.");
} else if (c == "usa") {
message = "United States of America";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else if (c == "canada") {
message = "Canada";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else {
message = "Mexico";
document.getElementById("count").innerHTML = "Your country is: " + message;
}
}
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser" onchange="selectedCountry()">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Through jQuery you can do it like below:-
Example:-
$(document).ready(function(){
$('#countryChooser').change(function(){ // on change of select
if($(this).val()!=='nothing'){ // if selected value is some country
$('#count').html("Your country is: "+$("#countryChooser option:selected").text()); // get country name and add it to paragraph
}else{
$('#count').html("");
alert('Please select a country.'); // alert for selecting a country
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Get an element by id:
var c = $('#countryChooser');
Get the value of this input/select element
var value = c.val();
Set the html of an element using the element id
$('#count').html('some html');
or set the text (html is not parsed this way)
$('#count').text('some html');
You can also handle the events with jQuery
$(document).ready(function() {
$('#countryChooser').on('change', function(event) {
// this is the DOM element with the id 'countryChooser'
// same as the native: var val = this.value;
var val = $(this).val();
// ...
});
});
I have bind the onchange() event of your select list inside the jQuery(document).ready() method. check this out-
// Updated code--
$(document).ready(function (){
$('#countryChooser').on('change' ,function () {
if(this.selectedIndex){
$('#count').html("Your country is: "+ this.options[this.selectedIndex].text);
}else{
$('#count').html("");
alert("Please select a country.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
$('#countryChooser').change(function(){
var selectedCountry = $(this).val();
if(selectedCountry == 'nothing'){
console.log('Select A country');
}
else{
$('#count').html('Your country is '+$('#countryChooser option:selected').text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--JavaSript link -->
<select name="countrylist" id="countryChooser" >
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Please check the code might help you out
thanks
I am using HTML5 Datalist for autosuggestion in my project.by default HTML5 follows the keyword contains approach rather then starts with appoarch.or example if i have a datalist of one,two,three means if i type o in the search box,it is showing both one and two.but what i am expecting is to show only one in the autosuggestion list.guys pleas help me out how to achieve this.
<input list="sampleList" >
<datalist id="sampleList">
<option value="one">
<option value="two">
<option value="three">
</datalist>
A possible duplicate to: HTML datalist: Is there a way to autocomplete based character order?.
JSFiddle Link by Buddhi Madarasinghe from the site above.
<input type="text" list="countries" name="mycountry" id="countryInput" />
<datalist id="countries">
<option value="India">India</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Israel">Israel</option>
</datalist>
You can achieve it with the help of JavaScript.
var initialArray = [];
initialArray = $('#countries option');
$("#countryInput").keyup(function() {
var inputVal = $('#countryInput').val();
var first = [];
first = $('#countries option');
if (inputVal != '' && inputVal!= 'undefined') {
var options = '';
for (var i = 0; i < first.length; i++) {
if (first[i].value.toLowerCase().startsWith(inputVal.toLowerCase())) {
options += '<option value="' + first[i].value + '" />';
}
}
document.getElementById('countries').innerHTML = options;
}
else
{
var options = '';
for (var i = 0; i < initialArray.length; i++) {
options += '<option value="' + initialArray[i].value + '" />';
}
document.getElementById('countries').innerHTML = options;
}
});
You can even modify the code for different search queries:
JSFiddle Link
Only by javascript (perhaps jQuery autosuggest) as default suggestions depends on browser's implementation of the datalist tag. And It's very poor. But, As long as I remember, IE compares only first letter
I have one drop-down list that has numbers 1-10 and a proceed button.
What I want is, when the user select a specific number and the user click the proceed button, it should display a number of textboxes equal to the number of selected in the drop-down list.
is it possible to doit with a loop? or any suggestions?
Using addEventListener, you can generate the textboxes as:
function create(param) {
//'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
for (i = 0; i < param; i += 1) {
target.innerHTML += '<input type="text" name="Fname"><br /><br />';
}
}
document.getElementById('createTextboxes').addEventListener('change', function () {
create(this.value);
}, false);
JsFiddle Demo
Here is an option - using jQuery cos its much cooler than just plain JS - first determine the number of textboxes required based on the value of the select list. Then create a string with the required number of textboxes and third - apply that HTMl to the empty div. Note that the reason for building the textboxes as a string and then adding it to the div is that this requires only one alteration to the DOM - doing it on each iteration would require altering the DOM numerous times. Its fine if you don't want to use jQuery - as the other answers demonstrate - all things done in jQ can be done in JS - but its just more fun to use.
$(document).ready(function(){
$('#selection').change(function(){
var num = $(this).val();
var HTML='';
for(i = 0; i < num; i++){
HTML += "<input type='text' name='textBox"+i+"' /><br/>"
}
$('#newDiv').html(HTML);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for = "selection"> Enter the number of textboxes required</label>
<select id="selection">
<option disabled selected></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<hr/>
<div id="newDiv"></div>
Try this... Pure Js and Fast
function creator(){
var tb = document.getElementById("generator").value
var area = document.getElementById("tbArea");
var childcount = area.childNodes.length;
if(childcount != 0)
{ for(var i = childcount-1; i > -1;i--)
{
area.removeChild(area.childNodes[i]);
}
}
for(var i =0; i < tb; i++){
var tbox = document.createElement('input');
document.getElementById("tbArea").appendChild(tbox);
}
}
document.getElementById("generator").onchange = creator;
<select id='generator'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
</select>
<div id='tbArea'></div>
Hello this is my current code:
<select id="link_course">
<option value="">Select Course</option>
<option value="ALL">ALL</option>
<option value="BSIT" selected>BSIT</option>
<option value="BSA">BSA</option>
<option value="BSBA">BSBA</option>
<option value="BSHRTM">BSHRTM</option>
</select>
<script>
$("#link_course").change(function()
{
document.location.href = "home.php?course=" + $(this).val();
});
</script>
If you click any of those options, for example BSBA, it will go to home.php?course=BSBA, and also you can see that the selected attribute is on the option BSIT. What I wanted to do is whenever I click another link, for example BSHRTM, the selected attribute will go to BSHRTM like it would be <option value="BSHRTM" selected>BSHRTM</option>. Any thoughts?
You can do selection via JavaScript :
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
if(getQueryVariable('course') != false) {
$('#link_course option[value="' + getQueryVariable('course') + '"]').prop('selected', true);
}
Reference
After loading the new page, you need to run JavaScript code to set the value on the correct item from the list.
Use window.location.hrefto get current URL. Then check on which page is user currently on and finally select corresponding option.
if(window.location.href.indexOf('home.php?course=BSHRTM)') != -1) {
$('select#link_course option[value=BSHRTM]').attr("selected","selected");
}
To avoid code duplication see Parse query string in JavaScript
You should do it in PHP:
<option value="BSHRTM" <?php if($course == 'BSHRTM') echo 'selected';?>>
Supposing that you previsously set $course = $_GET['course'];