Javascript: Appending second dropdown selection to URL - javascript

Hi I have two dropdowns in my webpage. How do I append the second dropdown selection to the URL without using.
window.location.href +="&selected2="+value2;
please tell me what change I must to the the function setsecondparam where value1 is the selection from the first dropdown.
function seturl(sel){
var value = sel.options[sel.selectedIndex].value;
window.location.href = "website.php?selected1="+value;
}
function setsecondparam(sel,value1)
{
var value2 = sel.options[sel.selectedIndex].value;
window.location.href ="website.php?selected1="+value1+"&selected2="+value2;
}
Thanks in advance

It's better to use one function. I wrote it more or less in ES5, you can change it to ES6 if you use babel.
function insertParams (key, value) {
let search = window.location.search;
let regex = new RegExp(key+"=[^\&]*");
search = search.replace(regex, key + '=' + value);
​
if (!regex.test(search)) {
search += (search.length > 0 ? '&' : '?') + key + '=' + value;
}
​
document.location.search = search;
}

Related

jQuery: reverse string slice function?

I have simple code that will replace the characters in a string with '*' and only displays the last 4 characters of the string. Example:
string = 424242424242
Should become:
********4242
The code that does that is this:
var str = $('.cc').val();
var trailingCharsIntactCount = 4;
str = new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice( -trailingCharsIntactCount);
$('.cc').val(str);
Now, I need to reverse that when the users focus on an input field.
This is a working fiddle:
https://jsfiddle.net/s66k9x1s/1/
Basically, I need to show/hide the input's value the same way I demonstrated in my fiddle.
Could someone please advice on how I can achieve this?
The string replacement cannot be reversed from thin air,
you need to save the original value somewhere.
You could use jQuery's .data(), for example.
Store the original value with .data('value', str),
and when the field receives the focus,
restore it from .data('value').
function getMaskedValue(str) {
var trailingCharsIntactCount = 4;
return new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice(-trailingCharsIntactCount);
}
var $cc = $('.cc');
var str = $cc.val();
$cc.data('value', str);
$cc
.val(getMaskedValue(str));
.focus(function() {
$(this).val($(this).data('value'));
});
And as #aaron pointed out,
after focus is lost, you also want to restore the masked value:
$cc
.focus(function() {
$(this).val($(this).data('value'));
})
.blur(function() {
str = $(this).val();
$(this).data('value', str);
$(this).val(getMaskedValue(str));
});
He is also right that you don't need .data(),
you could store the real value in a variable.
It will be good to hide it within a closure.
(See fiddle.)
(function() {
function getMaskedValue(s) {
var masklen = s.length - 4;
return s.substr(0, masklen).replace(/./g, '*') + s.substr(masklen);
}
var $cc = $('.cc');
var value = $cc.val();
$cc
.val(getMaskedValue(value))
.focus(function() {
$(this).val(value);
})
.blur(function() {
value = $(this).val();
$(this).val(getMaskedValue(value));
});
})();
I also simplified the implementation of computing the masked value,
which should perform better, eliminating array operations.
Leave the original value in str. Here's a clean and simple answer that includes re-hide on blur:
var cc = $('.cc');
var str;
var trailingCharsIntactCount = 4;
function getHiddenValue() {
str = cc.val();
return new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice(-trailingCharsIntactCount);
}
cc.val(getHiddenValue());
cc.focus(function() { cc.val(str); });
cc.blur(function() { cc.val(getHiddenValue()); });

Javascript - Incrementing specific numbers of a string

I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.

is there a way to exclude certain chars from encodeURIComponent

i am building a query string for my url and need to exclude certain chars from the encode.
I want to exclude the "&" and the "=" so that I can make a statement as such:
first=blah&second=blah and so on....
I guess the best way to put it is how do I stop them from being encoded?
some code:
else if (array[i].nodeName == "SELECT") {
if (array[i].id == "multiple") {
var selected = $.map($('#multiple option:selected'),
function (e) {
return $(e).val();
});
$.each(selected, function (index, value) {
name = array[i].name;
values += app + "\&" + key + "=";
});
} else {
name = arr[i].name;
values = arr[i].value;
}
}
key = encodeURIComponent(name);
value = encodeURIComponent(values);
queryString += name + "=" + values + "&";
Is there a way to exclude certain chars from encodeURIComponent?
No. It's a builtin function that takes exactly one argument.
You do need to encode & when it appears in the middle of a key or value so the simplest solution is to encode the individual names and values before combining them. Define
function emit(name, value) {
queryString += (queryString.indexOf("?") >= 0 ? "&" : "?")
+ encodeURIComponent(name) + "=" + encodeURIComponent(value);
}
and then call that function for each name/value pair in multiple selects or once for each other checked input.
else if (array[i].nodeName=="SELECT" ){
if(array[i].id == "multiple"){
var selected = $.map( $('#multiple option:selected'),
function(e){return $(e).val();});
$.each(selected, function(index, value){
emit(array[i].name, value);
});
} else {
emit(arr[i].name, arr[i].value);
}
}
Using encodeURI or similar will not properly encode #, = or other necessary code-points.
The name of the function should suggest how it should be used: call it on the pieces of the query string, not the whole query string.
edit — I've tried to create an example based on your code, but I can't figure out what it's trying to do. As it stands it seems to have syntax errors.

replace url parameter and text using jquery?

When I click search button the url parameter is taking care of. I need to change that url parameter name and value using jquery.
per example: search button clicked
http://testsite/_layouts/OSSSearchResults.aspx?k=deana&cs=This%20Site
Replace with:
http://testsite/_layouts/OSSSearchResults.aspx?k=deana&s=All%20Sites
I can not modify search button functionality, because it is out of the box functionality.
I can do changing url parameter and value. How can we do that?
Changing the parameter of a URL should be fairly straightfoward:
var param = window.location.href;
var param_q = param.split('?');
var param_ampersand = param_q[1].split('&');
var param_eq_1 = param_ampersand[0].split('=');
var param_eq_2 = param_ampersand[1].split('=');
var new_param_name_1 = 'test';
var new_param_value_1 = 'example';
var new_param_name_2 = 'test2';
var new_param_value_2 = 'example2';
// avoid infinite loop
if ((param_eq_1[0] != new_param_name_1 || param_eq_1[1] != new_param_value_1) || (param_eq_2[0] != new_param_name_2 || param_eq_2[1] != new_param_value_2)) window.location = param_q[0] + '?' + new_param_name_1 + '=' + new_param_value_1 + '&' + new_param_name_2 + '=' + new_param_value_2;
This worked for me in Chrome/FF. This just redirects the parameter - not sure if this is what you're looking for.
EDIT:
Added a logic to handle two parameters.

Append to URL and refresh page

I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?
this should work (not tested!)
var url = window.location.href;
if (url.indexOf('?') > -1){
url += '&param=1'
}else{
url += '?param=1'
}
window.location.href = url;
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '&param=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "&parameter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
location.href = location.href + "&parameter=" + value;
This line of JS code takes the link without params (ie before '?') and then append params to it.
window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
One small bug fix for #yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets

Categories

Resources