Django Delete Confirmation - javascript

I have an icon of a trash can for a delete button on a Django site.
It's just an anchor tag with an i tag inside that has its href set to a delete view passing the id of the model element.
It works perfectly fine, but I want to create a dialog popup that asks for confirmation before deleting it.
I have seen a few ways to do this but they all require it to be input instead of an anchor.
I also need to make this work on touch devices as well.
How can I change it to an input element and keep the icon as the button rather than showing a submit button. And how can I get the dialog to popup and when Yes is clicked, pass the correct url and id to the submit?
Any advice would be much appreciated.

The easiest way is to add a confirm prompt:
<a ... onclick="return confirm('Are you sure you want to delete this?')">Delete</a>
But you should not do inline javascript so try to add a class and abstract it away. Here it is with jquery:
<a class="confirm-delete" ...>Delete</a>
$(document).on('click', '.confirm-delete', function(){
return confirm('Are you sure you want to delete this?');
})

Let this be your anchor tag:
<a class="icon-trash" id="delete-object" data-object-id="{{ object.id }}">Delete</a>
Note that we have object.id with an attribute. We are going to need that in javascript part.
And you can write something like this at bottom of the page right before body tag closed:
UPDATE WITH SNIPPET
Here you can try the demo. it should work when you put the code right before body tag closed:
var elm = document.getElementById('delete-object');
var objectID = elm.getAttribute('data-object-id');
var resultDiv = document.getElementById('result');
elm.addEventListener('click', function() {
var ask = confirm('r u sure?');
if (ask && objectID) {
var r = "Page will be redirected to </object/delete/" + objectID + "/>";
resultDiv.textContent = r;
} else {
resultDiv.textContent = "User cancelled the dialog box...";
}
return false;
});
.delete-link {
background-color: red;
color: white;
border: 1px solid white;
cursor: pointer;
padding: 3px;
}
#result {
margin: 20px;
padding: 10px;
border: 1px solid orange;
}
<a class="delete-link" id="delete-object" data-object-id="3">Delete</a>
<div id="result"></div>

Just adding this attribute on your a / button tag will do the Job:
onclick="return confirm('Are you sure you want to delete?')"

Related

When visit a page, add class to div and save in cache

