How to decide which element is being clicked in jQuery? - javascript

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.

this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});

Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});

this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;

The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});

You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

Related

Is it allowed to use jQuery $(this) selector twice in a function and in an included each loop?

I have a list, which contents x columns of data. When clicking an edit button in a row, I want to set the html content of each column of this row, which has a name attribute into an array, which key is named by the columns name attributes value.
data['id'] = '123';
data['name'] = 'John Doe';
data['city'] = 'Arlington';
For that I'm starting a click event on the edit div. Inside this function I'm working with $(this) selector for setting up an each() loop over all elements having a name attribute.
Inside this loop I'm catching the names and values of each matched element with $(this) selector again.
So, my question: although it works - is it allowed to do it this way? Using $(this) for two different things inside the same function?
Is there a different way?
Here is my working example code
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>
Is it allowed?
It works, so of course.
Depends on what you mean by "allowed".
Is it confusing - perhaps.
Can it cause problems - definitely.
(There are plenty of questions on SO with this or problems caused by this that confirm it causes problems).
Reusing variable names ('this' in this case) is common and is based on scope.
It's hard to tell if you have a bug because you actually wanted the ".edit" html or the ".edit" attr rather than the div, so you can remove that confusion by copying this to a variable:
$(document).on( "click", ".edit", function() {
var data = {};
var btn = $(this); // the button that was clicked
btn.closest('.row').children('div[name]').each(function() {
// Do you mean the div or did you really mean the clicked button?
data[$(this).attr('name')] = $(this).html();
var div = $(this); // the child div
// clearly not what is desired
// `btn` variable referring to the outer `this`
data[div.attr('name')] = btn.html();
// intention clear
data[div.attr('name')] = div.html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
In this case, it's "clear" as you wouldn't use the btn html on all the data entries (or would you? I don't know your requirements...). So "unlikely".
But it's easy to see how, in another scenario, you would want to refer to what was clicked btn==this inside the nested .each.
Try this trick:
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
var that = this; // trick here
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(that).html();// replace this = that if you want to get parent element
});
$('#result').html(JSON.stringify(data, null, 4));
});
});
there is nothing wrong, what you do is simply this
function setDivs() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
}
function docClick(){
var data = {};
$(this).closest('.row').children('div[name]').each(setDivs);
$('#result').html(JSON.stringify(data, null, 4));
}
function docReady(){
$(document).on( "click", ".edit", docClick)
}
$( document ).ready(docReady);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>

Jquery on click not working while passing data

