Updating a value on click once when multiple element exists - javascript

I have a fiddle here http://jsfiddle.net/wMUTg/56/ that I'm trying to update a value by one when a button is clicked, only once. Similar to the 'like' functionality on facebook. I've got that working, however if I have multiple elements that are similar only one is updating. I know I have to use the $this functionality but I'm struggling to find where to put it. Also, does anyone know if this can be achieved without an input field? Ideally I'd like it to be in a span tag but I needed the input to get the value first.
$(".red #update").one("click", function() {
var val;
val = $('#counter').val();
val++;
$('#counter').prop('value',val );
});

#CertainPerformance, is right. You should use class instead of same multiple IDs in one DOM.
However here is your solution:
Used $(this).prev('#counter') as selector to refer relevant element.
$(".red #update").one("click", function() {
var val;
val = $(this).prev('#counter').val();
val++;
$(this).prev('#counter').prop('value',val );
});

Related

Store jQuery in a variable

I've got an FAQ page I'm building. Next to the question, there is a plus sign to expand the content. On click, I've added the class active, but there are many questions, and I don't want to repeat the same jQuery snippet for each question. I've figured out how to find the parent ID but I'm having trouble storing it in an variable to reuse in the jQuery script.
What I want to be able to do:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$('element .expand').toggleClass('active')
})
Is there a way to do this? I get undefined when I do this:
$('.expand').click(function(){
console.log(element)
});
You can use the find() function to locate children of a selected element:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$("#" + element).find('.expand').toggleClass('active')
});
However, looking at your code, it seems like you just want to toggle the "active" class of the clicked element. If that is the case, you can do this much more simply without a variable at all:
$('.expand').click(function(){
$(this).toggleClass('active')
});

removeClass Not working on dynamically Created CheckBox on GoogleMap

I showed 5 markers on google map with infowindow. Each contents has checkbox.
I am adding div contents to Compare list when user click on each.There is Remove button to remove them back.I want to UnCheck it on remove.Complete code is here JSFIDDLE
I have two issues now
On Each check i want to keep their ids in hidden fields,I tried this code which is not working
var value = [];
var count = 0;
$('#map-canvas input:checked').each(function() {
value+=$(this).attr('value')+',';
count++;
});
$('#cmpIds').val(value);
On Remove button click I want to uncheck each checkbox and hide it.I have this function which is not working for each popup onclick="removeAdd(this);"
There are two main issues with your code. Firstly, you are constructing an array incorrectly. In order to construct an array based on the checkbox value, you do not construct it literally (i.e. by inserting , between values). Instead, you use .push(), i.e.:
var value = [],
count = 0;
$('#map-canvas input:checked').each(function() {
value.push($(this).attr('value'));
count++;
});
$('#cmpIds').val(value);
Secondly, you should also avoid using inline JS for the delete function. Use .on() if you want to bind event handlers to dynamically added elements. Therefore, for the injected markup, simply remove the inline JS reference:
<a class="text-success">Remove</a>
Also, I have used $(this).closest('.media') to find the .parent().parent(), as it is more verbose. You can cache this selector so jQuery wouldn't have to comb through the DOM repeatedly within the same click event:
$(document).on('click', '.text-success', function() {
var $parent = $(this).closest('.media');
// Remove listing
$parent.remove();
// Uncheck associated textbox
var parentID = $parent.attr('id'),
checkboxID = parentID.split('_');
$('#'+checkboxID).prop('checked', false);
});
Working fiddle here: http://jsfiddle.net/teddyrised/z0Lkbmyh/4/
Additional notes: your value array and count variable are reset every time a change event is registered on your checkbox. I suspect, although I cannot confirm, that this is not the desired behavior — I believe you want to keep track of checked properties on the go. Therefore, you should declare both of them outside the .change() handler:
var value = [],
count = 0;
$(document).on('change', '.wrapmap-gist input:checkbox', function() {
$('#map-canvas input:checked').each(function() {
value.push($(this).attr('value'));
count++;
});
$('#cmpIds').val(value);
// Rest of your code here
});
$(document).on('click', '#button-id', function() {
// your code here
});

How do you find out if any select menu have been put into focus?

