document.getElementById onclick only working once per page load - javascript

I have a link:
<a id="lnk" href="${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext" onclick="update();"target="_blank">click to export</a>
and a JavaScript function in a separate file:
function update()
{
var link = document.getElementById("lnk");
link.href += "&var2=" + document.getElementById("textareaIdName").value;
return;
}
This is supposed to grab the text from a textarea box in a jsp form to pass into controller for output. It works the first time I click the link, but then if I change the text in the box and click link again it holds the same value from the first click on every other link click until I reload the page regardless of what I change in the text box. The link returns a file download.
How can I keep getting new text from textarea without reloading the page?

This occurs because you are using += each time the link is pressed which will keep concatinating the var2 onto the end of the hyperlink, to make this work you should use:
var linkName = "${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext";
function update(obj) {
obj.href = linkName + "&var2=" + document.getElementById("textareaIdName").value;
return;
}
<a id="lnk" href="" onclick="update(this);" target="_blank">click to export</a>

In your html:
<a ... onclick="return update(this);">click me</a>
Passing this in the handler means that this in the function references the DOM element, so you don't have to use getElementById, so the function is:
function update(link) {
link.href = /* whatever */;
}
Now you can put the handler on multiple elements without knowing or using the id.

Related

Pass on HTML element attribute to another element attribute

I’m using Elementor Pro for website development. I created a standard popup that is triggered if the user clicks on a link on the page like this
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink1.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink2.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink3.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink4.com”>test link</a>
The popup (on the same page) has a button that will forward the user to the external link previously clicked:
Take me to the link
Elementor offers no option to dynamically set the href value of the button based on the custom attribute (in this case “ext-link”), but I found no other option to dynamically set the href attribute of this button. Is there an easy JavaScript /jQuery escape here (no plugin!) that can be used to pass on the custom attribute value to the button link attribute?
EDIT -
I did some tryouts to fund a solution for this problem and I came up with the following:
<script>
// Append an onclick event to each link
let extLinkItems = document.querySelectorAll('[data-extlinkurl]');
extLinkItems.forEach((extLinkItem) => {
extLinkItem.setAttribute("onclick", "getUrl()");
});
The onclick event is added properly to each link here.
Because the function setLink (see below) did not work, I added some checks here:
console.log("Button count=" + document.querySelectorAll('#extlinkbtn').length); // Button count=1
console.log("Button href=" + document.getElementById("extlinkbtn").href); // Button href=http://www.test.com/
console.log("Button href=" + document.getElementById("extlinkbtn").getAttribute("href")); // Button href=http://www.test.com
These provided the expected results. The button is found and the href attribute is available.
function getUrl() {
var newUrl = event.currentTarget.getAttribute('data-extlinkurl');
console.log("newUrl=" + newUrl); // newUrl=https://www.mylink1.com
setUrl(newUrl);
}
Also works properly. When the link is clicked, the data attribute of the link is available.
function setUrl(newLink) {
let linkButtons = document.querySelectorAll('#extlinkbtn');
console.log("count=" + linkButtons.length) // count=0
linkButtons.forEach((linkButton) => {
linkButton.setAttribute("href", "'" + newLinkUrl + "'");
});
}
</script>
Here it becomes problematic. Once the link is clicked, the button cannot be found. The button is there, because the popup with the button is displayed on screen and the element visible. I'm testing several days now and either solution I tried did not work. Why is the button element found if searched on a global scope, but after the link is clicked the button is not available in the function scope?
Eventually and not thanks to the Elementor second line support, I found a solution. It seems that the content of the popup was initially loaded but deleted by a function after the DOM was loaded.
The solution was here: https://developers.elementor.com/elementor-pro-2-7-popup-events/
What I did was adding a custom data attribute to the link button that is clicked in the popup screen after this is loaded which holds the target URL. After this, I added some JS/jQuery to the popup template:
<script>
let newLinkUrl = "";
let extLinkItems = document.querySelectorAll('[data-extlinkurl]');
extLinkItems.forEach((extLinkItem) => {
extLinkItem.setAttribute("onclick", "getUrl()");
});
function getUrl() {
newLinkUrl = event.currentTarget.getAttribute('data-extlinkurl');
jQuery( document ).on( 'elementor/popup/show', () => {
document.getElementById('extlinkbtn').href=newLinkUrl;
});
}
</script>
This works perfectly

How do I add an anchor-tag to window.location?

I want to use that code here to reload the current page a user is on
<a href="javascript:window.location.href=window.location.href">...
And additionally I want the user to jump to a given anchor-tag #berechnen - how would I do that in that case?
I tried with something like so
<a href="javascript:window.location.href=window.location.href+#berechnen">
But of course that doesn't work. Do I need to save the window-location to a variable first and then add the #berechnen -string to it and then href to that variable?
In head:
<script type="text/javascript">
function redirectToAnchor(anchor) {
// We remove previous anchors from the current URL
var redirectToURL = document.URL.replace(/#.*$/, "");
redirectToURL = redirectToURL + anchor
window.location.href = redirectToURL;
window.location.reload(true)
}
</script>
Then:
<a href="javascript:redirectToAnchor('#ANCHOR')">
Personally I really dislike abusing the anchor tag by replacing its default behavior with JavaScript. By doing this, you break things like being able to open the link in a new tab, copying the link or bookmarking it.
One way you can keep this behavior and still reload the page after a click, is by adding the fragment to the href as you would do normally and in addition, you bind a JavaScript event that reloads the page when it is clicked. In that case you can simply use the href attribute to get the URL, and after you set the url, you reload the page. In the example below if the anchor has a force-reload class, it will also reload the page if you click on the anchor.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('force-reload') && e.target.nodeName === "A") {
e.preventDefault();
window.location = e.target.href;
window.location.reload();
}
});
Click here

