Putting Javascript variable in html link - javascript

I have a dynamic variable that gets updated by users of a webpage in a script and when the user clicks on a hyperlink I need to be able to send that variable to another webpage. So I need something like
Link
to work but I am not sure the exact syntax on how to do this. I already have a getter in my JavaScript I just need to be able to access it when the user clicks on a link.

You could either use an onclick action to send you to a function that navigates the page for you.
Or
You could update the href attribute anytime that value of variable needs to be changed.
The second option is probably preferable, but it largely depends on what else is going on in the page and how variable is set

it looks very familiar with this:
How to redirect on another page and pass parameter in url from table?
link
Native JS:
document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter());
jQuery:
$("#redirectwithid").click(function() {
var yourVariable = variableGetter();
if (yourVariable != null) {
window.location = 'yoururl?variable=' + yourVariable;
}
});​
Add for Native JS:
I don't know your code so just insert the code where you want to update your variable - at the same time the href will change.
Edit:
If you want to add multiple variable like ?variable=1 and a second variable2=2 you can achieve this by adding a & between the variables, like this:
NativeJS:
document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter() + '&variable2=' + variable2Getter());
JQuery:
$("#redirectwithid").click(function() {
var yourVariable = variableGetter();
var yourVariableTwo = variableTwoGetter();
if (yourVariable != null) {
window.location = 'yoururl?variable=' + yourVariable + '&' + yourVariableTwo;
}
});​

Related

Passing string variable to an href with jQuery and JavaScript from form element

