I'm aware that this issue was addressed many times, that's why I read most of the topics on this problem that were already opened on Stack Overflow but none of the suggestions have helped me.
I have a list of div elements, each containing a hyperlink and a span element with additional information. The span elements are initially hidden and they need to be toggled whenever the sibling anchor element is clicked.
<div class="politician">
<a href="">
Антонијо Милошоски
</a>
<span class="additional" style="display: none">
2013ВМРО-ДПМНЕ1997-1
</span>
</div>
<div class="politician">
<a href="">
Силвана Бонева
</a>
<span class="additional" style="display: none">
2013ВМРО-ДПМНЕ1991-1
</span>
</div>
Here's the jQuery code I have written to handle the toggling of the hidden elements:
$('.politician a').click(function (e) {
e.preventDefault();
var $this = $(this).parent().find('span');
$(".politician span").not($this).hide();
$this.toggle();
});
My problem was already stated in the title. I'm expecting the hidden elements to be shown, but instead the page gets refreshed. I guess there has to be something wrong with the way I'm using the preventDefault() method.
EDIT
Here is the piece of code that generates the div.politician elements.
function populateList(politicians) {
var politlist = $("#list").html("");
for (var i in politicians) {
var person = politicians[i];
var politinfo = "<div class=\"politician\">" + person.name + " " + person.surname + "<span class=\"additional\" style=\"display: none\">" + person.lastserved;
for (var j in person.member)
{
var membership = person.member[j]
politinfo += membership.party + membership.enrol + membership.leave;
}
politinfo += "</span></div>";
$(politinfo).appendTo(politlist);
}
}
Since you're adding elements dynamically, you need to use event delegation:
$('#list').on('click', '.politician a', function(e) {
// your code
});
This is happending because your html is not loaded when you add click event listener to it.
Wrap your code in document.ready function, like this:
$(function(){
$('.politician a').click(function (e) {
var $this = $(this).parent().find('span');
$(".politician span").not($this).hide();
$(this).toggle();
e.preventDefault();
});
});
http://plnkr.co/edit/gist:1986619?p=preview
Related
I'm pretty new to the world of jQuery and having some difficulty with a cart feature I am trying to add to a website.
I have created a function to add an element (based on its id) to the cart. This works fine. However when I try to reverse it (say someone clicks on the cart icon again to remove it) the cart count increases more and the class doesn't change back.
You will see in my code I am changing the classes for visual representation (unselected = svg with no fill & selected = svg with fill).
I have tried toggling the class, removing and adding the class but I can't think of much more. Any help would be greatly appreciated!
$(document).ready(function() {
var cart = [];
$("a.addToCart").click(function(event) {
var pressedId = event.target.id;
$("#cart_button").removeClass("hidden");
$("#" + pressedId).removeClass("addToCart");
$("#" + pressedId).addClass("addedToCart");
cart.push(pressedId)
$('.cart--counter').html(cart.length);
});
});
$(document).ready(function() {
$("a.addedToCart").click(function(event) {
var unpressedId = event.target.id;
$("#" + unpressedId).addClass("addToCart");
$("#" + unpressedId).removeClass("addedToCart");
cart.splice( $.inArray(unpressedID,cart) ,1 );
$('.cart--counter').html(cart.length);
});
});
Here is an example of the HTML with a class and ID.
<a id="12" class="addToCart">
Again, for clarification: the class changes appropriately from "addToCart" to "addedToCart" but is not reversible & the array is successfully updated with appropriate "ID" but can not be removed again.
Your issue is that when you add your event handlers, there are no elements with class addedToCart, so no event handlers get assigned. You need to use a delegated event handler instead:
var cart = [];
$(document).ready(function() {
$(document).on('click', "a.addToCart", function(event) {
var pressedId = event.target.id;
$("#cart_button").removeClass("hidden");
$("#" + pressedId).removeClass("addToCart");
$("#" + pressedId).addClass("addedToCart");
cart.push(pressedId)
$('.cart--counter').html(cart.length);
$('#cart').html(cart.toString());
});
});
$(document).ready(function() {
$(document).on('click', "a.addedToCart", function(event) {
var unpressedId = event.target.id;
$("#" + unpressedId).addClass("addToCart");
$("#" + unpressedId).removeClass("addedToCart");
cart.splice($.inArray(unpressedId, cart), 1);
$('.cart--counter').html(cart.length);
$('#cart').html(cart.toString());
});
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="12" class="addToCart">Item 12</a><br />
<a id="13" class="addToCart">Item 13</a>
<div class="cart--counter">**</div>
<br />
<div id="cart"></div>
<br />
<div id="cart_button" class="hidden">cart button</div>
I have a list in JQuery that's called additionalInfo, which is filled in using this JQuery function:
$('#append').on('click', function () {
//check if the following area is valid before moving on, check the jquery validation library
var text = $('#new-email').val();
var li = '<li>' + text + 'input type="hidden" name="additionalInfo" value="'+text+'"/> </li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
The point of the function is not only to store the info in a list that can be used later, but also to render a <li> with the info text in it. Right now I have another button on each <li> that when pressed, makes the li vanish, but I also need to add code to it that completely removes the info text from the additionalInfo list. This is the code I have for that method so far:
$('#removeEmail').on('click', 'li>.remove-btn', function (event){
$(event.currentTarget).closest('li').remove();
});
How can I get the segment of info text out of the li and then remove it from additionalInfo?
You have few problems. First of all when you create the new items, your markup is not correct. You were missing the opening bracket of input tag. Also i changed the code for delete so that it listens for the click event on any item with class remove-btn under the li element. This should delete the item when you click the remove link inside the li.
$(function(){
$('#append').on('click', function () {
var text = $('#new-email').val();
var li = '<li>' + text + '<input type="hidden" name="additionalInfo"
value="'+text+'"/>
<a href="#" class="remove-btn" >remove</a></li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
$(document).on('click', 'li>.remove-btn', function (event){
var _this =$(this);
_this.closest('li').remove();
});
});
Here is a working jsfiddle
I'm creating anchor tags dynamically and I want them to call a function that has a set parameter for each one.
Example:
<div class="AnchorHolder">
<a onclick="someFunction(1)">someText</a>
<a onclick="someFunction(2)">someText</a>
<a onclick="someFunction(3)">someText</a>
</div>
I've tried
$("#AnchorHolder").append("<a>" + someText + "</a>").click(function (e) {
someFunction(someIntVariable);
});
but instead connects all of the anchors to the IntVariables current value, whereas I wanted the previous ones.
How can I accomplish this?
Well, I would suggest you to try data attributes. As far I know they are made for that porpuse. See:
$("#AnchorHolder").append("<a href='#' data-myvar='" + someIntVariable + "'>" + someText + "</a>");
// Keep the event binding out of any loop, considering the code above will be called more than once...
$("#AnchorHolder").on('click', 'a', function (e) {
alert($(this).data("myvar"));
});
Fiddle
If you just want the click on the new element, tack it onto that element, and not on the #AnchorHolder element:
var newAnchor = $("<a>" + someText + "</a>").click(function (e) {
someFunction(someIntVariable);
});
$("#AnchorHolder").append(newAnchor);
Or, alternatively to get each <a> to call the someFunction with their postion-inside-the-div:
$("#AnchorHolder a").each(function(idx) {
var a = $(this);
a.click(function() { someFunction(idx); });
});
You can always create a html element as following
$('<a>').attr("onclick","fun('hi')").html('Some text').appendTo("#AnchorHolder");
Hope this helps
I'm trying to automate a click when visting a website. This is the HTML I'm looking at.
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
when I select the size, say for instance size 8, the class= tag turns to "box active" like so,
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box active">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
How can I go loop through the class and select a desired size? Also, I was just tinkering around and noticed that I had a hard time simulating a click on the add to cart and other buttons. For the add to cart the HTML looks like this,
<div class="add_to_cart">
<div class="add_to_cart_left">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
<img id="add_to_bag_btn_processing" alt="" src="/images/add_to_bag_processing.gif"></img>
</div>
</div>
Is this the correct chunk of HTML I should be looking at for a simulation of a click?
Since it's Christmas and you sounded excited to see jQuery in action I created a fiddle for you. Here is a sample of what you (could) want using jQuery: http://jsfiddle.net/akkJ5/2/
The code for selecting sizes and twiddling active classes is as follows:
var selectedSize = '';
$(".box").click(function(){
$(".box").removeClass('active');
$(this).addClass('active');
selectedSize = $(this).html();
$("#messages").html(selectedSize +" was selected");
});
In it I create an event listener for clicks on all box class elements. Since only one should be active I remove the active class from all box class elements then add active to the clicked box. I save the innerHTML of the selected link as selectedSize, and write it to an element for display sake.
In terms of simulating a click on a button you could do something like this:
$(".add_to_cart").click(function(){
alert('cart clicked');
});
$(".add_to_cart").trigger('click');
Updated
To attach event to all the classed you can do
var selectedvalue = '';
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
d.onclick = function (e) {
selectedvalue = this.text;
this.className = this.className + " active";
}
}
Check http://jsfiddle.net/raunakkathuria/Nv8t2/2/
To navigate through classes and add your class to the link that has same value
JS
var value = 8;
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
if(d.text == value) {
d.className = d.className + " active";
}
}
To simulate the click handler for the add to cart you can enclose them to
<a href="javascript:void(0)" onclick="myJsFunc();">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
</a>
If you want to send it some link update this href="javascript:void(0)" onclick="myJsFunc();" to href="your_link"
Check http://jsfiddle.net/raunakkathuria/Nv8t2/1/
I append the following content using jQuery to create a lightbox style popup that loads loads content using AJAX:
<div id="framebox-overlay">
<div id="framebox-wrapper">
<div id="framebox-nav-wrapper">
Previous
Next
</div>
<section id="framebox-content">
<!--AJAX to insert #single-project-wrapper content here-->
</section>
<div id="framebox-close">
<p>Click to close</p>
</div>
</div>
</div>
I am trying to get the appended next/previous links to work (.framebox-next and .framebox-prev as shown above), however the links are not triggering properly:
jQuery(document).ready(function(){
$('.framebox-trigger').click(function(e){
// Code that appends lightbox HTML and loads initial AJAX content goes here
});
// Code that isn't working:
$('body').on('click', 'a .framebox-next', function(e) {
e.preventDefault();
//remove and add selected class
var next = $('#portfolio-wrapper li.current-link').next('li > a');
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(next).addClass('current-link');
//fade out and fade in
var nexthref = $('#portfolio-wrapper li.current-link a').attr('href');
$('#single-page-wrapper').fadeOut('slow', function(){
var current = $('#portfolio-wrapper li.current-link a');
$(this).load(nexthref + " #single-page-wrapper", function(){
$(this).fadeIn('fast');
});
});
return false;
});
});
This last bit of code is not doing anything to the appended link .framebox-next. I have looked for other answers, and it seems that the .on() method should be effecting appended content.
Any help or input would be great.
Your selector is wrong for .framebox-next. You have a space between a and .framebox-next which would mean .framebox-next needs to be a child of the a element.
Use this selector instead:
$('body').on('click', 'a.framebox-next', function(e) {
...
}