send text-field's value to google as search query - javascript

Is there a way I can get the value of an input-field and send that to Google as a search query ?
How I would go about doing this would be using jQuery's .attr() and storing that in a variable. Then replacing all the spaces in that string with pluses (+). Then attaching that to http://google.com/? and then navigating yo the newly constructed URL using window.location.
Is there a better way to do this?
Or, if you can not think of a better way, could you help me implement the above.
The parts I am having trouble with are using .attr() and giving window.location a variable as its argument / parametre.

Well, replacing spaces with + need not be done as it does not make your query any different.
For the rest, you can use:
window.location.href = 'http://google.com?q='+encodeUriComponent($('#textbox').val());

Related

How to properly use jquery to set a value using $.post if html value only has a name?

I'm new to jQuery and JS, so perhaps this is a very simple question, but I don't quite understand how to use the $.post() function for jQuery. What I'm trying to do is change a value of an input in an html file using jquery.
For example, let's say I'm trying to post to some test site, and change the value of my_data ( the name of an attribute ), which is originally at 1.
I figured I'd use $.post for this, so I have something like:
$.post("http://test_site.com/", function(my_data) {
$(#my_data).val(5));
});
However, I think that # is for the id? I'm not sure if I'm just misunderstanding post, or not. Any hints / points in the right direction would be greatly appreciated!
You are missing quotes and name selector should be: $([name='YOUR_ATTRIBUTE_NAME'])
Try this:
$("[name='my_data']").val(5);

Javascript regex to replace ampersand in all links href on a page

I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.

How to get last part of URL, ignoring any GET parameters?

I'm expecting URLs in this for:
/user/username
but end users can also add whatever get parameters they want, like so:
/user/username?foo=bar
With that said, using AngularJS, what's the preferred way for me to get just the username (which appears after /user/) without anything else after it?
You should use the $location service and its .path() method, then use a regular split() and indexing.
I doubt there's a dedicated function for it but it seems easy enough to pull it out of the string with the query.
Get the path with $location.path() and then both of these does the job for you.
url.substring(6, (url.indexOf('?') != -1 ? url.indexOf('?') : url.length))
url.split('/')[2].split('?')[0]
Same question here: Is there a built-in way to get the current URL without any query parameters?
you can use window.location or $location service to get the path and then using split function
like this
var url = "/user/username?foo=bar";
var check = url.split('/user/');
var username = check[1].split('?');
console.log(username[0]);
you can find username by applying multiple split on your url. hope this is what you want.

Javascript & HTML Getting the Current URL

Can anyone help me. I don't use Client-side Javascript often with HTML.
I would like to grab the current url (but only a specific directory) and place the results between a link.
So if the url is /fare/pass/index.html
I want the HTML to be pass
This is a quick and dirty way to do that:
//splits the document.location.href property into an array
var loc_array=document.location.href.split('/');
//have firebug? try a console.log(loc_array);
//this selects the next-to-last member of the array.
var directory=loc[loc.length-2]
url = window.location.href // Not particularly necessary, but may help your readability
url.match('/fare/(.*)/index.html')[1] // would return "pass"
There may be an easier answer, but the simplest thing I can think of is just to get the current URL with window.location and use some type of parsing to get which directory you are looking for.
Then, you can dynamically append the HTML to your page.
This may get you started:
var linkElement = document.getElementById("whatever");
linkElement.innerHTML = document.URL.replace(/^(?:https?:\/\/.*?)?\/.*?\/(.*?)\/.*?$/i,"$1");

Making a URL W3C valid AND work in Ajax Request

I have a generic function that returns URLs. (It's a plugin function that returns URLs to resources [images, stylesheets] within a plugin).
I use GET parameters in those URLs.
If I want to use these URLs within a HTML page, to pass W3C validation, I need to mask ampersands as &
/plugin.php?plugin=xyz&resource=stylesheet&....
but, if I want to use the URL as the "url" parameter for a AJAX call, the ampersand is not interpreted correctly, screwing up my calls.
Can I do something get & work in AJAX calls?
I would very much like to avoid adding parameters to th URL generating function (intendedUse="ajax" or whatever) or manipulating the URL in Javascript, as this plugin model will be re-used many times (and possibly by many people) and I want it as simple as possible.
It seems to me that you're running into the problem of having one piece of your application cross multiple layers. In this case it's the plugin.
A URL as specified by RFC 1738 states that a URL should use a & token to separate key/value pairs from one another. However ampersand is a reserved token in HTML and therefore should be escaped into &. Since escaping the ampersands is an artifact of HTML, your plugin should probably not be escaping them directly. Instead you should have a function or something that escapes a canonical URL so that it can be embedded in HTML markup.
The only place that this is likely to actually happen is if you are:
Using XHTML
Serving it as text/html
Using inline <script>
This is not a happy combination, and the solution is in the spec.
Use external scripts if your script
uses < or & or ]]> or --.
The XHTML media types note includes the same advice, but also provides a workaround if you choose to ignore it.
Try returning JSON instead of just a string, that way your Javascript can read the URL value as an object, and you shouldn't have that issue. Other than that, try simply HTML decoding the string, using something like:
function escapeHTML (str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
};
Obviously you'll want to make sure you remove any reference to DOM elements you might create (which I've not done here to simplify the example).
I use this technique in the AJAX sites I create at my work and have used it many times to solve this problem.
When you have markup of the form:
<a href="?a=1&b=2">
Then the value of the href attribute is ?a=1&b=2. The & is only an escape sequence in HTML/XML and doesn't affect the value of the attribute. This is similar to:
<a href="<>">
Where the value of the attribute is <>.
If, instead, you have code of the form:
<script>
var s = "?a=1&b=2";
</script>
Then you can use a JavaScript function:
<script>
var amp = String.fromCharCode(38);
var s = "?a=1"+amp+"b=2";
</script>
This allows code that would otherwise only be valid HTML or only valid XHTML to be valid in both. (See Dorwald's comments for more info.)

Categories