How to simulate properly invoking a button via JS?

I'm using jQuery 1.10 in my project.
HTML:
<a id="btnStampa "class="btn btn-danger" href="" role="button" target="_blank" style="display:none;">
Print
</a>
JS:
function Print(e) {
var data = e.data.record;
if (data.token==null)
return;
$("#btnStampa").attr("href", "Ristampa41/" + data.token);
$('#btnStampa').trigger('click');
}
When I invoke Print method (within a table passing a token code) it doesn't open new window.
If set the button to visible, and I click after Print method invoked the working is that wanted
When I invoke Print method (within a grid passing a token code) it doesn't open new window.
If I set the Anchor tag to visible, and I click after Print method invoked the working is that wanted.
I also tried this code
$('#btnStampa').click();
but it doesn't work1
I need to have same behavoiur when I click on button but via JS.
Did you try click?
$('#btnStampa').click();
EDIT
Watchout: in your HTML, your ID has an extra space at the end and this must come from it ;)
By the way, I'm no jQuery expert, but did you consider using vanillaJS?
var link = document.querySelector('#btnStampa');
link.href= "Ristampa41/" + data.token;
link.click();
This works like a charm.

Browser option open link in new tab

I have action button for editing that doesn't have option "Open in new tab" when i right click.
Here is my code:
function actionsTemplateConversion(data) {
if (data != null){
if (canEdit){
row += '<a id="edit" title="${editTr}" onclick="edit(event);"></a>';
}
return row;
}
}
function edit(event) {
table = $('#table').data();
var dataItem = table.dataItem($(event.currentTarget).closest("tr"));
window.location = "users/"+dataItem.id+"/editUser.html?id="+"${id}"+"&name="+"${name}";
}
I've tried use href instead onclick and put this link from edit() function in href and with that i get option Open in new tab for right click, but also there is problem with this because if there is single qoutes in name than everything meesses up because of that qoutes. So only way is with this function.
I also tried with this window.location.href but it doesnt work.
Is there any other option for opening link beside window.location?
you can target at anchor tag this cause browser open new tab <a target="_blank" href=""/>
OR
if(user)
window.open(encodeURI('url'), '_blank');
else
window.open(encodeURI('url'));
if the quote in name try to encode it
https://www.w3schools.com/TAGS/ref_urlencode.asp
<a id="edit" title="${editTr}" onclick="edit(event);"></a>
That isn't a link. A link must have an href attribute. Without one, there is no URL to open when you click it or open in new tab. There is just a JavaScript program that runs.
I've tried use href instead onclick
That's the solution
link from edit() function in href and with that i get option Open in new tab for right click, but also there is problem with this because if there is single qoutes in name than everything meesses up because of that qoutes
This is the problem with generating HTML by mashing strings together instead of using DOM.
You have to very carefully escape everything.
Use DOM instead.
Since you are using jQuery already. Something along these lines should get you started:
var url = "users/" + encodeURIComponent(dataItem.id) + "/editUser.html?id=" + encodeURIComponent("${id}") + "&name=" + encodeURIComponent("${name}");
var $link = jQuery("<a/>")
.attr("href", url)
.attr("title", "${editTr}")
.attr("id", "edit") // Are you sure this is a UNIQUE id? Should this be a class instead?
.on("click", edit);

How to get jQuery to open a page in the current tab rather than a new one

Before saying that the answers are already on the forum take note that I have already tried them to no avail. Basically the problem is that when I press enter to search it opens the google page in a new tab. How do I get it to open in the current tab?
This is the HTML
<div class="Search">
<img id="pic" src="http://i.imgur.com/fjAZgqe.png" alt="moose"/>
<form class="websearch">
<input autofocus placeholder="Google" type="text" id="GGLSite"> <!--this creates the textbox they can use to search. Note the ID is what the function grabs -->
<input type="button" id="GGLmeme" onclick="DoGGL()" style="display: none;" value="Search GGL"> <!-- this is just the button that calls the function. The value is whats shown on the button -->
</form>
</div>
This is the Javascript
function DoGGL(){
var GGLVar = document.getElementById("GGLSite").value; //this grabs the variable (search terms) from the textbox
var NewURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + GGLVar; //this puts the site they typed into the wayback machines URL
var NewTabGGL = window.open(NewURL, "_blank"); //this opens a new tab with the URL.
if (NewTabGGL){ //make sure the browser can allow it
NewTabGGL.focus(); //switches them to the new tab -- done!
}
else{
alert("Popup didnt work");
}
}
$(document).ready(function(){
$('#GGLSite').keypress(function(e){
if(e.keyCode==13)
$('#GGLmeme').click();
});
});
I did some tweaks on your code (read the comments):
Javascript
// Remember capitalized functions are supposed to be used with the new operator, hence, this function must not be capitalized
function doGGL(event){
// Here we prevent the default behavior of the form submit
event.preventDefault();
// Javascript variables must not be capitalized
var gGLVar = document.getElementById("GGLSite").value;
var newURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + gGLVar;
// This sentence navigates to desired URL in the same window
window.location.href = newURL;
}
$(document).ready(function(){
// There's no need to catch the enter key because that's the form default behavior. So I'm attaching the submit event to the function defined above
$('.websearch').on('submit', doGGL);
});
This didn't work in jsFiddle so I tried it in a local file called index.html with the same HTML, CSS but replacing the javascript with the latter.
Hope it helps!
If you are trying to just get to the page from this page, window.location = NewURL; would work. I don't see exactly what you're trying to do.

Categories