jQuery created button dropping link text - javascript

I have created a dyanmic button in Java script with the following code:
var pathname = window.location.pathname;
var html = '<div id="gmSomeID"><form action="https://apples.com/active/index?u='+pathname+'"><input id="tapButton" type="submit" value="TAP" /></form></div>'
That should pass direct someone to the link mentioned above with pathname appended.
When I paste this URL in myself manually this works. However, each time I click this link, the URL is truncated to just:
https://apples.com/active/index?
For reference:
Original URL: https://apples.com/class/1/info
Pathname: /class/1/info
Why would JavaScript / Browser be truncating a link like this?

I thought about this, and had another idea:
Try putting the u parameter as a hidden input instead of action.
var html = '<div id="gmSomeID"><form action="https://apples.com/active/index"><input type="hidden" name="u" value="'+pathname+'"/><input id="tapButton" type="submit" value="TAP" /></form></div>'
I think that GET input values always override the values in the query string of the action parameter.
See also: submitting a GET form with query string params and hidden params disappear

Not sure if this is causing your problem, but every time you construct parameters of a URL, you should URL-encode the values.
So, to be correct, the code should look like this:
var pathname = window.location.pathname;
var html = '<div id="gmSomeID"><form action="https://apples.com/active/index?u='+encodeURIComponent(pathname)+'"><input id="tapButton" type="submit" value="TAP" /></form></div>'

Related

Setting a onclick event to a c# URL Action in javascript?

