"Add to Favorite / Remove" - Ajax not working - javascript

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');

Related

why is button toggle not working with class?

When I change my button toggle from ID-Name to Class-Name, the function is not working anymore. Does anyone know why?
I need a class since this button is multiple times on the page and loads in separately via css and sliders. The function and content is still the same.
$(document).ready(function(){
$('.infoBtn').on('click', function () {
var text=$('.infoBtn').text();
if(text === "info"){
$(this).html('close');
} else{
$(this).text('info');
}
});
});
The issue is your use of selector inside the click event:
$('.infoBtn').text();
Pointy:
Your code should use $(this), not $('.infoBtn') inside the handler.
What you have now will get the text only from the first one on the
page.
If you change that to $(this), it should work as required:
$(this).text();
$(document).ready(function(){
$('.infoBtn').on('click', function(){
//REM: Use $(this) and not $('.infoBtn')!
let text = $(this).text();
$(this).text((text === 'info') ? 'close' : 'info')
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class = 'infoBtn'>initial</button>
<button class = 'infoBtn'>initial</button>

How to get onclick event for jQuery Chosen drodpown listbox?

Hi I am developing one jquery application. I ghave one dropdownbox with jquery choosen.
$(function () {
$(".limitedNumbSelect").chosen();
});
This is my dropdown and binding values from database.
<b>Awarded To:</b> <asp:ListBox ID="ddlvendorss" runat="server" SelectionMode="Multiple" class="limitedNumbSelect"></asp:ListBox>
I am trying to get click event for the above dropdown. As soon as i click on the dropodwn i want to fire a alert before loading any options.
$('#ddlvendorss').click(function (e) {
alert("I am going crazy");
});
In the below code checkedValues arrays contains some values(values present in dropdownlistbox). As soon as i click on the drodpown i ant to hide those values. But below code doesnt work.
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
$(".limitedNumbSelect option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
Above code does not work. May I get some advise on this? Any help would be appreciated. Thank you.
Chosen hides the select element, thus you are not actually clicking the element. However you can use chosen:showing_dropdown event
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
alert('No need to go crazy');;
});
Fiddle
If you want to hide options, You can use
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
//Find options and hide
$(this).find('option:lt(3)').hide();
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
Fiddle
As per OP's code
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
//Get all options
var options = $(this).find('option');
//Show all
options.show();
//Hide based on condtion
options.filter(function () {
return checkedValues.indexOf($(this).val()) === -1;
});
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));

Jquery: After removing content with a click how do I reset the button with the one I triggered the add function?

So I have this function where I add content on click to a "Favorites page", but when I click the button to remove it from the Favorites tab it removes the content but the button on the main page does not reset, the question is, how do I reset the button to it's original state after clicking the "Unfavorite" button?
https://jsfiddle.net/yjL7L6g7/3/
$(document).ready(function() {
$('button').click(function() {
if ($(this).html() == 'Favorite') {
var $favorited = $(this).parent().parent().parent().clone();
$(this).html('Favorited');
$favorited.find('button').html('Unfavorite');
$($favorited).click(function() {
$(this).remove();
});
$('#favorites').append($favorited);
}
});
});
And my second question related to this code is, how do I add a button to be on the same row with the content that is being added to the "Favorites"? I tried a simple .append(); but it did not suffice as the button got placed in a new row, will .css() suffice?
The questions might be stupid but I am still on my first steps in learning jquery
I'd avoid cloning if possible because there are simpler ways to do what you're trying to do. The code below will create a new button and add it to your favorites page. It will also attach an event to the Remove button to change the text of the Favorited button as well as remove itself after being clicked.
$(document).ready(function () {
$('button').click(function () {
if ($(this).html() == 'Favorite') {
var that = this;
$(this).html('Favorited');
var id = $(this).attr('id');
$('#favorites').append('<button id="' + id + 'Remove" class="ui-btn">Remove</button>');
$('#' + id + 'Remove').click(function () {
$(this).remove();
$(that).html('Favorite');
});
}
});
});
As for your second question, there is CSS that allows elements to live on the same line. For example, if you have two buttons that you want on the same line, it would look something like this:
<button style="display: inline;">Button1</button>
<button style="display: inline;">Button2</button>
Let me know if you have any questions.

get clicked element ID or Name jquery or javascript

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
};

