Get part of the current URL using Javascript - javascript

fI'm developing a simple and small search in a Wordpress page using a $_GET variable in the url passed by javascript:
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = document.URL+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
So, the url to search is: MYURL/?page_id=51&pesquisa=test
Of course, the page_id is variable. If I search again, the URL is going to be: MYURL/?page_id=51&pesquisa=test&pesquisa=new, what is wrong.
How could I get just the MYURL/?page_id=51 using javascript? The window.location.pathname is not what I need.
Thanks.

Anything that searches naively will be vulnerable to problems like this: What if the URL is:
http://example.com/?pesquisa=test&page_id=51
You need to search for and remove the relevant query parameter:
var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;

Try this hopefully it should work
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>

try this.
var a = document.URL;
var result = a.substr(0, a.indexOf('&'));
Resources:
Get current URL in web browser
how to grab substring before a specified character jquery or javascript

javascript:
<script type="text/javascript">
function get_query_param(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = function() {
if (get_query_param("page_id") != null) {
alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
}
}
</script>
hope that helps.

Related

php javascript onclick value change

I want to remove the "http" if it is put in the url part of the input link, before the data is sent.
this my input code look onclick=
<input style=" outline: none;" type="button" onclick="formatText ('link:url');" class="btn btn-yeni" value="link"/>
This my javascript code (the received data is sent to another file and replaced.)
<script type="text/javascript">
function formatText(tag) {
var Field = document.getElementById('entry_girdi');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value += '(' + tag + ')';
}
</script>
what i want to do If the input value is "link: http: //example.com" I would like to change it and post it as "link: example.com".
Can you try in your url string :
var result = url.replace(/(\w+:|^)\/\//, '');
result variable will hold "link : example.com" in place of "link : http://example.com"
Use the replace() function to replace part of a string.
function formatText(tag) {
var Field = document.getElementById('entry_girdi');
Field.value = Field.value.replace("http://", "");
Field.value += '(' + tag + ')';
}

How do I convert this jQuery codes to JavaScript?

I am having trouble in solving my previous post. I only got a solution which requires jQuery, but I want to use JavaScript instead.
Really need help on this.
Previous Post (For Reference) : HTML - How To Display & Direct Selected Values From Drop Down Menu To A New HTML Page
This is the first jquery codes.
<input type="submit" id="btngo" value="Go" />
<script type="text/javascript">
$(function() {
$("#btngo").bind("click", function() {
var url = "Page2.htm?foodbeverage=" + encodeURIComponent($("#foodbeverage").val()) + "&status=" + encodeURIComponent($("#status").val());
window.location.href = url;
});
});
</script>
This is the second jquery codes.
< script type = "text/javascript" >
var queryString = new Array();
$(function() {
if (queryString["foodbeverage"] != null && queryString["status"] != null) {
var data = "<b>Food Beverages:</b> " + queryString["foodbeverage"] + " <b>Dine Takeaway:</b> " + queryString["status"];
$("#showdata").html(data);
}
}); <
/script>
I've converted the first snippet to a native JS equivalent. I didn't add the status to the URL, it is just more of the same as getting the food beverage.
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
// Get the input element from the DOM.
var beverage = document.getElementById('foodbeverage'),
// Get the value from the element.
beverageValue = beverage.value,
// Construct the URL.
url = 'Page2.html?foodbeverage=' + encodeURIComponent(beverageValue) + '&status=test';
// Instead of going to the URL, log it to the console.
console.log('goto to URL: ', url);
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
<label>
Beverage:
<input type="text" id="foodbeverage"/>
</label>
<input type="submit" id ="btngo" value="Go" />
For the second code snippet, add a div to the form/page. The JS function below will update the div value on window onload with parameters passed. Note that div is only updated if both the querystring paramaters are present.
<div id="showdata"></div>
<script type="text/javascript">
window.onload = passParameters;
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
var foodbeverage = getParameterByName("foodbeverage");
var status = getParameterByName("status");
if (foodbeverage != null && status != null) {
var data = "<b>Food Beverages:</b> " + foodbeverage + " <b>Dine Takeaway:</b> " + status;
document.getElementById("showdata").innerHTML = data;
}
}
//Get URL parameter value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

JavaScript Failing in iWeb

I am using iWeb for some simple webpage development, and I have put some JavaScript in an HTML widget. The first widget I did worked perfectly, but the second one I am having issues with. The script is supposed to pull the $_GET variables from the URL to address the user. My script worked perfectly outside of iWeb, but fails what I copy it into an iWeb widget. Here is my code:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
//Replace all String Function
String.prototype.replaceAll = function(search, replace){
//if replace is null, return original string otherwise it will
//replace search string with 'undefined'.
if(!replace)
return this;
return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};
//GET from URL
var getVars = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i){
var tmp = args[i].split(/=/);
if(tmp[0] != ""){
getVars[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replaceAll("+", " "));
}
}
$(document).ready(function(){
$("#rsvpName").html(getVars["rsvpName"]);
if( getVars["rsvpResponse"] == "1" )
$("#rvspMessage").html( "You will be attending as part of a party of " + getVars["rsvpNum"] + "." );
else if( getVars["rsvpResponse"] == "0" )
$("#rvspMessage").html("We regret you will not be able to attend!");
alert( getVars["rsvpName"] + getVars["rsvpResponse"] + getVars["rsvpNum"]);
});
</script>
<h1>Thank you, <b><span id="rsvpName">Name</span></b>, for RSVPing.</h1>
<p id="rvspMessage">Message</p>
Anyone have a suggestion?