How can I add a class to a div when I visit a page in my website and save this on cache?
For example: I have a index.html that looks like this: https://i.stack.imgur.com/6iJEr.png
What I wanna do is when someone click in one div (witch is linked to a page like page3.hml) this div will add a class and save in cache, so when back to index.html this div will still have this class. Like this: https://i.stack.imgur.com/lMjZG.png
The class wold be something like
.visited{
border-bottom: 10px solid red;
}
Is this possible?
Sorry for my English :(
You can use local storage to save the divs. With my example, each div needs a different ID and a click handler added to a class.
SO Snippets doesn't allow local storage so here is a working fiddle: https://jsfiddle.net/hdo4sq9j/2/
.visited{
border-bottom: 10px solid red;
}
<div id="id1" class="clickme">1</div>
<div id="id2" class="clickme">2</div>
<div id="id3" class="clickme">3</div>
visited = localStorage.getItem('visited')
if (visited === null) {
localStorage.setItem('visited', []);
visited = [];
}
else{
visited = visited.split(",")
}
divs = document.querySelectorAll(".clickme");
divs.forEach(function(div) {
div.addEventListener("click", function(ev) {
if (visited.indexOf(div.id) == -1) {
visited.push(ev.target.id)
}
localStorage.setItem('visited', visited);
})
if (visited.indexOf(div.id) > -1) {
div.classList.add("visited")
}
});
The simplest method would be using the CSS :visited selector if you won't mind converting those divs into hyperlinks.
Then it would be something like:
a:visited {
border-bottom: 10px solid red;
}
Check out the w3schools article about the hyperlink selectors:
https://www.w3schools.com/css/css_link.asp

HTML button to open URL in a new window

I'm populating an email template and I'm having some issues with the button onclick event.
What I am trying to achieve is when clicking on the button it should open a URL in a new window rather than a new tab.
Currently when the email gets sent it is losing the onclick event functionality. Any recommendations on how can I achieve this?
I have also tried creating the button in the html template rather than replacing the tags as code below, but still run into the same issue.
HTML Code:
<p>
Hi,
</p>
<p>
A [JobType], to start on [JobStartDate]
<br />
Click here to view the job: [JobUrl]
</p>
<p>
<b>Job Details:</b>
<br />
- Reference: [JobReferenceNumber]
<br />
- Checklist: [AnswerEvaluationName]
<br />
- Created by: [JobCreator]
<br />
</p>
<p>
Kind regards<br />
</p>
<p class="auto-style6">
Please do not reply to this system generated email
</p>
</body>
public void CreateEmailNotificationForNewJob()
{
// Populate the Email Template
string EmailRecipientTestingNotes = "";
string EmailSubject = "";
string EmailTemplate = EmailSender.LoadEmailTemplate("EmailNewJob.html");
string EmailTo = "";
string TestButton = ("<input type=\"button\" onclick=\"window.open('https://www.google.com/','mywin','width=500,height=500');\" >");
EmailSubject = "Job/task ";
EmailTemplate = EmailTemplate.Replace("[JobReferenceNumber]", "Reference");
EmailTemplate = EmailTemplate.Replace("[AnswerEvaluationName]", "Daily Update");
EmailTemplate = EmailTemplate.Replace("[JobStartDate]", "Today");
EmailTemplate = EmailTemplate.Replace("[JobType]", "1");
EmailTemplate = EmailTemplate.Replace("[CompanySiteName]", "");
EmailTemplate = EmailTemplate.Replace("[SiteName]", "");
EmailTemplate = EmailTemplate.Replace("[JobUrl]", TestButton);
EmailTo = "test#test.co.za";
try
{
// Send email code
}
catch (Exception ex)
{
// Add handling
}
}
Most email clients don't allow execution of JavaScript like a browser would (usually this is for security reasons).
But if you want to create a link to a URL to display in the email, you can just use a hyperlink instead of a button. (You can of course always use CSS to make it look like a button, if you wish.)
string TestButton = ("<a href='https://www.google.com/'>Click here</a>");
Email clients won't accept JavaScript.
The best you can do is to use a standard link with the target attribute set to _blank:
string TestButton = ("<a href='www.blah.com' target='_blank'>link text</a>");
Having said that, most email clients will open in a new/blank tab anyway. However, this is helpful still for those who use click "view this email in your browser" (on Outlook desktop, for example, this is generated automatically).
Just use a hyperlink instead of a button because email clients won't accept JavaScript.
Of course you can use css to make it looks like a button.
Button:
string TestButton = ("<a class='button' href='https://www.google.com/'>Click here</a>");
Css:
.button {
font: bold 11px Arial;
text-decoration: none;
background-color: #EEEEEE;
color: #333333;
padding: 2px 6px 2px 6px;
border-top: 1px solid #CCCCCC;
border-right: 1px solid #333333;
border-bottom: 1px solid #333333;
border-left: 1px solid #CCCCCC;
}

Why can I not add a space to the text of a HTML button with the 'contenteditable' attribute?

I have a button in HTML and I want the user to be able to change the button's text when double clicking.
<button onclick='doStuff()' ondblclick='renameButton()' id='myButton'>Click Me</button>
This is my function in JavaScript:
function renameButton() {
var button = document.getElementById('myButton');
button.setAttribute("contenteditable", true);
}//end renameButton
This function allows me to edit the button:
Issue 1) I cannot add a space when editing the button. The space-bar on my keyboard literally does nothing.
Issue 2) Is it possible to set a white background on the editable text to allow the user to see that it is editable? As far as I know, it is only possible to control the background color of the entire button element, but not the text node.
You need to put a span kind of element to hold the text inside the button if you want to make sure SPACE is fed into the content.
On a button, space is a trigger for button press and hence can't be added in to the text with contenteditable attribute.
See it working here: https://jsfiddle.net/mwwj1jty/2/
HTML
<button onclick='doStuff()' ondblclick='renameButton()' id='myButton'><span id="myspan">Click Me</span></button>
JAVASCRIPT
function renameButton() {
var span = document.getElementById('myspan');
span.setAttribute("contenteditable", true);
span.style.backgroundColor = "red";
}//end renameButton
You could put a span inside the button where the text is, and change the background-color of the span instead as seen here https://jsfiddle.net/msoLg3qb/
HTML
<button ondblclick='renameButton()' id='myButton'><span>Click Me</span></button>
CSS
span {
background-color: white;
}
button {
background-color: green;
}
JAVASCRIPT
var button = document.getElementById('myButton');
function renameButton() {
button.setAttribute("contenteditable", true);
}
Don't use a button element for this, as you can see that there are limitations. When a button is active, pressing the SPACE key initiates a click event. To get around this, use a different element, a span would be perfect here.
I've also added the background color as you asked about.
Lastly, don't use inline HTML event attributes (onclick, etc.). That's an ancient technique that just will not die but has many reasons not to use it. Instead, follow modern standards and use .addEventListener().
// Get a reference to the button
var spn = document.getElementById("myButton");
// Set up your event handlers in JavaScript, not in HTML
spn.addEventListener("click", doStuff);
spn.addEventListener("dblclick", renameButton);
spn.addEventListener("blur", saveName);
function renameButton() {
spn.contentEditable = "true";
spn.classList.add("edit");
}
function saveName(){
spn.contentEditable = "false";
spn.classList.remove("edit");
}
function doStuff(){
}
/* Make span look like a button */
.button {
display:inline-block;
padding:5px 20px;
border:1px solid grey;
background-color:green;
border-radius:2px;
cursor:pointer;
box-shadow:1px 1px 1px grey;
color:white;
user-select:none;
}
/* Make span feel like a button */
.button:active {
box-shadow:-1px -1px 1px white;
}
/* Style to add while content is editible */
.edit {
background-color:white;
color:black;
}
<span id='myButton' class="button">Click Me</span>

