I have a small problem, I made a delete button with a PHP while loop which looks like this:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<button onclick="delconfirm()">Delete</button>
}
this echo's a few delete buttons for some content. However I need user confirmation for deleting first, this is where onclick="delconfirm()" comes in.
my confirm looks like this:
function delconfirm()
{
var r=confirm("Are you sure you want to delete this content?");
if (r==true){
// ...do nothing i guess? it needs to redirect using the PHP echo'd link...
}
else{
window.location = "edit.php";
}
}
However, whether you press cancel or ok, it'll delete it anyway. How can I fix this?
Change it to this:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<button onclick="return delconfirm();">Delete</button>
}
And then your function:
function delconfirm()
{
return confirm("Are you sure you want to delete this content?");
}
EDIT: If you want a more unobtrusive solution:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<input type="button" value="Delete" data-id="$id" />';
}
And then some javascript to bind the event:
function bindButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].type == "button") {
buttons[i].onclick = function () {
location.href='somewhere.php?id=' + this.getAttribute("data-id");
}
}
}
}
and bind it to the window.onload, as per Ian suggestion:
window.onload = bindButtons;
Note: If you were using jQuery this solution would be easier and more elegant.
Working jsFiddle
If the user presses cancel then you need to stop the event from doing what it would normally do. Try this, for example:
function delconfirm(e) {
e = e || window.event;
if (!confirm("Are you sure you want to delete this content?")) {
e.preventDefault();
// This will prevent the event from bubbling up to the <a>.
e.stopPropagation();
return false; // For the ancient/crappy browsers still out there.
}
return true;
}
You need to stop/delete the current click event. After your code is executed the event sinks to the anchor and triggers a click. With MooTools just add 'new Event().stop();'. I think jQuery has also something like this.
EDIT: Hanlet EscaƱo is right. You can return true (the browser will redirect to the URL in the href, or false to let the browser do nothing)
In order to prevent to the HTML link to work, you have to return false in your js function or event.preventDefault() where event is an argument which is passed to the click event function
I did thin when putting a click event on the a element and not on an element inside the a tag. But it might work.
Related
i'm currentrly coding in php and when i click a button the message should me Would you like to delete this entry?
This is where I'm currently at
<button onClick="alert('Sure to delete entry?')">Remove Entry</button>
And sure it works. But when I press "x" to close the alert window it still deletes the entry.
How can you make a popup window that has the "Cancel" opition?
I would really appreciate the help! :)
if (confirm("Your question")) {
// do things if OK
}
Use confirm
Click here for examples
You can do this using the following JavaScript code:
if (confirm('Sure to delete entry?') == true) {
//write your code here to delete
}
The HTML
<a href="delete.php?delete=<?php echo $row['guestbook_id'];?>"
onclick="return areYouSure()">Remove Entry</a>
And the JS
function areYouSure()
{
var con = window.confirm("Are You Sure?");
if(con)
{
return true;
}
else
{
return false;
}
}
In my website authors (users) can mark posts as favorite.
It works this way:
if ($favinfo == NULL || $favinfo == "") {
$favicon = "ADD"; .
}
else {
$favicon = "REMOVE";
}
Its suposed to look dynamic, it works, when user click ADD, it adds the post to his favorites and reload the page with the REMOVE link.
The problem is its not really dynamic it reloads all the page.
How can i only reload that link (wich is inside a div)?
I know i have to use ajax, jquery, etc, but i tried some examples found here in S.O. but no success.
$('a').on('click', function(e){
// the default for a link is to post a page..
// So you can stop the propagation
e.stopPropagation();
});
Including this stop you page from reloading your entire page
If you want it to be dynamic, you will need to use AJAX. jQuery has ajax support which makes this really easy. If you are not familiar with ajax or javascript you should read up on it first.
PHP
if ($favinfo == NULL || $favinfo == "") {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"add\" href=\"".$siteurl."/author/favorites.php"\">ADD</a>"; .
}
else {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"remove\" href=\"".$siteurl."/author/favorites.php"\">REMOVE</a>";
}
JavaScript
$('a.fav-btn').on('click', function(e){
var $this = $(this), // equates to the clicked $('a.fav-btn')
url = $this.attr('href'), // get the url to submit via ajax
id = $this.attr('data-id'), // id of post
action = $this.attr('data-action'); // action to take on server
$.ajax({
url: url+'?'+action+'='+id
}).done(function(){ // once favorites.php?[action]= is done...
// because this is in .done(), the button will update once the server has finished
// if you want the link to change instantly and not wait for server, move this outside of the done function
if(action === 'add'){
$this.attr('data-action', 'remove').html('REMOVE'); // update the button/link
}else{
$this.attr('data-action', 'add').html('ADD');
}
})
return false; // prevent link from working so the page doesn't reload
}
If you are okay with using JQuery, you have some tools to accomplish this.
Have a structure / method of identifying your links.
You can have a click() listener on your add button that will call a JQuery $.post(url, callback) function.
In that callback function, you can have it update the corresponding DIV (that you defined in #1) with a 'remove' link. i.e if you identify the DIV by ID, you can retrieve it via $('#id') and then update that object.
The same idea can apply with the 'remove' link that you add.
So, generally...
<button id="add">Add</button>
<div id="links"> ...</div>
<script>
$('#add').click(function() {
$.post('your url',
function(data) {
var links = $('#links');
// update your links with 'remove' button, etc
}
);
});
</script>
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
I'm setting the URL after the hashmark with a jquery click event. The URL is getting set properly but when I use the browsers back button it doesn't take me to the previous page.
Before my click event the URL looks like this:
http://example.com/menu.php?home
My click event looks like this:
$('#visits').click(function() {
$('#main').load("visits.php?type=1&view=1", function () {
location.href = "#visits";
});
return false;
});
My URL now looks like this:
http://example.com/menu.php?home#visits
It seems as though menu.php doesn't get called with the browsers back button.
Any idea what I'm missing?
You could code something like this:
var _hash = '';
function myHashChangeCallback(hash) {
// handle hash change
// load some page using ajax, etc
}
function hashCheck() {
var hash = window.location.hash;
if (hash != _hash) {
_hash = hash;
myHashChangeCallback(hash);
}
}
setInterval(hashCheck, 100);
Use the onhashchange event of the window, to check if the hash changes. This is getting called when you hit the back Button of your browser.
$(window).bind('hashchange',function() {
if (location.hash != '#visits') {
//Code to revert the changes on the page
}
}
Older versions of IE don't support hashchange, so you have to cheat by using setInterval to poll a few times a second and check if it's changed.
if($.browser.msie && $.browser.version < 7){
setInterval(function(){
if(window.location.hash != window.lastHash){
hashChangeHandler();
window.lastHash = window.location.hash;
}
}, 100);
}
else{
$(window).bind('hashchange',function() {
if (location.hash != '#visits') {
hashChangeHandler();
}
}
}
I need to make a form similar to the one "shorten link" sites use. It should simply remove WWW. and echo the result so I later add my code around it.
For example if the user types www.pizza.com/blablabla clicking on input should display: pizza.com/blablabla
Thanks
You can do lots of fancy stuff with regular expressions. For example, this javascript will do what you want:
// Event for enter click
$("#url").keypress(
function(e) {
if(e.keyCode == 13) {
$("#output").html(cleanURL($("#url").val()));
}
}
);
// Event for button click
$("#submit").click(
function() {
$("#output").html(cleanURL($("#url").val()));
}
);
// Function to clean url
function cleanURL(url)
{
if(url.match(/http:\/\//))
{
url = url.substring(7);
}
if(url.match(/^www\./))
{
url = url.substring(4);
}
return url;
}
Works on enter click, button click and removes both http:// and www
You can try it out here: http://jsfiddle.net/Codemonkey/ydwAb/1/