Question is very simple but due to some reason i am not able to fix it.
Here is the a href tag that will open modal box.
<center>Apply</center>
Here is jquery to get id from data attribute.
<script type="text/javascript">
$('document').ready(function()
{
$(document).on('click', '#btn-classified', function() {
//$("#btn-classified").on("click", function () {
//$("#btn-classified").click(function() {
var myvar1 = $(this).data('data');
alert(myvar1);
});
});
</script>
For some reason i am not getting any output if i use $(document).on('click', '#btn-classified', function() {
and if i use $("#btn-classified").on("click", function () { then i am getting undefined.
To get 'data' attribute of <a> element use .attr() function of jQuery
$('document').ready(function() {
$(document).on('click', '#btn-classified', function() {
var myvar1 = $(this).attr('data'); // .attr() to get attribute of an element
alert(myvar1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' id='btn-classified' data='This an element of DOM'>Get this DATA value</a>
Your Code get undefined on event click when your call to an element which exist after of the function.
You need performance the logic of your code, on jQuery you want use
$(document).ready(function(){
//your functions with selectors of DOM
})
or use .on() function of jQuery to events.
$(document).on('click', '.mainButton', function(){
//your code
})
You have two hrefs - one says javscript:void(); the other has a hash (#) Remove one. Then you won't get undefined.
You'll want to change data to data-id in your HTML. That way you can access the data properties in your javascript like so:
$('#btn-classified').on('click', function() {
alert($(this).data('id'));
});
$(this).data('data') would actually expect data-data="<?=$someId?>" in your HTML.
As per the docs https://api.jquery.com/data/ the attribute should be data-data
if it needs to be fetched through .data function.
$('document').ready(function()
{
$(document).on('click', '#btn-classified', function() {
//$("#btn-classified").on("click", function () {
//$("#btn-classified").click(function() {
var myvar1 = $(this).data('data');
alert(myvar1);
});
});
<script data-require="jquery" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<body>
<center>
<a href="#" class="btn-home" data-data="123" data-toggle="modal" data-target="#ApplyModal" name="btn-classified" id="btn-classified" >Apply
</a>
</center>
</body>
Use .attr('data') instead of .data('data') functions because .data function is used to Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

jQuery: add click event to specific id

I have a small jquery problem:
My code is like this:
<div id="select-word-5" class="select-word-link"> - some content - </div>
<div id="select-5" class="select"> - some content - </div>
I have throughout my document several select-word-link and select divs.
I want to add a click event to the first div, that reacts just to the second div.
My idea was to loop through all the "select-x" elements, but i think there is a much better way?
$('.select-word-link').each(function()
{
var id = this.id;
var idLink = this.id.replace("-word", "");
$('.select').each(function()
{
if (idLink == this.id)
{
$(id).click(function() {
alert("this does not work");
});
});
});
You can do this easier by triggering an action on an event.
$('#select-5').click(function(){
alert('Does this work?');
});
$('.select-word-link').click(function(){
$('#select-5').trigger('click'); // will behave as if #select-5 is clicked.
});
Info: http://api.jquery.com/trigger/
More advanced:
$('#select-5').click(function(){
alert('Does this work?');
});
$('#select-6').click(function(){
alert('Does this work?');
});
// etc
$('.select-word-link').click(function(){
var selectId = this.id.replace('-word', '');
$('#'+selectId).trigger('click'); // will behave as if #select-5 is clicked.
});
maybe this code help you
$(".select-word-link").click(function(){
$(this).next().hide();
});
});
try
$('.select-word-link').first().on('click',function(){
// you code goes here
})
jQuery as CSS uses # selector to identify that this string is an Id.
e.g.
<div id="someId"></div>
and you execute this code:
$('#someId')
this will select the DOM object that has the Id someId
while id property returns the id of the DOM object without the selector # i.e. this jQuery code:
var id = $('#someId').get(0).id
will initialize the variable id to 'someId'
Thus, in your code add '#' in the selector
$('#' + id).click(function() {
alert("this does not work");
});
You have to trigger click next() element not all .select
$(".word").click(function() {
var selectId = this.id.replace('-word', '');
console.log(selectId);
$('#'+selectId).trigger('click');
});
$(".next").click(function() {
alert($(this).html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-word-5" class="select-word-link word">- some content 5-</div>
<div id="select-word-6" class="select-word-link word">- some content 6-</div>
<div id="select-word-7" class="select-word-link word">- some content 7-</div>etc.
<div id="select-5" class="select-word-link next">- some content next 5-</div>
<div id="select-6" class="select-word-link next">- some content next 6-</div>
<div id="select-7" class="select-word-link next">- some content next 7-</div>
very simple solution
$('#select-5 , .select-word-link').click(function () {
// your code
});
If you want trigger same functionality from 2 or more different div ids or classes or combination of both then put separated by , like '#select-5 , .select-word-link' as shown in above example.

Hide element which is not a certain class

I want to hide an element which is not a certain class via jQuerys not() :
Content 1
Content 2
<div class="post-item c_1"></div>
<div class="post-item c_2"></div>
and
var thisContent;
jQuery('.content-btn').click(function() {
thisContent = this.id;
jQuery('.post_item').not('.'+thisContent).fadeOut();
}
am I using .not() method wrong in this context, because it seems not to work!
Your selector needs to be
jQuery('.post-item')
And you need to close the ) at the end of your jQuery, like this:
var thisContent;
jQuery('.content-btn').click(function() {
thisContent = this.id;
jQuery('.post-item').not('.'+thisContent).fadeOut();
});
See http://codepen.io/anon/pen/EaNXjg for a working example.
Try using
$(element).hasClass(".clasname").fadeOut();
as #AND Finally noticed modify your selector .. and while you use click on Anchor you need to use e.preventDefault; try this
jQuery('.content-btn').click(function(e) {
e.preventDefault;
thisContent = this.id;
jQuery('.post-item').not('.'+thisContent).fadeOut();
$('.'+thisContent).fadeIn();
});
DEMO

Dynamic parameters in JQuery

I have function in which append method is taking a static parameter.
function toggle() {
$("#MS").append($('#hide'));
}
What i want is to pass the parameter dynamically from my Hyperlinks click event.
In above code that #MS is static which i want to pass dynamically
Code:
HTML
<div id="MS">
JP MORGAN<br>
</div>
I want to pass the argument from onclick to toggle method and that parameter will be used in the append method.
I have tried several combinations buut it didnt worked.
Please help..
My new code after changes
<script>
$(function() { // when the DOM is ready
var $hide = $('#hide').click(function(){
$(this).closest('div').hide();
});
$('a.toggle').click(function(e){
e.preventDefault();
$(this).parent().append($hide);
});
});
</script>
<div id="JP">
JP MORGAN<br>
</div>
still not working
Since you are using jQuery, you can add classes to your a elements and use parent method:
$(function() { // when the DOM is ready
var $hide = $('#hide').click(function(){
$(this).closest('div').hide();
});
$('a.toggle').click(function(e){
e.preventDefault();
$(this).parent().append($hide);
});
});
Retrieve the ID dynamically on the anchor's click event and pass that ID to the function:
$("a").on("click", function(e){
e.preventDefault();
$(this).append($('#hide'));
};

Categories

Resources