Remove class from <a> button after pressing another <a> button

I'm trying to create a site, on which you can download a file by pressing an button. The thing is, that I want people to click another button first to subscribe to a youtube channel and THEN to be able to download the file. So, I have to get rid of the disabled class on the download button after pressing the subscribe button. Here below is my code, what am I doing wrong?
EDIT: Tried all the answers now, none did work. I'm getting this error, what does that mean?
Uncaught ReferenceError: $ is not defined
at index.html:23
Line 23 is
$('#sub').on('click',function(event){
$('#sub').on('click',function()){
$('#dl').removeClass('disabled');
});
.disabled {opacity: 0.8; cursor: not-allowed;}
.size-3 {font-size: 16px;}
.btn {
font: 100%/1.1 "Quicksand", sans-serif;
background-color: rgba(0,0,0,0.3);
border: 2.2px solid #ecf0f1;
color: #ffffff;
padding: 12px 62px;
text-align: center;
text-decoration: none;
display: inline-block;
text-transform: none;
font-size: 20px;
margin: 3px 6.9px;
cursor: pointer;
transition-duration: 0.4s;
}
<a id="sub" href="#" class="btn size-3">Subscribe to ZERO</a>
<a id="dl" href="#" class="btn size-3 disabled">Download Exyther</a>
jsFiddle: https://jsfiddle.net/qrc3qm2e/
I have added extra code to check if the button shouldn't be clickable, if you need a jQuery answer please follow this link https://jsfiddle.net/qrc3qm2e/1/
Javascript
var subElement = document.getElementById("sub");
var dlElement = document.getElementById("dl");
subElement.onclick = function(event)
{
dlElement.classList.remove('disabled');
dlElement.removeAttribute('disabled');
};
dlElement.onclick = function(event)
{
if(dlElement.className.indexOf('disabled') > -1)
{
event.preventDefault();
return;
}
};
HTML
<a id="sub" href="#" target="blank" class="btn size-3">Subscribe to ZERO</a>
<a id="dl" href="#" target="blank" class="btn size-3 disabled" disabled="disabled">Download Exyther</a>
This makes your code an error: function()) << double close
correct JS
$('#sub').on('click',function(event){
event.preventDefault();
$('#dl').removeClass('disabled');
});
https://codepen.io/jacobweyer/pen/JNzgJE?editors=1111
Here's a codepen of the issue
$('#sub').on('click', function(event){
if (event.preventDefault) {
event.preventDefault();
}
$('#dl').removeClass('disabled');
});
You didn't close the function, but also you can add event into the function. This will pass the click event into your jquery.
With the click event you can actually prevent the page from jumping moving as well by preventing the default action on the a tag.
You can help by keeping your example really really simple. We don't need to know about your font for example. : )
You probably want to use a disabled property - or that AND style that a bit with CSS. here's how to do that. - if you want to use a link - then the download will be its default behaviour - so you shouldn't have to prevent it - but see #JacobW 's about that. You'd likely not want the URL in the markup - if you are really trying to dissuade them from getting the file until subscribing. If you can't switch out the button for the link - and see the concept, I'm sure you will at some later date. : ) Good Luck!
JavaScript - and disabled property
https://jsfiddle.net/sheriffderek/3t0pn6gv/
markup
<button class='one'>one</button>
<button class='two' disabled>two</button>
style
button:disabled {
opacity: .3;
}
script (not jQuery for #Canvas)
var signupButton = document.querySelector('button.one');
var downloadButton = document.querySelector('button.two');
signupButton.addEventListener('click', function() {
downloadButton.disabled = false;
});
with jQuery and CSS class - (not actually disabled... but looks so)
https://jsfiddle.net/sheriffderek/wyx1od9g/
markup
<button class='one'>one</button>
<button class='two disabled'>two</button>
style
.disabled{
opacity: .2;
}
script
$('button.one').on('click', function() {
$('button.two').removeClass('disabled');
});

Javascript to dynamically add textbox , and again convert the text box to text

I need something like a fill in the blanks sheet for children. When people click the ------ (dashes) it should turn into a textbox, and people can type it. after that when they move from that element after typing, it should turn into the text that they entered inside that text box.
I really dono how to approach this problem. I tried the following code, but what happens is, i am unable to type inside the text box. The cursor is not appearing at all
<html>
<head>
<title>NSP Automation</title>
<script src ="jquery.min.js">
</script>
</head>
<body>
<div class="container">
My Name is = <span id="name">__________<span>
</div>
<script>
$(document).on('click', '#name', function(){
document.getElementById("name").innerHTML = "<input type=\"text\">";
});
</script>
</body>
</html>
any pointers on how to achieve this ?
Thanks,
Since you've set the listener on the whole document, you will be recreating the input-tag with every click. Try something like:
$('#name').on('click', function(){
this.innerHTML = "<input type=\"text\">";
$('#name').off('click')
}
After clicking on the span-element, you remove the listener on it again, and you should be able to type.
http://jsfiddle.net/218rff9v/
Here is an example that generates the wished behaviour for all spans in your container. Some details can be improved but I think it's working as expected.
function convertSpanToInput() {
// Insert input after span
$('<input id="tmp_input">').insertAfter($(this));
$(this).hide(); // Hide span
$(this).next().focus();
$("#tmp_input").blur(function() {
// Set input value as span content
// when focus of input is lost.
// Also delete the input.
var value = $(this).val();
$(this).prev().show();
$(this).prev().html(value);
$(this).remove();
});
}
$(function() {
// Init all spans with a placeholder.
$(".container span").html("__________");
// Create click handler
$(".container span").click(convertSpanToInput);
});
Here is an html example with which you can test it:
<div class="container">
My Name is = <span></span>. I'm <span></span> years old.
</div>
JsFiddle: http://jsfiddle.net/4dyjaax9/
I'd suggest you have input boxes and don't do any converting
Simply use CSS to remove the borders and add a dashed border bottom
input[type=text]{
border:none;
border-bottom:1px dashed #777;
} <!-- something like that -->
add a click handler to add a edited class, so you can remove the bottom border
input[type=text].edited{
border:none;
}
That way you don't need to replace html elements, you just style them to look different
Why not use text input and only change CSS classes?
CSS:
.blurred{
border-style: none none solid none;
border-width: 0px 0px 1px 0px;
border-bottom-color: #000000;
padding: 0px;
}
.focused{
border: 1px solid #999999;
padding: 3px;
}
JavaScript:
$('#nameInput').focus(function(){
$(this).removeClass('blurred').addClass('focused');
});
$('#nameInput').blur(function(){
$(this).removeClass('focused').addClass('blurred');
});
HTML:
<div class="container">
My Name is = <span id="name"> <input id="nameInput" type="text" class="blurred"></input> <span>
</div>
Check this jsfiddle:
http://jsfiddle.net/gwrfwmw0/
http://jsfiddle.net/we6epdaL/2/
$(document).on('click', '#name', function(e){
if( $("#myText").is(e.target))
return;
$(this).html("<input type='text' id='myText' value='"+ $(this).html() +"'>");
});
$(document).on("blur", "#name", function(){
$(this).html( $("#myText").val() );
});

Categories

Resources