javascript button onclick to a web uri with location.href - javascript

I am trying to add a onclick function to a button outside of the <button> tag, in Javascript. Below is what I have at the moment, but the button doesn't links to that uri when clicked. How should I do this? Many thanks for your help in advance! I commented in the code as well.
For the button I have:
"<td><button"+" id="+foodList[i].Id +" onClick="+"\"doSomething(this.id)\""+" >"+"Get"+"</button></td></tr>"
So basically I assigned the "Get" button an id in a for loop.
function doSomething(id) { //the button's id
var item = document.getElementById("type").value; //get some value from elsewhere in the page
if (item == "food") {
var uri = "baseuri" + id;
document.getElementById(id).onclick = "location.href='" + uri + "';"//add an onclick to the button so that it will takes the user to that uri
} else {
var uri = "another baseuri" + id;
document.getElementById(id).onclick = "location.href='" + uri + "';"
}

Change this:
document.getElementById(id).onclick="location.href='"+uri+"';"
to something like this:
document.getElementById(id).onclick= function(){
location.href = "Wanted url here"; // location.href = location.href + "/currentpath/additional/params/here"
}
That way, when you click the button, you have attached a function to it, and it changes the url (redirects the page)

You must write it like this :
document.getElementById(id).onclick = function() {
location.href = uri;
}

Related

How to switch url with javascript button

I'm trying to reuse a button in different landing pages and change the hyperlink of this button depending on what page is being browsed.
I started my function for it but I'm stuck on how to pass the data. If the user is on a page that contains home_ns in the url, I would like the button link to be cart1 and if the user is on a page called home_nd I would like it to be cart 2.
<script type="text/javascript">
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
// This is where I am stuck
}
}
</script>
Then the button will be
<button onclick="urlCart()">Order Now</button>
Here is what you need:
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
window.location.href = cart1;
} else {
window.location.href = cart2;
}
}
You could create a look-up map of pages to cart ID. You can then update the search parameter in the URL to reflect the found ID.
Note: Since the Stack snippet below is not going to actually have the correct href, the code will not add/update the parameter. If you want to integrate this, replace the url variable declaration with this:
let url = window.location.href;
You could also use the pathname instead of the href for finer granularity.
let url = window.location.pathname;
// See: https://stackoverflow.com/a/56593312/1762224
const setSearchParam = function(key, value) {
if (!window.history.pushState) return;
if (!key) return;
let url = new URL(window.location.href);
let params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) params.delete(key);
else params.set(key, value);
url.search = params;
url = url.toString();
window.history.replaceState({ url: url }, null, url);
}
const pageMap = {
"home_ns": 2419,
"home_nd": 2417
};
function urlCart() {
let url = 'https://mywebsite.com/home_ns' || window.location.href;
Object.keys(pageMap).some(page => {
if (url.includes(page)) {
console.log('Found page:', page);
setSearchParam('add-to-cart', pageMap[page]);
return true;
} else {
return false;
}
});
}
<button onclick="urlCart()">Order Now</button>
Simply you can move the user to another page by:
location.href = myURL;
The browser will automatically go to the specified page.
Examples of what a URL can be:
An absolute URL - points to another web site (like
location.href="http://www.example.com/default.htm")
A relative URL - points to a file within a web site (like location.href="default.htm")
An anchor URL - points to an anchor within a page (like
location.href="#top")
A new protocol - specifies a different protocol
(like location.href="ftp://someftpserver.com",
location.href="mailto:someone#example.com" or
location.href="file://host/path/example.txt")
Source

Redirect from master page to its content pages using jquery not working

I called this method on keyUp event of enter key
function PerformSearch(search_key) {
var url = "<%=ResolveUrl("/Test/TestPage.aspx?type=search&search_key=")%>" + search_key;
//GoToLocation(url);
//window.open(url);
//$(location).attr("href", url);
//window.location.replace(url);
window.location.href = url;
}
use like this
window.location = url;
For your reference read this
You have string concatenation errors in your url.
This:
var url = "<%=ResolveUrl("/Test/TestPage.aspx?type=search&search_key=")%>" + search_key;
Should be this:
var url = "<%=ResolveUrl('/Test/TestPage.aspx?type=search&search_key=')%>" + search_key;

how to send mail using javascript?

I need to send a mail using javascript but i was unable to do it with
can any one please help with the code.
var link == "mailto:test#test.com"
+ "&subject=" + escape(":Feedback");
window.location.h ref = link;
You assign link variable with == which is not correct. Try with:
var link = "mailto:RAS.AMB#Wilhelmsen.com&subject=" + escape(":Feedback");
window.location.href = link;
Your javascript is not valid. You have a space in href and var link == should be var link =
This works.
var link = "mailto:RAS.AMB#Wilhelmsen.com&subject=" + escape(":Feedback");
window.location.href = link;

How to rewrite and submit form at same time

There is a form that i want to submit and url rewrite at the same time. I can change url by adding onsubmit="rewrite_form(event);" option in form :
function rewrite_form(e) {
var form = document.forms[0]; // .getElementById("form1");
window.location = '/search/' + form.f.value + '_' + form.t.value + '.htm/' + form.amt_from.value;
if (e && e.preventDefault) { e.preventDefault(); }
return false;
}
Url changes but other values of form not posted to url generated page.
Just change the form's action property instead.
function rewrite_form(e) {
var form = documen.forms[0];
form.action = 'newurl';
//rest of code, make sure not to call e.preventDefault(); or return false
//because the form will not get submitted
}
i got the solution:
function rewrite_form() {
//Create custom link here
----------------------------
----------------------------------
//create form submit action
var url = '/search/' +'your custom link';
document.getElementById('FormId').action = url;
document.FormId.submit();
}

javascript - redirecting

I can get the code to pop-up both alert but redirecting is not working. After adding an item it should redirect.
<script type="text/javascript" src="/_layouts/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Where to go when cancel is clicked
goToWhenCanceled = '/test/English/YouCanceled.aspx';
// Edit the redirect on the cancel-button's
$('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
$(this).click(function(){
STSNavigate(goToWhenCanceled);
})
});
// Edit the form-action attribute to add the source=yourCustomRedirectPage
function setOnSubmitRedir(redirURL){
var action = $("#aspnetForm").attr('action');
var end = action.indexOf('&');
if(action.indexOf('&')<0){
newAction = action + "?Source=" + redirURL;
}else{
newAction = action.substring(0,end) + "&Source=" + redirURL;
}
$("#aspnetForm").attr('action',newAction);
alert(redirURL);
}
/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
var goToWhenSubmitted = '/test/English/ThankYou.aspx';
setOnSubmitRedir(goToWhenSubmitted);
});
*/
// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
var dynamicRedirect = '/surveys/Pages/ThankYou.aspx';
// Call the function and set the redirect URL in the form-action attribute
setOnSubmitRedir(dynamicRedirect);
alert(dynamicRedirect);
// This function must return true for the save item to happen
return true;
}
function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
If you set window.location.href = 'SomeUrl' at any point, it should redirect right then. Looking at your code, I dont see that anywhere.
At what point are you trying to redirect?

Categories

Resources