JS: Click one div, change another div value - javascript

I have a vote button I created that is contained within a .vote_div. 2 parts: .vote_num for the vote total, and .vote for the vote button. The page has a list of items so I need to make sure when the user clicks .vote, it changes the corresponding .vote_num + 1.
My JS function worked when the .vote actually was the total votes, but now I am seperating the two. How do I grab the right .vote_num on the .vote click?
Thanks!
<script>
$(".vote").click( function() {
var votes = $(this).attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
$(this).text(parseInt(votes) + 1);
return false;
});
</script>
<div class="vote_div">
<span class="vote_num" votes='{{host.num_votes}}'>{{host.num_votes}}</span>
<span class="vote" id="{{host.user.id}}">Vote</span>
</div>
EDIT & SOLUTION:
Got it working using $(this).parent() :
<script>
$(".vote").click( function() {
var votes = $(this).parent().find('.vote_num').attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
votes = parseInt(votes) + 1;
$(this).parent().find('.vote_num').text(votes);
return false;
});
</script>

try:
var votes = $(this).parent().find('.vote_num').attr('votes');
It goes to the parent of the clicked div then looks for an element with class vote_num then grabs the votes attributes.
#James answer should work, but this should give you a little more freedom to rearrange the two divs and add other elements so long as they share the parent.
To be even more robust you could do (note the 's' on "parents")
var votes = $(this).parents('.vote_div').find('.vote_num').attr('votes');
This will allow the elements to be nested arbitrarily deep as long as they only have a single parent with a class of `vote_div'.
See: http://api.jquery.com/parent/ , http://api.jquery.com/parents/ , and http://api.jquery.com/find/

if you have multiple class with vote, maybe you should use each()
$(".vote").each(function () {
var current = $(this);
current.click = function () {
// the rest of your function
}
})

Assuming I've understood the question correctly, and also assuming that your vote_num element is always the first element in the vote_div element:
var votes = $(this).siblings().eq(0).attr("votes");
Put this inside your click event handler will get the votes attribute from the first sibling element of the clicked element.
You can make this simpler if you are sure the element in question will always be directly before the clicked element:
var votes = $(this).prev().attr("votes");

var votes = $(this).attr('votes');
'votes' does not belong to class 'vote', it belongs to class 'vote_num'
so the line should be
var votes = $(".vote_num").attr('votes');

$('.vote').click(function(){
var $vote_num_obj = $(this).parent().find('.vote_num');
var new_vote_num = parseInt($vote_num_obj.attr('votes'))+1;
$vote_num_obj.attr('votes', new_vote_num);
$vote_num_obj.html(new_vote_num);
});
Put this script inside $('document').ready(function(){ ..here.. });
I suggest to change votes attribute of your span.vote_num to data-votes and change also the jquery attribute selector, this way it will be standard compliant.

Related

Adding and removing a class at the same time as updating a div

I am very new to JavaScript. I am trying to update a div, which works fine before the add and remove class pieces are added. The problem is when I add the class I can't seem to get it to be removed when the when the next image is clicked. I have used a remove class option, but it doesn't seem to want to work.
Any help is appreciated. Here is the code:
$('[class^="question"]').on('click', function(e) {
e.preventDefault();
var numb = this.className.replace('question', '');
$('[id^="answer"]').hide();
$('.question*').removeClass('question*selected');
$('#answer' + numb).show();
$('.question' + numb).addClass('question' + numb + 'selected');
});
Here is a link to the Fiddle I am Playing with.
Thanks.
You can keep track of your added class by defining a global variable. I created a working example in CODEPEN.
$(document).ready(function() {
var appliedClass = "container1";
var classNo = 1;
$(".buttonCon").click(function() {
if ($(".container").hasClass(appliedClass)) {
$(".container").removeClass(appliedClass);
classNo++;
if (classNo > 4) {classNo = 1;}
appliedClass = "container" + classNo;
$(".container").addClass(appliedClass);
}
});
});
I have appliedClass variable which keeps tracking of the latest added class. Every time you click on the button with .buttonCon class, this variable will be updated to the new added class. Next time, first we remove the former class. Then we added the new one. The second if statement might not be needed in your case, but in my example, I needed it to keep looping through container1 to container4 classes.
You've set yourself up with a really difficult-to-work-with class structure -- this can be a lot easier than you're making it. Give each of your "question" links the class 'question' and the unique id "question1", "question2", etc. Same for the answer nodes: class "answer" and id "answer1", "answer2" etc.
Now you can easily access all question links with $('.question') or all answers with $('.answer'), and can use the IDs to identify individual nodes as needed:
$('.question').on('click', function(e) {
e.preventDefault();
var numb = this.id.replace('question', '');
var answerNode = $('#answer'+numb);
if (answerNode.hasClass('hide')) {
// the Q they clicked on is not yet visible
$('.answer').addClass('hide'); // hide all answers
answerNode.removeClass('hide'); // show the desired one
} else {
// the Q they clicked on is already visible, so toggle it back off
answerNode.addClass('hide');
}
});
http://jsfiddle.net/647dadtj/

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Get DIV ID where Class is selected?

I currently have the following:
$(window).load(function(){
$(".boxdiv").click(function () {
$(this).toggleClass("selected");
});
});
Which perfectly does the first part of what I need. I have a fair amount of div's with the class "boxdiv" and they each have a unique ID that will identify it. What I need to happen is to have some kind of button that when pressed sends all of these div ID's with the class selected, to the next page.
Anyone got any idea of how I can do this?
Map the ID's in an array, and use $.param to create a querystring
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;});
window.location.href = '/next_page?' + $.param({ids : id_arr});
});
EDIT:
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
window.location.href = '/next_page?ids=' + qs;
});
Perhaps this is what you're looking for:
$(".button").click(function(){
var id_arr = [];
$(".boxdiv").each(function(){ // Loop through each element with that class
id_arr.push($(this).attr('id'));
}); // Loop through each element with that class
});
window.location = 'next.html/ID=' + id_arr.join(',');
The ID's should be stored in id_arr
You can loop over each div that has the class selected. You can then use attr() to access the ID names.
Javascript
var ids = [];
$.each($(".selected"), function() {
ids.push($(this).attr('id'));
});
ids = ids.join(',');
HTML
<div id="boxA"></div>
<div id="boxB" class="selected"></div>
<div id="boxC" class="selected"></div>
<div id="boxD"></div>
This should return ["boxB", "boxC"]
See: http://jsfiddle.net/B4V28/1/
All of the answers submitted are in fact correct - but I think the real issue is your expectation of what jQuery is doing for you.
jQuery will gather all of the ID's in any manner, but you will need to have a way to collect them on the next page and actually do something with them. This will all need to happen server side.
Most likely, the ideal method, based on your comment of "potentially there could be many" you would want to do a mapping (see other answers), and pass the json object to your server, where it can pass it to the next page.
With the same code -
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
alert('/next_page?ids=' + qs);
});
Here is a fiddle for you - http://jsfiddle.net/kellyjandrews/4dYfh/

jquery selection attributes

Let's say I have a sample table like this :
http://jsfiddle.net/65BkH/
Now what i want is, if there is this <button id="invite">Invite</button>. I want this button to select the "invite url" of the selected contact. If you see the jsfiddle, if you click the checkbox, it will crop all the others contacts. How could i do that?
I've tried to target the contact, but i can only get the top contact.
$('#linkedin_match tbody .match .m a').attr('href');
what i want is to target the currently selected.
FURTHER PROBLEM :
This button I'm talking about is not the table per say.
$('#btn_save').click(function(e) {
var hrefVar = $('#linkedin_match tbody .match .m').find('a').attr('href');
alert(hrefVar);
});
Now if i used that, it still searches for the first link, even though i've selected the others. So, any changes?.
You can use this:
$('#invite').on('click',function(){
var url = $this.closest('tr').find('a').prop('href');
});
To get all the checked href related with the checked inputs in a array use this:
$('#invite').on('click', function () {
var all_url = [];
$('input:checked').each(function () {
var url = $(this).closest('tr').find(' td.m a').prop('href');
all_url.push(url);
});
});
Demo here
$('.m').click(function(e){
var hrefVar = $(this).find('a').attr('href');
alert(hrefVar);
});
fiddle

Get the id of the clicked-upon div

I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:
<div class="item" id="10">hello world</div>
<div class="item_10">hello people</div>
When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.
I tried to use currentid = this.id; but it doesnt work :( !
First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).
It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.
In this case, you want to use the target property of the event to find what you clicked on. For example:
$(document.body).click(function(evt){
var clicked = evt.target;
var currentID = clicked.id || "No ID!";
$(clicked).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/
If you were registering on the specific elements instead, then this.id does work:
$('div').click(function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/1/
This is sub-ideal, however, because:
It makes many event handler registrations instead of 1, and
If additional divs are added to the document after this code is run, they will not be processed.
Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:
$(document.body).on('click','div',function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/2/
I think you're trying to do something like:
$(".item").click(function(){
var id = $(this).attr("id");
var el = $(".item_" + id);
});
Now el is your second div.
You can simply use this.id
$('div').click(function() {
var divid = this.id;
alert($('.item_'+divid).html());
});
Demo
Something like this?:
$('div').click(function() {
theId = $(this).attr('id');
//Do whatever you want with theId.
});
This can be done as:
$('.item').click(function() {
var divId = $(this).attr("id");
});

Categories