Let's say I'm on a page on my website: http://www.example.com/SearchResults.asp?Search=stackoverflow. Is it possible to use a JavaScript or jQuery code to get the variable "search" from the URL string and populate it into the value of the search box?
Basically I'll have my regular identified search box:
<input type="text" title="Search" id="search_box" />
And a user will search for something, but I will want a JavaScript or jQuery code that will get the value from the "search" variable in the URL string when the customer is on the Search.asp page and add it as the "value" to the input#search.
So the user will be on this page: http://www.example.com/SearchResults.asp?Search=stackoverflow and the search box will look like:
<input type="text" title="Search" id="search_box" value="stackoverflow" />
Thanks
You could try this function:
function getSearchVariable(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 unescape(pair[1]);
}else{
return false;
}
}
}
If this function is present in the sample you mentioned above, all you would call getSearchVariable("Search") to have "stackoverflow" returned.
So in your page, you would have a script element that looks like:
<script type="text/javascript">
function getSearchVariable(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 unescape(pair[1]).split("+").join(" ");
}else{
return "";
}
}
}
$(document).ready(function(){
$("#search_box").val(getSearchVariable("Search"));
});
</script>
Hope that helps!
You can use the JQuery URI plugin (shamelessly written by yours truly) to extract any piece of the URL: Specifically, $.uri(window.location.href).at("query").search yields "stackoverflow" for the said URL.
The overall flow would be to register a callback (fired on page-load) to analyze the URL and set the value of that form element, that is:
<script>
$(document).ready(function () {
$('#Search').val($.uri(window.location.href).at("query").search);
})
</script>
JavaScript
document.getElementById('Search').value = [(window.location.search.match(/(?:^|[&;])Search=([^&;]+)/) || [])[1]];
jsFiddle.
The wrapping it with [] means that if the value was not found, it will return an empty string instead of undefined (which would be set to the input's value and shown as the undefined string).
jQuery
$('#Search').val(function() {
return (window.location.search.match(/(?:^|[&;])Search=([^&;]+)/) || [])[1];
});
jsFiddle.
The (/* get GET param */ || []) is so the code will not error if the GET param was not found.
Related
I have a JavaScript function that works on its own, however, I am having difficulty getting it to function correctly inside of an HTML web page (no server backend). The function that works correctly by itself is:
function decodeUrlDefensev3(link) {
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
var link = "https://urldefense.com/v3/__https://files.bitsight.com/e3t/Ctc/LR*113/c1NcF04/VWyThK1lvg49W724nRX2d04lQW1xTZ7Q4QfX7gN6fpSV75nCTJV3Zsc37CgZP4N95fbTLz6L-gW48j6gR3bC3zwW6L_GnH7kDhzMW9418Rb3hJ605W2HjF587SWBXyW8RmYtF6fgdWYW5XQmQn1bFttzW5qPlhD5h_TCqW4-gDCr8x7fD0N4M_DVGdxFD9W2T0jhF4j9YsWW7603Qw8dF3j7W36QBsz4RM6hNW6Hpcdy8Qtmw4W8y5VBz2TLWGhVTNFr45gN7FDW7m9S0M1tvjXNW7vLHnj2945hZW437Z0x5Vd_ZcW7MjgJC89gYB6W2Y3sH14zDDZvW39S6bT1pFgM2W8gn9pV4HdltbW3MTVMS59VlW-VBQkF74S69PWW5yn7jz6PhmVLW4sYpYl4yDVH4W3dkf3v6S141VW3Sqpcn7xkSPcW33N24p3R1FxPW3y04W03TWHN4N2wvRyC4j7X83p5G1__;Kw!!HhY5bxTJhQ!vdj_DUrp0JIWgTw61Vg8M1chEvhp0k7XlLFiomq0Wu1rCrze9dzn2inIIVKchdRRP6HqJshCEuIHCbwCa1ha0FPyFA$"
console.log(decodeUrlDefensev3(link))
Expected output:
https://files.bitsight.com/e3t/Ctc/LR*113/c1NcF04/VWyThK1lvg49W72*nRX2d04lQW1xTZ7Q4QfX7gN6fpSV75nCTJV3Zsc37CgZP4N95fbTLz6L-gW48j6gR3bC3zwW6L_GnH7kDhzMW9418Rb3hJ605W2HjF587SWBXyW8RmYtF6fgdWYW5XQmQn1bFttzW5qPlhD5h_TCqW4-gDCr8x7fD0N4M_DVGdxFD9W2T0jhF4j9YsWW7603Qw8dF3j7W36QBsz4RM6hNW6Hpcdy8Qtmw4W8y5VBz2TLWGhVTNFr45gN7FDW7m9S0M1tvjXNW7vLHnj2945hZW437Z0x5Vd_ZcW7MjgJC89gYB6W2Y3sH14zDDZvW39S6bT1pFgM2W8gn9pV4HdltbW3MTVMS59VlW-VBQkF74S69PWW5yn7jz6PhmVLW4sYpYl4yDVH4W3dkf3v6S141VW3Sqpcn7xkSPcW33N24p3R1FxPW3y04W03TWHN4N2wvRyC4j7X83p5G1
The above code will return a correctly decoded website URL in the console. This works for technical people however, I am trying to create a basic HTML with a text box for users to enter the encoded URL, click a button, then return the decoded URL on their screen.
Using the below code:
function decodeUrlDefensev3(link) {
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
var link = document.getElementById('textbox1').value;
console.log(link)
<input type="text" id="textbox1" value="https://www.google.com" />
<input type="button" value="button1" onclick="decodeUrlDefensev3(link)" />
<input type="button" value="button2" onclick="function2()" />
The console.log(link) returns the true variable saved above. However, when I click the button, I get an error "Uncaught TypeError: Cannot read properties of null (reading '1')".
How do I pass the textbox input and properly call my function so that whatever is entered inside of textbox1 is parsed using my JavaScript function?
An example of what I am trying to do can be found here:https://jsfiddle.net/37phxda8/1/
I need to use my function above, not the function on that JS Fiddle.
You aren't passing the parameter to the decodeurl function. Try it like this:
function decodeUrlDefensev3(link) {
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
function handleClick() {
var link = document.getElementById('textbox1').value;
decodeUrlDefensev3(link);
}
Then in your html:
<input type="button" value="button1" onclick="handleClick()"/>
The error is probably because there are no results from the link.match function (for "https://www.google.com"), let alone 3 [2nd and 3rd items of the result are used for decode_pile and chars_pile respectively]. You should either change the RegExp for the match or provide and error message like the commented if block in the edited code below.
Also, your function is not taking updated input from textbox1 - only the initial value of "https://www.google.com" set in html. You should retrieve it within the function like:
function decodeUrlDefensev3() {
var link = document.getElementById('textbox1').value;
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
/*if (!matches || matches.length < 3) {
alert("Invalid input, could not decode");
return null;
}*/
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
And then your HTML for the button can simply be:
<input type="button" value="button1" onclick="decodeUrlDefensev3()"/>
When I submit the form and I try to get the Roomsno input value its showing like
this-
Array ( [0] => 1,2 ); why???
How can I send it so that it will come as a real array means like this-
Array([0]=>1 [1]=>2)
<input type="hidden" class="form-control" name="Roomsno" id="Roomsno" required>
<script>
var rmidarray = []; // new Array()
var rmnoarray = [];
$('.roomtype').change(function() {
roomss_id = $(this).attr('data-id');
no_room = $(this).val();
var check = rmidarray.includes(roomss_id);
if (check == true) {
// alert('hi')
index = rmidarray.indexOf(roomss_id);
// alert(index);
rmnoarray.splice(index, 1, no_room);
// rmnoarray[index].push(no_room);
} else if (check == false) {
// alert('by');
rmidarray.push(roomss_id);
rmnoarray.push(no_room);
} else {
alert('No rooms Selected!!!')
}
$("#Roomsno").val(rmnoarray);
});
</script>
As the value is in array format so Rather than setting the value directly use jason.stringfy-
Ex.
$("#Roomsno").val(rmnoarray); //Instead of this one
$('#Roomsno').val(JSON.stringify(rmnoarray)); //This one worked for me
And when i try to get the value i use json.decode and the value will come as array and we can use it normally as we use array. The array will come like- Array([0]=>1[1]=>2)
I have a search results page in a PHP site that returns a list of results using pagination. The URL looks like this:
findProducts.php?action=searchAssets&orderNumber=xxxx&productName=zzz&skip=20
I have a select menu that allows the user to modify/filter the search results which triggers a script like this:
$(document).ready(function() {
$('#productType').change(function() {
window.location.href = window.location.href + '&productType=' + $(this).val();
});
});
This is working well except for one thing - I need to reset the 'skip' parameter to 0 for the new filter search as the pagination values from the previous search won't be valid or applicable. Is there a way I can change:
skip=20
to:
skip=0
as part of this script?
You could do a RegExp replace on the URL:
window.location.href = window.location.href.replace(/((?:\?|&)skip)=\d+/, '$1=0') + '...';
(untested)
Note that you should do the same with the productType because otherwise you'll add it again and again.
Better solution would possibly be to have a base URL and then add all necessary parameters instead of doing search and replace...
You can get the query from the URL by splitting the URL using ?
This will give you the base url in the first index and the query in the second.
You can then get the query parameters by splitting the query using &.
You can loop through all of the parameters checking if it is the skip parameter. If the parameter is the skip parameter push your new value to an output array. Otherwise push the unchanged parameter to an output array.
You can then use join to join all of your output elements using & to reconstruct the query and return your original base url with your new query string.
<script>
function fixQuery(qstr) {
var parts = qstr.split('?');
var query = parts[1];
var a= query.split("&");
var out=[];
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
if(decodeURIComponent(b[0])=="skip")
{
out.push("skip=0")
}
else {
out.push(a[i]);
}
}
return parts[0] + '?' + out.join("&");
}
var result= fixQuery("http://example.com/findProducts.php?param1=test+thing¶m2=hello&skip=10");
console.log(result)
//http://example.com/findProducts.php??param1=test+thing¶m2=hello&skip=0
</script>
I've got a bit of javascript (shown below in a simplified format) which is the "ad tag" from the ad server that brings up an ad unit on the html page.
<script type="text/javascript" src="http://adserverdomain.net;pcode=1234;city=nameofcity;suburb=nameofsuburb"></script>
The javascript has more variable but I've just shown one.
Below this I have a <div> in which I'd like to pull the variable "pcode" from the above javascript and display it's value using
$('div').html("");
So the <div> needs to be populated with the value "1234".
Any idea how I can do this? Thanks
EDIT: I've updated the url (added .net and some other variables after pcode to avoid confusion). Also, I don't have access to the initial script, so I can't add an id to it. The script is generated by the ad server and it always has the variable pcode (with a different value). just need to be able to display that in another div on the same html page.
Try
<script type="text/javascript" src="http://adserverdomain;pcode=1234;city=sajdhsk;suburb=asdsadas"></script>
<div id="pcode"></div>
<div id="city"></div>
<div id="suburb"></div>
then
var pcodesrc = $('script[src^="http://adserverdomain;"]').attr('src');
$('#pcode').html(pcodesrc.match(/pcode=(.+?)(?=(;|$))/)[1])
$('#city').html(pcodesrc.match(/city=(.+?)(?=(;|$))/)[1])
$('#suburb').html(pcodesrc.match(/suburb=(.+?)(?=(;|$))/)[1])
Demo: Fiddle
or
$('#pcode').html(pcodesrc.match(/pcode=([^;]+)/)[1])
$('#city').html(pcodesrc.match(/city=([^;]+)/)[1])
$('#suburb').html(pcodesrc.match(/suburb=([^;]+)/)[1])
Demo: Fiddle
Try this with url.Actually the below code get data from url querystring.Edit it and give your url.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var me = getUrlVars()["pcode"];
Try this buddy
function getvalues()
{
var values = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { values[key] = value;});
return values;
}
whenever you want to use it
var value = getvalues()["pcode"];
Use this value to put in your html element
In first page im getting value in textbox i need to pass it to another page which is divided into 2 frames.
I need to display that value in first frame's html page.
Please provide me a simple example.
I tried with
window.document.getElementById("inputbox1").value
but im unable to get the value.
Please provide me a simple example.
I would go with localStorage, as #MicrosoftGoogle propose, but is not well supported yet, you can use pure javascript to achieve this. You will have something like this on your form page:
<form action="param-received.html" method="GET">
<input type="text" id="foo" name="foo">
<input type="submit" value="Send" name="submit" id="submit">
</form>
Once you click on Send button,you will be redirect to /param-received.html?foo=hola&submit=Send.
location.search attribute contains the chain of parameters.
? concatenates the URL and the string of parameters.
& separates multiple parameters.
= assigns a value to the variable.
Here is the complete code to process data sent on param-received.html:
<script language="JavaScript">
function processForm()
{
var parameters = location.search.substring(1).split("&");
var temp = parameters[0].split("=");
l = unescape(temp[1]);
alert(l); //Dialog with the text you put on the textbox
}
processForm();
</script>
Write the value in a cookie and read the cookie from the other page.
For writing and reading cookies check here
You could use the GET part of the request or cookies
if url parameters are an option you could use this
function getParameter(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
getParameter("page");
ref
http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html
another might be cookies
was beaten to the cookie part :p
edit indeed not a good cookie reference
this one is better http://www.w3schools.com/js/js_cookies.asp
function getValue(varname)
{
var url = window.location.href;
var qparts = url.split("?");
if (qparts.length == 1)
{
return "";
}
else{
var query = qparts[1];
var vars = query.split("&");
var value = "";
for (i=0;i<vars.length;i++)
{
var parts = vars[i].split("=");
if (parts[0] == varname)
{
value = parts[1];
break;
}
}
value = unescape(value);
// Convert "+"s to " "s
value.replace(/\+/g," ");
return value;
}
}
var VariableGot = getValue(YourPassingVariableName);
Just copy the function into your html file and pass your variable name to the function which is send through GET Method.Now You will get the value of the variable from url.