I have a web page to download files using a button.But for some cases the files does not exit and download links are blank...So whenever the user clicks the link page just reloads.It would have been great if i could somehow disable the page reload and display an alert that says file not yet available..
This is the download link button code.row["slink"] gives the download link and may become empty sometime.
'<button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn> ';
Check if row['slink'] is present, else replace href with javascript:alert(...)(This won't do page reload for blank href, and show an alert):
var href = row["slink"].trim().length > 0 ? row["slink"] : "javascript:alert('File Not Yet Available')"
'<button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn> ';
Simple Solution
You can set target to blank:
<a ... ... target="_blank" > ... </a>
This will open it in a new tab instead of refreshing.
More Sophisticated Approach:
You can also use a conditional to build your anchor tag.
if (row["slink"] == "")
{
var atag = '<button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</button> ';
}
This will give an alert if there is no file.
Related
I have the following function for copying a string of text:
function copyText(str) {
console.log(str);
let tmp = $('<input type="text">').appendTo(document.body);
tmp.val(str.toString() );
tmp.select();
document.execCommand('copy');
tmp.remove();
}
This function works fine, both when called from the console and when called from a button press.
I have a function that copies a color:
function copyColor(elm) {
let hex = $(elm.parentElement).find('span').html();
console.log('copyText("' + hex + '")' );
copyText(hex);
}
This function is called when a button is pressed. The button passes itself as the parameter. I am dynamically creating the buttons (each one represents a new "color item"). Here is the HTML that is dynamically inserted with jQuery:
'<button class="btn copy-btn no-color" title="Copy" data-toggle="popover" onclick="copyColor(this);"><i class="fas fa-copy"></i></button>'
The whole thing is:
$('#' + mode + '-modal .modal-body').prepend(
'<div class="' + mode + '-item color-item">'
+ '<button class="btn open-btn no-color" title="Open Color" data-toggle="popover" onclick="openColor(this, \'' + mode + '\');"><i class="fas fa-external-link-alt"></i></button>'
+ '<input class="form-control color-name" type="text" placeholder="Name your color (optional)" value="' + name + '">'
+ '<br class="mobile-only">'
+ '<div class="color-preview" style="background-color:' + hex + ';"></div>'
+ '<span>' + hex + '</span>'
+ '<button class="btn copy-btn no-color" title="Copy" data-toggle="popover" onclick="copyColor(this);"><i class="fas fa-copy"></i></button>'
+ '<button class="btn link-btn no-color" title="Get Link" data-toggle="popover" onclick="copyColorLink(this);"><i class="fas fa-link"></i></button>'
+ '<button class="btn delete-btn no-color" title="Remove" data-toggle="popover" onclick="removeColor(this);"><i class="fas fa-trash"></i></button>'
+ '<i class="fas fa-arrows-alt" style="cursor:move;" title="Drag to Change Order" data-toggle="popover"></i>'
// + '<button onclick="copyText(\'hi\')">hi</button>'
+ '</div>'
);
where mode, hex, and name are all parameters in this function.
Every time I click to copy the color, it calls the copyColor() function, gets the correct string, calls the copyText() function, gets the correct string, and runs with no errors, however it fails to edit my clipboard. When calling this function from the console, with the exact same string, it works, and when creating a static button to copy the color, for example:
<button onclick="copyText('hi')">hi</button>
then it works fine as well. I have also tried dynamically adding one of these buttons:
+ '<button onclick="copyText(\'hi\')">hi</button>' to my code that injects HTML, and it does not work.
Other dynamically created buttons seen above also call functions and pass themselves as a parameter and work fine, for example the delete button, calling the removeColor() function with this as the parameter.
Lastly, I've tried giving the buttons dynamic IDs, by way of:
'<button id="copy-btn-'+ nextID +'" etc...
Where nextID is a value I increment, and I add the onclick listener for that specific button immedatly after creating it:
$('#copy-btn-'+nextID).click(function() {
copyText('hello');
});
nextID++;
I've tried creating a new copy function that only takes in the string, and instead of passing an element I just pass the string to be copied:
function copyColorNew(hex) {
console.log('copyText("' + hex + '")' );
copyText(hex);
}
and here is the relevant part of the inserted button code:
onclick="copyColorNew(\''+hex+'\');">
and it calls the function correctly, passes the correct arguments, and fails to copy the string.
I don't have any duplicate function names, all files are included correctly, I've hard refreshed the page, all variables are in their respective scope, and I've never got any errors. I've also omitted dozens of other rather inconclusive experiments I've done.
I am completely out of ideas, and I've spent several hours a day for several days on this problem. I am well aware how to copy a string in javascript, I'm well aware of how to create a button and append it dynamically, and I'm well aware of how to give the button an onclick listener that passes itself as a parameter. I've had no problems with these things in the past and I still do not everywhere else in this code as I've detailed above.
The only thing I can think of is it's a security problem to allow dynamically created DOM elements to call functions that access the clipboard, but I'm not even pasting the data.
Once again, buttons in the static HTML page can correctly copy 'hello world', dynamically inserted ones cannot copy 'hello world'.
By using the clipboard API (suggested by u/elmstfreddie on Reddit):
navigator.clipboard.writeText(hex);
I got it to work. I replaced copyText(hex); with navigator.clipboard.writeText(hex); in my copyColor() function.
Here is the link to the docs.
I am trying to add a download element to the page. I click it using Greasemonkey.
The new div has been added to the page but the download window is not opening.
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body') [0].appendChild(iDiv);
iDiv.innerHTML = '<button class=button> <a href=' + link + ' target=_blank> </button>';
document.getElementsByClassName('button') [0].click();
<a href=http://somesite.com target=_blank> is invalid. You're missing quotes around the URL.
Also, as #Springfield pointed out, you're not closing your <a> tag.
Solution :
iDiv.innerHTML = '<button class="button"> Link</button>';
which renders :
iDiv.innerHTML = '<button class="button"> Link</button>';
Don't wanna be rude, but first questions first: Where does your anchor-tag end?
You open an a-tag, but its content as well as the end tag are both missing.
I'm writing a javascript app that dynamically generates buttons that lead users to links about different products.
They look like this:
The problem is when they're generated the links contained within them work in chrome but not in IE or Firefox.
Here's the HTML:
HTML
<div class="row">
<div class="button-class">
</div>
</div>
This is the code I use to generate them:
JQUERY
buttons: function(num) {
$(".button-class").html("<div class='text-center'><ul class='list-inline'><li><button class='btn btn-success'><a href=" + state.greens[num].website + " target='_blank'>Company Website</a></button></li> <li><button class='btn btn-success' data-toggle='modal' data-target='#myModal'>View the Label</button></li></ul></div>");
if (state.greens[num].link !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href=" + state.greens[num].link + " rel='nofollow' target='_blank'>Get It On Amazon</a></button></li>");
}
if (state.greens[num].review !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href=" + state.greens[num].review + " target='_blank'>Read The Review</a></button></li>");
}
},
buttons is part of an object called display and is called by display.buttons();
The two if statements check to see if certain types of links exist within a product's object and then appends them to the UL if the ydo.
The buttons generate correctly but they don't open up the links when clicked in Firefox and IE (maybe Safari but I haven't checked).
What's more confusing to me is that the html being generated looks semantically correct.
For example this is the html shown in the Firefox debugger that's not working:
Doesn't make sense to me.
If you want to go to a live version of the page you can see it here: superfood picker
Then go to the last section that reads "Click On A Product's Detail Page To Learn More" and looks like this:
Click on one of the products and it'll take you to the buttons that I'm talking about.
It's not semantically correct because you need to wrap in quotes the href
buttons: function(num) {
$(".button-class").html("<div class='text-center'><ul class='list-inline'><li><button class='btn btn-success'><a href='" + state.greens[num].website + "' target='_blank'>Company Website</a></button></li> <li><button class='btn btn-success' data-toggle='modal' data-target='#myModal'>View the Label</button></li></ul></div>");
if (state.greens[num].link !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href='" + state.greens[num].link + "' rel='nofollow' target='_blank'>Get It On Amazon</a></button></li>");
}
if (state.greens[num].review !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href='" + state.greens[num].review + "' target='_blank'>Read The Review</a></button></li>");
}
},
Note that's it's best if you change double quotes instead single quotes and viceversa.
I am trying to create a popup window and put 2 button on that, and when click on the button the value of btn be true and close the popup and see the Main window,
I have done some thing! but when the main window loaded its gray!
I mean this:
and this:
and when press F12 in browser I see this:
<body class="modal-open" style=""></body>
and this is my .cshtml file:
#{
List<string> formRows = new List<string>();
string btnReceiptPrint = string.Format(#"<button id='BtnReceiptPrint' style='height:35px;width:110px;' class='btn btn-success' type='button'
onclick='$(""#ReceiptPrint"").val(""true"");hideModal(this);_submitForm(""sellInvoiceForm"");'>{0}</button>", Resources.UI("ReceiptPrint"));
string btnNormalPrint = string.Format(#"<button id='BtnNormalPrint' style='height:35px;width:110px;' class='btn btn-success' type='button'
onclick='$(""#NormalPrint"").val(""true"");hideModal(this);_submitForm(""sellInvoiceForm"");'>{0}</button>", Resources.UI("NormalPrint"));
formRows.Add("<p style ='text-align : center'>" + btnReceiptPrint + "</p>");
formRows.Add("<p style ='text-align : center'>" + btnNormalPrint + "</p>");
#Html.FormGroupGenerator(formRows)
}
Can anyone help me PLZ?
When you press btn then do : $('#your-modal').modal('hide'). It will close the modal.
We have uplaod function on our site. And uploaded file, displays link which on click user can see file they have uploaded in new window.
We also use divbox http://jquery.phpbasic.com/divbox
My code is this:
$("#uploader" + queueId).html("
<div class='cancel'>
<input class='button_cancel' name='removeFile' fileName='"
+fileObj.name.replace("'", "%27")+"' type='button'>
</div>
<a class='lightbox' href='" + self.attr("path")
+ fileObj.name.replace("'", "%27") + "'><span class='fileName'>"
+fileObj.name+"</span></a>");
For some reason when we click on the link, it still opens in new window and doesnt initiate the lightbox.
In my page i see this ( all normal )
<a class="lightbox" href="uploads/nutshell.png">
<span class="fileName">nutshell.png</span>
</a>
Which should fire the lightbox.. Anything scream out at you in the js code I posted above ? I am wondering if its self.attr("path")
Here is what we have::::::
in the js for divbox we have
$('.lightbox').divbox({caption: false});
in the js for the uploader we have.
$("#uploader" + queueId).html("<div class='cancel'><input class='button_cancel' name='removeFile' fileName='"+fileObj.name.replace("'", "%27")+"' type='button'></div><a class='lightbox' href='" + self.attr("path") + fileObj.name.replace("'", "%27") + "'><span class='fileName'>"+fileObj.name+"</span></a>");
Presumably you're doing something like this:
$('a.lightbox').divbox({ ... })
before you add the <a> in question with:
$("#uploader" + queueId).html("...");
$('a.lightbox') only applies to elements that exist on the page when $('a.lightbox') is called, it won't bind DivBox to elements that are added to the page later. You'll have to bind DivBox to the new <a> that you added with something like this:
$("#uploader" + queueId).html("...");
$('#uploader' + queueId).find('a.lightbox').divbox({ /* and whatever options you need */ });
Rough demo of the technique: http://jsfiddle.net/ambiguous/EswfB/
To build off of mu is too short's answer, you could implement like so:
$("#uploader" + queueId).html("
<div class='cancel'>
<input class='button_cancel' name='removeFile' fileName='"+fileObj.name.replace("'", "%27")+"' type='button'>
</div>
<a class='lightbox' href='" + self.attr("path")
+ fileObj.name.replace("'", "%27") + "'><span class='fileName'>"
+fileObj.name+"</span></a>")
.find('a.lightbox')
.divbox({ /* and whatever options you need */ });
And simply chain the commands into one.