Read id with jquery and apply action to corresponding div

I want a certain button to show a certain div. Now I need to update my javascript for every new button & div. As this will be connected to a cms, for every post it needs to work automatically. How can I read the id/class from the button dynamically to apply an action to the corresponding div?
Way of thinking:
button_xxx opens div with id xxx
button_xxx_close closes it
Here's the html:
Button 001
Button 002
...
Button 099
<div id="001">
<p>CLOSE</p>
<p>Content</p>
</div>
<div id="002">
<p>CLOSE</p>
<p>Content</p>
</div>
<div id="099">
<p>CLOSE</p>
<p>Content</p>
</div>
And the javascript:
$(document).ready(function() {
// SHOWS DIV
$('#button_001').on('click', function(){
$('#001').removeClass('movedown');
$('#001').addClass('moveup');
});
$('#button_002').on('click', function(){
$('#002').removeClass('movedown');
$('#002').addClass('moveup');
});
$('#button_099').on('click', function(){
$('#099').removeClass('movedown');
$('#099').addClass('moveup');
});
// HIDES DIV
$('.button_001_close').on('click', function(){
$('#001').removeClass('moveup');
$('#001').addClass('movedown');
});
$('.button_002_close').on('click', function(){
$('#002').removeClass('moveup');
$('#002').addClass('movedown');
});
$('.button_099_close').on('click', function(){
$('#099').removeClass('moveup');
$('#099').addClass('movedown');
});
});
You can reduce your code using startswith attribute selector in jquery
$("a[id^=button_]").click(function () {
var id = this.id.split("_")[1];
$("#" + id).removeClass("movedown").addClass("mouseup");
});
$('[class^=button_]').on('click', function () {
var id = $(this).attr("class").split("_")[1];
$("#" + id).removeClass("mouseup").addClass("movedown");
});
First snippet will select all anchor elemets with id starts with button_ and bind click event to them.
Second snippet will select all elemets with class starts with button_ and bind click event to them.
Note
If your elements are created dynamically, use the below code
$(document).on("click", "a[id^=button_]", function () {
var id = this.id.split("_")[1];
$("#" + id).removeClass("movedown").addClass("mouseup");
});
$(document).on('click', '[class^=button_]', function () {
var id = $(this).attr("class").split("_")[1];
$("#" + id).removeClass("mouseup").addClass("movedown");
});
Edit
$('[class^=button_]').on('click', function () {
// var id = this.id.split("_")[1]; <-- changedd this line
var id = $(this).attr("class").split("_")[1];
$("#" + id).removeClass("mouseup").addClass("movedown");
});
I changed the line, Because that element doesnt have id. So you should pick the classname instead.
You can use $(this).attr("class") to get the current element's class name. Then split the classname to extract the div id
Simply with toggleClass
$("a[id^=button_] , [class^=button_]").click(function () {
var id = this.id.split("_")[1];
$("#" + id).toggleClass("movedown mouseup");
});
Try with this:
$(document).ready(function() {
// SHOWS DIV
var elem = '';
$('a[id*="button_"]').on('click', function(){
elem = this.id.split('_')[1];
$('#'+elem).toggleClass('movedown moveup');
});
// HIDES DIV
$('.button_'+elem+'_close').on('click', function(){
$('#'+elem).toggleClass('movedown moveup');
});
});
You could do this without the need for regular expressions with a small change to your html
Button 001
<div id="001">
<p>CLOSE</p>
<p>Content</p>
</div>
and then add click handlers for both
$('.button_open_div').on('click', function(ev){
$('#'+$(this).data('divid')).removeClass('movedown').addClass('moveup');
});
$('.button_close_div').on('click', function(){
$('#'+$(this).data('divid')).removeClass('moveup').addClass('movedown');
});
or a toggle function
$('.button_open_div, .button_close_div').on('click', function(ev){
$('#'+$(this).data('divid')).toggleClass('movedown moveup');
});
example: http://jsfiddle.net/XXE2R/

Categories