In my view I have a checkbox input as follows:
<input type="checkbox" data-toggle="modal" data-target="#CheckItemsModal" id="#item.ItemId" onclick="location.href = '#Url.Action("CheckedItem", "List", new { id = item.ItemId })'; Checked(this.id)" />
I am trying to have a modal confirmation on the checking and un-checking of the checkbox however this means that my URL action would need to be moved to the modal's button while still preserving the id = item.ItemId so my plan is to us javascript to do this however I am not sure how to assign the onclick event of the modal button properly.
This is what I have so far (The error it's throwing is that checkId inside the url action does not exist in the current context):
function Checked(checkId) {
if ($(checkId).Checked == true) {
$(modalButton).setAttribute('onclick','location.href = '#Url.Action("CheckedItem", "List", new { id = checkId })'')
}
}
Any help would be much appreciated.
C# is run on the server and JavaScript in the browser. Your URL.Action is executed on the server where the checkId variable does not exist. You need to generate the url from pure JavaScript in the onclick method or generate links using Url.Action for all checkboxes in advance.
Another option is to use string replace in the JavaScript onclick method. For example:
location.href = '#Url.Action("CheckedItem", "List", new { id = "_REPLACE_ID_" })'.replace( "_REPLACE_ID_", checkId);
Look at the generated HTML source to see what happens.
You also need to be careful about your quotes. In your code you have invalid JavaScript with multiple consecutive single quotes at the end.

How to dynamically add data from a span tag into a href tag

I think this may have a simple answer that I'm missing. The following tag inserts a TV show name into any page on my website:
<span class="show-title"></span>
what I'm trying to do is incorporate that data dynamically into a HREF URL link.
So, let's say on the page I'm on:
produced the result: GOTHAM.
I'd like to then use that data to create this url:
https://en.wikipedia.org/wiki/GOTHAM_(TV_series)
So I'm trying stuff like:
</span>_(TV_series)"> Link
or
Link
nothing working - any help would be awesome. Thanks!
You could do something like this:
In HTML
<a class="wikipedia-link">Link</a>
And your JavaScript function:
setLink(showTitle) {
var link = document.getElementsByClassName("wikipedia-link");
link.setAttribute("href", "https://en.wikipedia.org/wiki/" + showTitle + "_(TV_series)");
}
The html you use is wrong. span shouldn't be inside tag a. No tag inside another.
If your result is in javascript variable, you can set the url using jquery.
$('a').attr('href', "https://en.wikipedia.org/wiki/" + result + "_(TV_series)");
result variable is your desired result.
Although there's better ways of going about doing this, I'm going to answer the question in the context in which you presented it:
First, give the url link a class or ID so you can easily select it with JavaScript to change the href value later. Also, don't try to nest the span tag anywhere inside the a tag. Leave it outside.
<span class="show-title">GOTHAM</span>
Link
Next, in a JavaScript file or a <script> tag, define your variables:
var showTitle, showWikipediaLink, linkElement
Then, assign value to your newly defined variables
linkElement = document.querySelector('.show-wikipedia-link');
showTitle = document.querySelector('.show-title').innerText;
showWikipediaLink = 'https://en.wikipedia.org/wiki/' + showTitle + '_(TV_series)';
Finally, use JavaScript to update the href value of the link element to the show's Wikipedia link:
linkElement.href = showWikipediaLink;

How to add additional parameter like (rel="Y" data-behavior="X" data-token="XXX" class="XXX") with a hyper link created by using java script

I am creating a hyper link using java script.
Here is code snippet
var a = 1374.75;
var b = 'Hotel Delhi Airport Link';
var url = 'https://www.instamojo.com/stayuncle/payments-for-stayuncle'
var link = decodeURIComponent(url+'?data_amount='+a+'&data_Field_68092='+b)
alert("Redirecting to"+ link)
location.href = link
I want to pass following attribute with this link like
rel="X" data-behavior="Y" data-token="Z" class="P"
As we usually pass these parameter with hyper link using html tag
like
<p>
<a href="https://www.instamojo.com/stayuncle/payments-for-stayuncle/"
rel="X" data-behavior="Y" data-token="Z" class="P">check</a>
</p>
How can I do same in javascript?
You shouldn't decode the data in the URL, you should encode it. Encode each value by itself:
var link = url +
'?data_amount=' + encodeURIComponent(a) +
'&data_Field_68092=' + encodeURIComponent(b);
Regarding the attributes in the link, they are not related to the URL at all. If you click on the link they won't be included in the request. They may have some other function for any code that catches the click event and does something different, but that is not repeatable by putting anything in an URL.

Extracting the middle part of a URL and appending it to a new external link to display in IE8

I'm having some difficulty making a simple function to take a portion (a variable number of characters) of a URL and append it to another URL then display it.
Here's the kicker - it must work on IE8.
I'm currently using the following code in HTML with Javascript to append text input to a URL, but I would like to automate the process by having user input be the entire URL and extracting a part of it to the end of the base URL. I am currently using HTML and Javascript for open to suggestions on how to handle it cleanly in a method which will function correctly on IE8
Example of original URL - http://www.website.com/search?type=165498746&otheroperator?type=168574981&search?type=165498746&display
Example of part I need to extract - 165498746 (the first occurrence, directly after search?type=)
Example of complete URL to display - http://www.website.com/file?type=165498746
Javascript:
function ChangeLink() {
var inputlink = document.getElementById("userinputtext");
var baselink = document.getElementById("baseurl");
baselink.href = ("http://www.website.com/search?type=" + inputlink.value);
baselink.innerHTML = baselink.href;
}
HTML:
<form>
<a id="baseurl" href="http://www.website.com">www.website.com</a>
<input type="text" id="userinputtext" size="20">
<input type="button" value="Generate Profile Link" name="generate" onClick="ChangeLink()">
</form>
Noteworthy is that the part of the text I need to append to the end of the link will originate from the middle of the original link, and also that the original url may change in length of characters as will the actual portion I wish to append to the URL.
The only part which is consistent is that the part I wish to extract is after the initial "search?type=" and the ampersand directly after that, but both "search?type=" and the ampersand may appear more than once in the URL.
I have tried to slice() the text, but as the length of the portion I wish to slice varies in length I have been unable to.
Get the indexOf('?');
Get the substring from indexOf('?') to the end of the string.
String.split('&')
iterate through split.
For each split item, split it again on "="
First item of split is the name of the parameter.
Second item of the split is the value.
Check if it is the name of the parameter you are looking for or whatever you want.

How can I send POST data and navigate with JQuery?

On my blog I have a lot of <pre> blocks containing code snippets.
What I want to do is add a .click() handler to all the <pre> elements on the page which will send its content to another page - let's call it viewcode.php - via POST.
I know how to send information to this page using $.ajax, I'm just not sure how to send the information and navigate to the page.
The idea is that visitors can click a <pre> which will navigate to another page containing the code on its own for readability and easy copy / paste.
I have a feeling the solution is dead simple and probably obvious, I just can't think of it.
Not sure I would handle it this way, probably I would simply pop up a dialog with the code rather than leave the page, but you could handle this by building a form using javascript then triggering a submit on that form instead of using AJAX.
Using dialogs with jQuery UI:
$('pre').on('click', function() {
$('<div title="Code Preview"><p>' + $(this).text() + '</p></div>').dialog({
... set up dialog parameters ...
});
});
Build a form
$('pre').on('click', function() {
var text = $(this).text();
$('<form class="hidden-form" action="something.php" method="post" style="display: none;"><textarea name="code"></textarea></form>')
.appendTo('body');
$('[name="code"]').val(text);
$('.hidden-form').submit();
});
You could use a hidden <form> element. Then set the onclick() attribute of the <pre> to copy the value from the <pre> to the form. Optionally, you can set the action attribute to select the page you'd like to post the information to. Finally, submit that form.
I know it's not elegant, but it'll work.
If your code snippets are stored somewhere in a database or files, I suggest you just link the snippets to a page where you get the snippet based on some identifier.
If the snippets are only contained in your html, and you just want to display them in a cleaner way, you shouldn't need any ajax posting. You might want to Use a hover div or a jquery plugin, that pop's up and shows a cleaner piece of code obtained from the pre element, something like:
$('pre').click(function() {
var code = $(this).html(); //this is the pre contents you want to send
$('#hoverDiv').html(code).show();
});
Yes, you have to create a form and submit it. You can do all sorts of things with ajax posts/gets but the only way to navigate to a post result is via an actual form post. Here is concise version of it:
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();
My code does this:
// Navigate to Post Response, Convert first form values to query string params:
// Put the things that are too long (could exceed query string limit) into post values
var form = $('#myForm');
var actionWithoutQueryString = form[0].action.split("?")[0];
var action = actionWithoutQueryString + '?' + $.param(form.serializeArray());
var html = myArray.map(function(v, i) { return "<input name='MyList[" + i + "]' value='" + v + "'/>"; }).join("\n");
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();

Categories

Resources