This piece of code is somehow not working and I dont know why, im not good at php nor js just trying to make some website.
The part that is not working is this favorite button, it works like it has to work but it does not switch to "unfavorite" after click, it only works if u refresh the browser.
This is the html that is generated by the php file:
<a class="btn" id="fav28" title="Add to Favorites" href="javascript:;" onclick="AddFav('28','fav','add')">
<i class="icon-heart"></i>
</a>
And this is the js function:
function AddFav(id, dothis, dowhat) {
$.ajax({
url: ("/process.php?do="+dothis+"&id="+id+"&action="+dowhat)
});
if(dowhat == "add"){
document.getElementById(dothis+id).className = 'disabled';
document.getElementById(dothis+id).onclick = another_function
document.getElementById(dothis+id).title = 'Remove from Favorites';
}else if(dowhat == "remove"){
document.getElementById(dothis+id).className = 'btn';
document.getElementById(dothis+id).title = 'Add to Favorites';
}
}
I have tried the
document.getElementById(dothis+id).onClick = "AddFav(28,id,remove)";
but nothing happens with this, it simply does not change the onclick
what it has to do is to change the "onclick" event from
onclick="AddFav('28','fav','add')"
to
onclick="AddFav('28','fav','remove')"
Thanks in advance.
I might be wrong, but I don't think you can override the "onclick" attribute in HTML with JavaScript. The "onclick" will always run, even if you try to change it or add another click handler in JavaScript.
Your best solution for this problem would be to remove the "onclick" attribute, and setup the click handler with JavaScript instead.
Your PHP should generate this:
<a class="btn" id="fav28" title="Add to Favorites" href="javascript:;">
<i class="icon-heart"></i>
</a>
Note that "onclick" was removed. In your JS you should have something like this:
var favButton = document.getElementById('fav28');
favButton.addEventListener( 'click', function(){
// Note: `this` is referring to the button you clicked
if( this.className === 'disabled' ) {
// Run AddFav as if you were removing the favourite
this.className = 'btn';
this.title = 'Add to Favourites';
} else {
// Run AddFav as if you were adding the favourite
this.className = 'disabled'
this.title = 'Remove from Favourites';
}
});
Then your AddFav method only has to worry about adding or removing the favourite, which in your case looks like it's only an Ajax call. You can remove all logic from AddFav that changes the button and call it where I've commented out.
You says you tried
document.getElementById(dothis+id).onClick = "AddFav(28,id,remove)";
but the syntax is wrong because you don't have qoutes for id and remove (that are strings) like:
AddFav(28,'id','remove')";
I see you use jquery.. if you use jquery why not enjoy all features. your function can became:
function AddFav(id, dothis, dowhat) {
$.ajax({
url: ("/process.php?do="+dothis+"&id="+id+"&action="+dowhat)
});
if(dowhat == "add"){
$('#' + dothis + id).addClass('disabled'); // add class disabled
$('#' + dothis + id).removeClass('btn'); // remove class btn if exist
$('#' + dothis +id).on( "click", function() {
AddFav(id,'fav','remove'); // attach new function AddFav for click event
});
$('#' + dothis +id).attr('title','Remove from Favorites');
}
else if(dowhat == "remove"){
$('#' + dothis + id).addClass('btn'); // add class btn
$('#' + dothis + id).removeClass('disabled'); // remove class btn if exists
$('#' + dothis +id).attr('title','Add to Favorites');
}
}
If you want to do it in pure javascript than the changing the onclick attribute to another function is done like this:
document.getElementById(dothis+id).onclick = function { AddFav(id,'fav','remove') };
Like this:
http://jsfiddle.net/4ku75/
It might be a scope problem: the AddFav function might not be defined in the global scope.
Try replacing
function AddFav(id, dothis, dowhat) {
with
window.AddFav = function(id, dothis, dowhat) {
This way, your AddFav function is global, and you might call it using window.AddFav or simply AddFav
Related
I want to create a "Add to favorite" & "Remove from favorite".
When I add the favorite, I change the ID of the DIV for remove.
I can successfully add to favorite but I can't undo.
This code for add
$('#addToFavoriteButton').click(function (event) {
var ItemID = $('#addToFavoriteButton').data('itemid');
event.preventDefault();
$.post('/system/ajax.php', {
AddFavID: ItemID
}, function (response) {
document['getElementById']('addToFavorite').id = 'RemoveFavoriteButton';
});
});
This code for remove
$('#RemoveFavoriteButton').click(function (event) {
var ItemID = $('#RemoveFavoriteButton').data('itemid');
event.preventDefault();
$.post('/system/ajax.php', {
RemoveFavbidID: ItemID
}, function (response) {
document['getElementById']('RemoveFavoriteButton').id = 'addToFavoriteButton';
});
});
Where am I wrong?
The main problem with your code is that you are assigning an event handler to a button and then changing the ID of that button, expecting it to trigger different code when it is clicked. That is wrong.
If you change the ID of an element it will still trigger the event handler that you originally assigned to it. See this example...
$("#button1").on("click", function() {
alert("you clicked button 1 - my id is " + this.id);
});
$("#button2").on("click", function() {
alert("you clicked button 2");
});
// change the ID of #button1 to #button2
$("#button1").attr("id", "button2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1">button 1</button><br/>
<button id="button2">button 2</button><br/>
What makes more sense is to have a button to add a favourite, and a button to remove a favourite. You just hide the remove button until add is clicked, and vice-versa.
Like this...
var $add = $("#addFavourite");
var $remove = $("#removeFavourite");
$add.on("click", function() {
$add.hide();
$remove.show();
var itemId = $add.data("item-id");
alert("adding item " + itemId);
// do your AJAX stuff to add the favourite here
});
$remove.on("click", function() {
$add.show();
$remove.hide();
var itemId = $add.data("item-id");
alert("removing item " + itemId);
// do your AJAX stuff to remove the favourite here
});
#removeFavourite {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="addFavourite" data-item-id="123">add favourite</button>
<button id="removeFavourite" data-item-id="123">remove favourite</button>
I Suggested that you change the class instead of the id, since the id must be unique.
Or you can always use HTML5 data attribute, which you can use for both CSS styling (using attribute selector) and JS use (with dataset or jQuery's .data () method). see
Example:
HTML
<div id="el" data-test="data"></div>
vanilla javascript
var el = document.getElementById('el');
el.dataset.test // 'data'
by the way how you get the id is wrong -
document['getElementById']('RemoveFavoriteButton').id
You must use
vanilla javascript
document.getElementById('RemoveFavoriteButton').id;
jQuery
$('#RemoveFavoriteButton')attr('id');
I'm trying to make a HTML button trigger a function called switch_user, but every time I try clicking it, the console says switch_user is not a function.
This is the button:
<input type="button" class="btn btn-login" onclick="switch_user()" id="switch_user" value="{%trans%}Switch{%endtrans%}">
At the bottom of the page I have a script tag, with this function in it:
function switch_user(){
$("#switch-success, #switch-error").addClass("hide");
$.getJSON("/api/business/admin/swaproles?module="+$("#module").val()+"&user_from="+$("#user_from").val()+"&user_to="+$("#user_to").val(), function(data){
if(data) {
if(data["error"]){
$("#switch-error").html( "{%trans%}There was an error{%endtrans%}: " + data["error"]);
$("#switch-error").removeClass("hide");
}
else {
$("#switch-success").html("{%trans%}User was switched successfully{%endtrans%}");
$("#switch-success").removeClass("hide");
}
if(data["success"] == "ok") {
$("#elements").html("");
}
} else {
$("#switch-error").html("Critical failure - Please contact support");
$("#switch-error").removeClass("hide");
}
});
}
When I try to run the function manually from the console, it can find it just fine, but the buttons onclick refuses to recognize it. What am I doing wrong?
The issue is because the id of the element and the function name are the same. As they both exist under the window scope, there is a conflict. To fix the immediate problem either change the name of the function or the id of the element.
Better still, remove the outdated on* event attribute completely and use unobtrusive JS code to attach the event handler. As you're using jQuery already, here's how to do that:
<input type="button" class="btn btn-login" id="switch_user" value="{%trans%}Switch{%endtrans%}">
$(function() {
$('#switch_user').on('click', function() {
var $switchSuccess = $('#switch-success').addClass('hide');
var $switchError = $('#switch-error').addClass('hide');
$.getJSON("/api/business/admin/swaproles?module=" + $("#module").val() + "&user_from=" + $("#user_from").val() + "&user_to=" + $("#user_to").val(), function(data) {
if (data) {
if (data["error"]) {
$switchError.html("{%trans%}There was an error{%endtrans%}: " + data["error"]).removeClass("hide");
} else {
$switchSuccess.html("{%trans%}User was switched successfully{%endtrans%}").removeClass("hide");
}
if (data["success"] == "ok") {
$("#elements").html("");
}
} else {
$switchError.html("Critical failure - Please contact support").removeClass("hide");
}
});
})
});
Change the id . don't keep the id of element and function name same.
The JavaScript DOM bindings allow indexing by HTML id. Functions and properties share the same namespace in JavaScript. So, when an id in your HTML has the same name as one of your functions or properties, you can get logic errors that are hard to track down. While this is more of a CSS best practice issue, it’s important to remember when you can’t solve your javascript issue.
So I have multiple delete buttons on a table and each button has there own unique id. I am trying to get this value via javascript but I can't get it to work at all.
Here is a section js that is working properly and loads the correct html (this is ran for each movie):
function createRow(movie) {
movie.NewDate = new Date(movie.ReleaseDate);
return '<tr><td><img class="movieImage" src="' +
movie.ImageLink +
'" alt="' +
movie.Title +
' Image" style="width:50px;height:75px">' +
'<td>' +
movie.Title +
'</td><td>' +
movie.NewDate.toLocaleDateString("en-US") +
'</td><td><button type="button" class="removeButton" value="' + movie.DVDID + '">Delete</button></td></tr>';
}
And here is the js where I am trying to retrieve the id:
$(document)
.ready(function () {
var deleteButtons = $(".removeButton");
deleteButtons.each(function (index) {
var currentButton = $(this);
var buttonValue = currentButton.val();
currentButton.click(function () {
alert(buttonValue);
});
});
});
I found the last snippet via Click one of multiple buttons, put value in text input
Right now just getting a proper alert would be sufficient.
Have you tried this approach:
$("#tableId").on("click", ".removeButton", function(){ alert($(this).attr("value")); })
This "on" binds all the ".removeButton" elements with the given function when click is triggered.
Your javascript should look like this:
$(document).ready(function () {
var deleteButtons = $(".removeButton");
deleteButtons.on('click', function() {
alert($(this).attr('value'));
});
});
Also, since you adding these buttons dynamicly with javascript, you may need to rebind button click events after you add new row. Also binding should be done after loading button html to DOM.
Since you are creating buttons dynamically, you won't be able to reach them properly because when the javascript was initiated they didn't exist in the DOM. So in order for you to be able to find the buttons, you'll have to look at the document scope and then find which button (class) you click on, like so:
$(document).on('click', '.removeButton', function(){
console.log($(this).val())
})
See fiddle for complete example
I wants to get the ID or the name of the clicked elemt by using the following code. this code is working fine if i have only one element.
$(window).mousedown( function(e) {
mouseTracker.clickState = true;
console.log( "id:" + e.target.id + " name:" + e.target.name );
}).mouseup( function() {
mouseTracker.clickObject = '';
});
but if element is wrapped up in other elements then i am unable to get the ID. for example:
<div id="main">
<div id="subDiv">
<span id="spID" onClick="alert ('hello world')"> Click Me </span>
</div>
</div>
in the above case, it is return the ID of the main div. how can i get the clicked element.
The most secure way to do this is to add an event listener to each element. There are different ways to do that:
First as you have coded in your HTML:
var testfunction = function(event){
// Do something
};
<span id="spID" onclick="testfunction(event)"></span>
Or nicer:
<span id="spID"></span>
var element = document.getElementById('spID');
element.addEventListener('click', function(event){
// do something
})
Best regards
Dustin
I wouldn't use inline scripting if it was me. The bigger a project gets, the messier this becomes. I tend to have all my event listeners tucked away together in an init function that you can just add to as you need more event listeners:
In the head of your HTML:
<script src="global.js"></script>
<script>
$(document).ready(function() {
global.init();
});
</script>
In a separate js file, linked to your HTML (e.g. global.js):
(function (global, $, undefined) {
global.init = function() {
//bind your event listeners in here
};
})(window.global = window.global || {}, jQuery));
In terms of using this for the purposes of what you are trying to do, if you have a series of these clickable spans, I would use a class selector, so you only have to bind the click event once, otherwise if you are binding to only one span as above then you already know the ID anyway as you had to use it in the bind.
Using class:
global.init = function() {
//assuming you have applied the class "clickable-span" to all the spans you want to be clickable
$('.clickable-span').on('click', function(evt) {
var id = $(this).attr('id'),
name = $(this).attr('name');
console.log( "id:" + id + " name:" + name );
});
//add more event listeners here
};
I have a problem with this javascript code:
function MyClass() {
var id_nr = Math.ceil(Math.random() * 999999);
this.button_id = 'button_' + id_nr;
}
MyClass.prototype = {
createButton: function() {
var msg = 'Button \'' + this.button_id + '\' was clicked';
var my_button = (
'<input type="button" id="'
+ this.button_id
+ '" value="Click Me" /\>'
);
document.body.innerHTML += '<div>' + my_button + '</div>';
document.getElementById(this.button_id).onclick = function() { alert(msg); }
}
};
window.onload = function() {
var s = new MyClass();
s.createButton();
};
Yes, this current code works fine. But the problem appears when I add more than one MyClass objects:
window.onload = function() {
var s = new MyClass();
s.createButton();
var w = new MyClass();
w.createButton();
/* ...and many other buttons */
};
For some reason the onclick event will be triggered only if I click the button that was created last. And I don't know why.
One workaround could be something like this:
<input type="button" onclick="javascript:doSomeThing();" />
But unfortunately this is not the proper solution right row, because my goal is that the onclik event should be able to call another class methods as well. (Those methods are not created yet).
How can I make this code work properly? Any kind of a help is appreciated.
When you use innerHTML the contents get stripped from the DOM and then readded and parsed again, breaking any past event listener that you might have added.
If you want to do it in vanilla JS, consider using appendChild() and, also, I would suggest addEventListener(). Your code would then look like so:
var my_button = document.createElement('input');
my_button.type = 'button';
my_button.id = this.button_id;
my_button.value = 'Click me';
document.body.appendChild(my_button);
my_button.addEventListener('click', function () { alert (msg) });
Working example with vanilla Javascript
If you are up to using some jQuery, this would be so much easier to implement. Your method would look something like:
var my_button = $('<input>')
.prop('type', 'button')
.prop('id', this.button_id)
.val('Click Me')
.on('click', function () { alert(msg) } );
$('body').append(my_button)
Working example with jQuery
Or you could perhaps use the jQuery.on() method to delegate an event handler to all subsequent instances of your buttons.
Working example with delegated event handler
The use of innerHTML here seems to break the event listener "onclick".
You can avoid this by using the document.createElement method to create your html element :
var but = document.createElement("input");
but.type = "button";
but.id = this.button_id;
but.value = "Click me";
document.body.appendChild(but);
Personaly, I prefer use jQuery for manipulating the DOM tree element, as it offer really powerfull tools for this.