I am trying to limit query calls using a function that will place edited items into an object then pass them to a PHP script to update only the edited information. In this case I am using jQuery's change() function, however I can not find a pseudo selector for select menu's (ie. :input, input:checkbox). The only idea I have left is to add a class to all the select menu's and go from there like so:
$(":input, input:checkbox, .selectedMenu").change(function() {
//Some Code here
});
I have checked all over and cannot find any information on this. Would this be the best way or is there an alternative?
Problem: How can you find out if any select menu has been put into focus using a pseudo selector or anything on those lines?
Select is its own tag. You don't need a psuedoselector:
$("select").change(function () { ... });
I think that all you want to do is use the select box that was changed, in this case you can do this
$(":input, input:checkbox, .selectedMenu").change(function() {
var $el = $(this);
alert($el.val());
});
you can add a focused class:
$(":input, input:checkbox, .selectedMenu").change(function() {
$(".focused").removeClass("focused");
this.addClass("focused");
//Some Code here
});
I would put this as a comment but I'm not allowed to... Maybe I misunderstood your question, but what about:
$(":input, input:checkbox, select")

Jquery, getting 'this' selector from a conditional

I have several elements on my page with the 'checkbox' class. When clicked, a corresponding checkbox input is checked. However, I need to have JQuery check if the checkbox element is active when the page first loads, and check the checkbox input accordingly at that time.
Since there are multiple 'checkbox' classes on my page, I used the 'this' selector previously and it worked fine, however I do not know how to make it do this with my conditional on page load without the .click action that I used before. Here's what I'm trying to make work:
if($('.checkbox').hasClass('active')) {
$('[name="'+$(this).attr('rel')+'"]').prop('checked', true);
}
Obviously the 'this' selector doesn't know what I'm referring to. Is there a better way of doing this? Since it's checking through a bunch of elements and not just one I'm stumped. Thanks!
You can only use this within the context of a jQuery function, so in this scope it's not going to refer to any .checkbox.
You can use .each instead:
$('.checkbox.active').each(function() {
// In this context, this refers to the DOM element represented by .checkbox.active
$('[name="'+this.rel+'"]').prop('checked', true);
});
The each function may suit your needs:
$('.checkbox').each(function() {
var $this = $(this);
if ($this.hasClass('active')) {
$('[name="'+$this.attr('rel')+'"]').prop('checked', true);
}
});
If the checkboxes must be unchecked when the active class is absent, then:
$('.checkbox').each(function() {
var $this = $(this);
$('[name="'+$this.attr('rel')+'"]').prop('checked', $this.hasClass('active'));
});

Javascript/jQuery - How do I obtain name of the class of clicked element?

I googled and googled and I concluded that it's very hard to get answer on my own.
I am trying to use jquery or JavaScript to get a property of clicked element. I can use "this.hash" for example - it returns hash value I presume.
Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?
jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.
JavaScript documentation? - is there even one comprehensive one? again please a link.
DOM documentation? - the one on W3C or where (link appreciated).
And what is this.hash? - DOM JavaScript or jQuery?
In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:
Example: http://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.
There are jQuery methods that do this as well, like .attr().
Example: http://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.
This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.
jQuery
​$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});​​​​
Javascript
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}​
Try it out
http://jsfiddle.net/M2Wvp/
Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
this supports on clicking anywhere of the page. if the element you clicked doesn't have a class name, it will return null or empty string.
$('#ele').click(function() {
alert($(this).attr('class'));
});
And here are all of the attribute functions.
http://api.jquery.com/category/attributes/
You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.
Then you can iterate all of them and find the one you want.
window.onclick = function(e) {
var classList = e.srcElement.className.split(/\s+/);
for (i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
}
jQuery does not really help you here but if you must
$(document).click(function(){
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item==='someClass') {
//do something
}
});
});
There's a way to do this without coding. Just open the console of your browser (f12?) and go to element you want. After that, hover or click the item you want to track.
Every change done on the DOM will be for a few seconds marked (or lightened) as another color on the console. (Watch the screen capture)
On the example, each time I hover a "colorItem", the 'div' parent and the "colorItem" class appears lightened. So in this case the clicked class will be 'swiper-model-watch' or 'swiper-container' (class of the lightened div)

Categories