Get the parameter string in javascript using jquery

I have these links :
Block 1 :
Adapters
Battery
After click on the link in Block1 , then I start to click on Block2:
Block 2 :
<img src ="/Content/Images/Top/searchbutton.png"/>
I can get the parameter value such as dep=56,cat=654 by using these jquery.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null){
return "";
}else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function SearchClick() {
var cur_url = window.location.href;
var depId = getParameterByName("dep");
var catId = getParameterByName("cat");
var searchStr = getParameterByName("search");
var url_add = "";
if (depId != "") {
url_add += "&dep=" + depId;
}
window.location = "/Products?tab=2"+ url_add;
}
But now I exchanged the link in Block 1 with
<a href='javascript:void(0);' dep='" + work.ID + "'>" + work.ProName + "</a>
//it works well
So how can I get the value of dep in Block 1 by using javascript or jquery when I click on the the Block 2 link?
Thanks so much for all your answers.
It would be best if you put an ID on the A tag, like so:
<a id="myLink" href='javascript:void(0);' dep='" + work.ID + "'>" + work.ProName + "</a>
then you could use the following JQuery to get the value of work ID:
$("#myLink").attr("dep")
or plain old Javascript like so (assuming you've still got that ID on the A tag):
document.getElementById("myLink").getAttribute("dep")
EDIT: I've put it in the click for you, here is all my code:
<a id="block1Link" href='javascript:void(0);' dep="56">Adapters</a>
<br />
<br />
Click
<script type="text/javascript">
function SearchClick() {
var department = $("#block1Link").attr("dep");
alert(department);
}
</script>
Or if you want to use Javascript swap the var department line with this line:
var department = document.getElementById("block1Link").getAttribute("dep");

C# using textbox as "post it" / "sticky memo" client side event

I want a textbox to act like a "post it" or "Sticky memo" just like widget Igoogle or Windows 7 widget.
The idea:
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
Every time that user types into the textbox it calls Javascript to save the text into cookies.
Could somebody give me a hint?
This is somewhat quick and dirty but will get you going.
There's plenty of setCookie/getCookie JS snippets around the web. I used these:
http://www.dotnetspark.com/kb/1480-use-cookies-javascript-getcookie-setcookie.aspx
Teh code now:
<input type="text" id="txtMemo" />
<script type="text/javascript">
function setCookie(CookieName, CookieVal, CookieExp, CookiePath, CookieDomain, CookieSecure)
{
var CookieText = escape(CookieName) + '=' + escape(CookieVal); //escape() : Encodes the String
CookieText += (CookieExp ? '; EXPIRES=' + CookieExp.toGMTString() : '');
CookieText += (CookiePath ? '; PATH=' + CookiePath : '');
CookieText += (CookieDomain ? '; DOMAIN=' + CookieDomain : '');
CookieText += (CookieSecure ? '; SECURE' : '');
document.cookie = CookieText;
}
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
function getCookie(CookieName)
{
var CookieVal = null;
if(document.cookie) //only if exists
{
var arr = document.cookie.split((escape(CookieName) + '='));
if(arr.length >= 2)
{
var arr2 = arr[1].split(';');
CookieVal = unescape(arr2[0]); //unescape() : Decodes the String
}
}
return CookieVal;
}
var memoCookieName = "txtMemo_value";
var memoElementId = "txtMemo";
var memoElement = document.getElementById(memoElementId);
memoElement.value=getCookie(memoCookieName);
memoElement.onkeyup = function() {
setCookie(memoCookieName,this.value, new Date(new Date().getTime()+1000*60*60*24*30));
};
</script>
This will work with plain HTML. In your case with ASP.NET markup and controls the ID property has a different meaning, so you need to make your JS aware of the actual client ID. This way for example:
(...)
var memoCookieName = "txtMemo_value";
var memoElementId = "<%= TextBox1.ClientID %>";
var memoElement = document.getElementById(memoElementId);
(...)
Of course. Play with "change" event:
http://www.w3schools.com/jsref/event_onchange.asp
It's just about using this event and update some cookie that you previously created with JavaScript too.

Categories

Resources