I am attempting to use the following bit of JS and jQuery to pass a variable (user's Email address form tfa_27) through an href link on the form.
I can redirect to the page, but the url just reads 'tfa_5?=$VARIABLE' instead populating the Email address into the URL, which ends my login state for the user. I know I am missing something ...
function dynamicLinks(linkClass, fieldId) {
var selection = $("#" + fieldId);
console.log(selection.val()); //Gives 'some.email#domain.ca'
var linkArr = [];
$(selection).each(function() { linkArr.push($(this).val()); });
$(linkClass).attr("href", function(i, origLink) { return origLink.replace(/\$VARIABLE/, linkArr[i]); });
//$(linkClass).attr("href", function(i, origLink) { return "https://tfaforms/XXXXXXX?tfa_5=" + selection.val() }); //Does not update href on form
};
dynamicLinks(".linkClass","tfa_27");
On the page itself, this is what my HTML href looks like this with the form ID hidden from SE for security reasons - the $VARIABLE should be an email address.
Back to Options
Please note this piece of code is partially legacy code, so I may have some extra pieces - if so, please let me know! I am unsure how to move the variable into the href on the form, or how to build that href dynamically - I was told this would work well, but am missing something.
Thanks!

Create link in handlebars.js using helper

I have tried to follow the example in the handlebars documentation on how to create a link, but the instructions are very unclear to me. handlebarsjs.com/expressions.html (see "Helpers")
First of all, without the link helper I can make the link text appear on the screen, but just as text, not a link.
<script id="template" type="text/x-handlebars-template">
<h4>{{{my_link}}}</h4>
</script>
And the text is retrieved from an ajax request.
Then I add the link keyword
<h4>{{{link my_link}}}</h4>
And then nothing is displayed. This is the helper code I have currently, which doesn't work:
$(function(){
Handlebars.registerHelper('link', function(my_link) {
var url = Handlebars.escapeExpression(my_link.url);
var result = "<a href='" + url + "'></a>";
console.log(result);
return new Handlebars.SafeString(result);
});
});
Is it relevant where I put this piece of code in the javascript?
When I click a submit button, the ajax request is made and the link is retrieved. With the link helper, the console.log gives an empty link:
"<a href=''></a>"
Since you registered the name of the helper as link, your template should start with {{{link
So
<h4>{{{my_link}}}</h4>
should be
<h4>{{{link my_link}}}</h4>
And
var url = Handlebars.escapeExpression(my_link.url);
should be changed to
var url = Handlebars.escapeExpression(my_link);
Instead of creating the whole a element I can suggest you to create helper for attribute only. This way you can reuse it to many others elements and also the code will be much simpler and better to read in the templates. For example I have build this attr helper function:
handlebars.registerHelper('attr', function(name, data) {
if(typeof target === 'undefined') target = "";
var result = ' ' + name + '="' + data + '" ';
return new handlebars.SafeString(result);
});
And here is how it looks in the template:
<a target="_blank" {{attr 'href' general.link}}><img src="assets/images/nice_image.png" class="link-icon" /></a>
I think this approach is much more simpler, and even more reusable than having helper to create the whole element. You can name the helper in the way that will match the attribute also, href, src...

How to reload a page with javascript sending both GET and POST, and append additional parameter?

I have a page with an select box, which fires an onChange event. In this Java-Script snippet, I would like to reload the current page, including the GET and POST parameters that where sent during request. AFAIK, this can be achieved by using window.location.reload(), or window.location.href = window.location.href when sending POST data is not required.
However, I need to append an additional value (actually, the value of the select element), additionally to the previously sent element. I do not care whether the data is sent using POST or GET. Is there a way to achieve the desired behavior?
To accomplish this you are going to have to rebuild a request from scratch. In the case of get requests, the arguments are easily accessible in the query string but post requests are a little trickier. You will need to stash all that data in hidden input elements or something so that you can access it.
Then you can try something like this:
var queryString = windlow.location.search; //args from a previous get
var postArgs = $("#myPostArgsForm").serialize(); //args from a previous post... these need to be saved and added to the html by the server
//your additional data... this part you probably need to adapt
//to fit your specific needs. this is an example
var myNewArgName = encodeURIComponent("newArg");
var myNewArgVal = encodeURIComponent("Hello!");
var myNewArgString = myNewArgName + "=" + myNewArgVal;
//if there is no queryString, begin with ?
if(!queryString) {
queryString = "?"
}
//if there is, then we need an & before the next args
else {
myNewArgString = "&" + myNewArgString;
}
//add your new data
queryString += myNewArgString;
//add anything from a previous post
if(postArgs) {
queryString += "&" + postArgs;
}
window.location.href = window.location.hostname + window.location.pathname + querystring
<form id="myPostArgsForm">
<input type="hidden" name="prevQuery" value="whats up?" />
</form>
Pretty simple really; have onChange fire a function that uses getElementById to figure out the selector value and then just use window.location to send the browser to the literal: http://yourdomain.com/yourpage.html?selectval=123
then, in the body onload() method, fire another JS function that checks the "get var" like:
function (GetSelector) {
var TheSelectorWas = getUrlVars()["selectval"];
alert(TheSelectorWas);
}
and do whatever you need to do in that function (document.writes, etc). BTW, posting the actual code you're using is always a good idea.
-Arne

Can I change the parameter or is the action static/"locked down"?

My code works, I can upload a file.
But how do I set typeNavn to something else runtime, so the value depends on witch tap is selected on the page.?
I want to either set typeNavn as either "billeder" or "dokumenter". Now it's always "billeder" from ViewBag.typeNavn, is that possible and how?
Is the action so static, that I can't change any of it's parameters runtime? I have tryed messing around with a callback, a JavaScript variable and a Razor variable. And it either doesn't work for me, or doesn't change it's first value.
var upload = $('#upload').wijupload(
{
// Note: the next two lines must be on one line for it to work.
// It's only two on SO so we don't have the x-scrollbar.
action: '#CleanHtml.Clean(Html,#Url.Action( "UploadFiles", "Dokument",
new { typeNavn = ViewBag.typeNavn } ))'
});
You need a JavaScript variable that can be changed dynamically, and then used as part of the action url.
var typeNavn = ''; // Declare this somewhere. This is updated by some means.
var cleanHtml = '#CleanHtml.Clean(Html)'; // I don't know what Clean() does.
var upload = $('#upload').wijupload(
{
// Note: the next two lines must be on one line for it to work.
// It's only two on SO so we don't have the x-scrollbar.
action: '/UploadFiles/Dokument?typeNavn=' + typeNavn)'
});
OK the layout of the above code may not be what you need (I don't know what cleanHtml is supposed to be), but the core idea of using a variable typeNavn is key here. You need some means of updating that variable to reflect the type selected i.e. a dropdownlist of something.
It's a bit unclear...do you have a radio/checkbox/etc where you want to change typeNavn or do you want to set that in the controller? Url.Action will render a string which you could certainly change using javascript. However in what context you are using this is a bit unclear.
Just going to guess that you want something like this:
$(".list").change(function(){
var list = $(this);
var url = baseUrl + "?typeNavn=" + list.val(); // How you get baseUrl variable is up to you
var upload = $('#upload').wijupload(
{
action: url
});
});
One thing you can do is pass the TabName in the action of controller as a parameter when loading view. And set the viewbag's value accordingly. So this will not be static and work perfectly.
second way, you can update querystring paramter name by jquery
You can use a placeholder value which can be replace with any desired value using the .replace() method. Here is pseudo-code. In example I have used -1 as placeholder value
Code
var typeNavn = '#ViewBag.typeNavn';
var action = '#CleanHtml.Clean(Html, #Url.Action( "UploadFiles", "Dokument",
new { typeNavn = -1} ))'; //Really have no idean
//Here you can use -1 as place holder which you can replace using JavaScript like
action = action.replace('-1', typeNavn);
var upload = $('#upload').wijupload(
{
action: action
});
Note: I have no idea about CleanHtml.Clean

How can I pass the value of an input in a href

I'm trying to pass the LoadNumber into a php file to use in a query and result in a FPDF on a button click. the button works but the value its passing is $(' not the value I wanted. Where am I going wrong. Here is my code.
$(location.href="dispatch.php? LoadNumber=$('#LoadNumber').val()")};
You can do it like:
// Get the LoadNumber value first
var value = $('#LoadNumber').val();
// Set the url with query string properly
var url = "dispatch.php?LoadNumber=" + value ;
// Re-direct to the url now
location.href = url;
Just to make things clear for you.
This can also be done in one line like:
location.href = "dispatch.php?LoadNumber=" + $('#LoadNumber').val();
Use it in this way :
$(location.href="dispatch.php? LoadNumber="+$('#LoadNumber').val())};
Don't put $('#LoadNumber') in quotes.
If you want to set that value to location.href, just write the following:
location.href = "dispatch.php?LoadNumber=" + $('#LoadNumber').val();
window.location = 'dispatch.php?LoadNumber=' + $('#LoadNumber').val();

Categories

Resources