Search query parameter Javascript - javascript

I want to adding and set parameters for query string with same key and different value .
url.com/product.php?order=price.low&order=quantity.low
so there is a same key called order with different value.
i created some radio button for change product sort.
and add event listener like this :
function lowQRadio() {
document.getElementById("radio-qlow").checked=true;
params.set("order","quantity.low");
window.location.href=(location.pathname + '?' + params);
}
function highQRadio() {
document.getElementById("radio-qhigh").checked=true;
params.set("order","quantity.high");
window.location.href=(location.pathname + '?' + params);
}
function lowPRadio(){
document.getElementById("radio-plow").checked=true;
params.set("order","price.low");
window.location.href=(location.pathname + '?' + params);
}
function highPRadio(){
document.getElementById("radio-phigh").checked=true;
params.set("order","price.high");
window.location.href=(location.pathname + '?' + params);
}
some variable defined above this code and here is variables:
let url = new URL(window.location.href);
let params = new URLSearchParams(url.search);
if(params.has("order")){
var aflag=params.getAll("order");
console.log(aflag.length);
if(aflag[aflag.length-1]==="quantity.low" || aflag[aflag.length-2]==="quantity.low") {
document.getElementById("radio-qlow").checked = true;
}
else if(aflag[aflag.length-1]==="quantity.high" || aflag[aflag.length-2]==="quantity.high"){
document.getElementById("radio-qhigh").checked=true;
}
else if(aflag[aflag.length-1]==="price.low" || aflag[aflag.length-2]==="price.low"){
document.getElementById("radio-plow").checked=true;
}
else if(aflag[aflag.length-1]==="price.high" || aflag[aflag.length-2]==="price.high"){
document.getElementById("radio-phigh").checked=true;
}
so i want when user choose sort by price and quantity ,both of this radio button will checked and query changed and if user choose one of sort method ,only one parameter set and if choose another one ,both of these checked and page will be refresh
the php code or back-end worked but js code work only for one type of radio button and both sort not working!!
please help me to fix this,thanks with regards

The query string is a name-value pair collection. Names must be unique. Do you want to do something like
url.html?OrderBy=col1,col2,col3
Use a delimited string as the query string parameter value, then in your php code split the value and use logic to apply the order by.

Related

Looping through a text file in React or JS

I'm getting a text file as API response from here https://api.pwnedpasswords.com/range/D0597 that looks like this
007F24D71AC210875C58951F5D99ACC71D2:3
0097880A0B749B59A5F7FD0D943A133ADE1:4
00CAEC74DE2FA10428E6D3FAD065D53B865:4
00F8C45A33243D0A4FD293DC70130E82E00:1
024556F4CB4A1DA178A6EC4E43ECED22467:1
030BA417A72B878EC629BD585705D306260:1
03664676C5A123BE6927DB6BAC5F5427468:1
0491953CF08D183806C28DB827835D27348:1
04BA7B823BBB772A8172F94A757AAF59A39:2
04D3C208B89E12C60AB12900690E86C13DA:1
06856BA40BCB6BCE13C40F271487F347BA5:1
071E3D06232DEA85E297102F6037164C033:5
and I need to loop through and check if the value of an input is included in the list of first item. If present I need to show the second value after ":".
I was trying to use split() for new line and ":" and iterate but kind of got lost.
// data is your text file
var foo = data.split("\n"),
bar = "your input";
Object.keys(foo).forEach(function(key) {
if (foo[key].split(":")[0] === bar) {
console.log(foo[key].split(":")[1]);
}
});

Persisting an array to use on another html page

I need to be able to display from information in an array.
A selection is chosen by checkboxes, which is stored in the temporarySelection, then the temporarySelection info is transferred to other arrays (eg. added to restaurantSelection, then cleared for the next choices).
I need to then be able to display these arrays on a separate html page.
There's 4 different arrays to transfer to the second html page, placeSelection, hotelSelection, restaurantSelections, and sightSelections.
I've had a look around, tried a few different things, but nothing seems to be working.
Any ideas?
I've already attempted to use localstorage in a function (although I may not hav got it quite right).
Looked into cookies but I've been told not to do this as it is unnecessary as only Javascript will be using it.
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
if(!temporarySelection.includes(locationName.innerHTML)) {
console.log('pushing ' + locationName.innerHTML + ' into
temporarySelection')
temporarySelection.push(locationName.innerHTML);
} else {
var index = temporarySelection.indexOf(locationName.innerHTML);
console.log('Removing index number: ', index)
temporarySelection.splice(index, 1);
}
}
I hope that the second html page, the "results page" will show the arrays for placeSelection, hotelSelection, restaurantSelections, and sightSelections in 4 separate boxes.
Not sure how you are setting local storage. Below are the two small functions to set and get values for your array in store.
function setStore(temporarySelection){
localStorage.setItem("temporarySelection", JSON.stringify(temporarySelection));
}
function getStore(){
const temporarySelection = localStorage.getItem("temporarySelection");
if(temporarySelection)
{
return JSON.parse(temporarySelection)
}
else{
return [];
}
}
Here is your code with these functions in use
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
if(!temporarySelection.includes(locationName.innerHTML)) {
console.log('pushing ' + locationName.innerHTML + ' into
temporarySelection')
temporarySelection.push(locationName.innerHTML);
} else {
var index = temporarySelection.indexOf(locationName.innerHTML);
console.log('Removing index number: ', index)
temporarySelection.splice(index, 1);
}
setStore(temporarySelection)
}
Now you can get your store values with getStore function in any page.

Show DIV only when url has specific query parameter string jQuery

I am trying to show the hidden div only when the specific url have specific value, like below:
var url = window.location.search;
if (url.match("Test Value")) {
$(".testdiv").show();
}
else if (url.match("Some Text")){
$(".textdiv").show();
}
Not sure if I am trying the correct way and if the none of the string matching, its showing error, what appproach should I try here?
You can use URL.searchParams.
new URL(location).searchParams.get('nameOfQueryStringParam')
Example:
const param = new URL('http://example.com?x=1&y=2').searchParams
console.log(param.get('x')) // 1
console.log(param.get('y')) // 2
console.log(param.get('z')) // null
Then, use it for your purpose like ..
param.get('x') ? $('#div1').show() : $('#div2').show()

Updating multiple dropdowns with json data

What is good practice when storing an HTML select dropdown into a JavaScript variable. I also need to capture the value which they selected and pass that through.
I originally tried to use jQuery to create the option and hold it in a variable but it would error out.
var keyNamesList = $('<option></option>').val('').html('Select a Key');
I then used an HTML string and appended the options list in a loop with with more HTML represented as a string. See JSFIDDLE link for a mock up.
var keyNamesList = "<option value = ''> Select an item</option>"
keyNamesList += "<option value = '"+data.key+"'>" + data.value + "</option>";
JSFIDDLE
$('<option></option>')...
Should just be $('option').
PS: What are you trying to do?
It's unlikely that using an append per option and setting the value and content via the DOM API is going to cause a big performance hit, but just as general rule it's considered good practice to avoid multiple append and DOM mutation calls if you can, so I would normally build a single HTML string:
function getOptions(data, blank) {
var optTpl = '<option value="%key%">%label%</option>',
options = [];
if (blank) {
// if blank is truthy then append an option - if bool true then
// a default label, otherwise use the value of blank as label
options.push(optTpl
.replace('%key%','')
.replace('%label%', (blank === true ? 'Select one...' : blank))
);
}
$.each(data, function (i, datum){
options.push(optTpl
.replace('%key%',datum.key)
.replace('%label%', datum.value)
);
});
return options.join('');
}
// usage:
$('theSelectElement').append(getOptions(data, 'Select something!'));
I like to use a kind of template and call string replacements but you could build the strings on each iteration like you proposed in your question:
options.push("<option value = '"+data.key+"'>" + data.value + "</option>");
Example un-integrated with yours: http://jsfiddle.net/8tjwL6u5/

"reference" in javascript?

I have a set of variables that I use to tell if an question in a survey has been answered, and they are initially set to false: q0=false; q1=false; qX=false;. Then in the body, I have several input type="radio"s with .change(function(){ counter_radio(q#,INPUT'S_ID); }); binded to each. This is the code for function counter_radio():
function counter_radio(q,id){
if (q===false) {
q=true;
count++;
$("#counter").css("width", count);
$("#percent").text(count + "%");
}
$("span#"+id).append(", "+q);
$("span#"+id).fadeIn();
}
I expect that the counter to only increment once (the first time a radio from a set is selected). However, the counter is incrementing every time the input type=radio changes. My problem is that, q returns true, but q# remains false. In php, I would make q a reference to q# so when q is set to true, q# is also set to true. Is there such a construct in javascript?
You could change your bound function to:
.change(function(){ q# = counter_radio(q#,INPUT'S_ID); });
and add a return q; to the end of your counter_radio function.
As others have said, simple variables like booleans are passed by value, not by reference in Javascript so there is no way to change that.
If you have multiple variables like this:
var q0=false, q1=false, qX=false;
then, it might be easier to put them in an array:
var qArray = [false, false, false];
Then, because arrays and objects are passed in a way that you can modify the original, you can pass the array and an index to your function like this and you are then able to modify the original data from your function:
function counter_radio(q, index, id){
if (q[index] === false) {
q[index] = true;
count++;
$("#counter").css("width", count);
$("#percent").text(count + "%");
}
$("span#"+id).append(", " + q[index]);
$("span#"+id).fadeIn();
}
counter_radio(qArray, 2, id);
There's no native syntax for that, but you can e.g. use objects for that:
function counter_radio(q_,id){
if (q_.ref===false) {
q_.ref=true;
count++;
$("#counter").css("width", count);
$("#percent").text(count + "%");
}
$("span#"+id).append(", "+q);
$("span#"+id).fadeIn();
}
I would collect the values when the user submits the form:
jQuery('radio[name=...]:checked').val()
If you want to warn the user that not all questions have been answered, use the jQuery validation plugin.

Categories

Resources