Add class to element with dynamically added data attribute - javascript

Ok, so I have a HTML file, that looks something like this:
while($stuff = $junk->fetch()){ ?>
<div class="top-div" data-place-id="<?php echo $place['id']; ?>"></div>
<div>
<article>
<div>
//some stuff
</div>
<div>
<span class="expand" data-place-id="<?php echo $place['id']; ?>"></span>
</div>
</article>
</div>
} ?>
As you can see, for each result from a database, a structure like this is being output. Naturally, there are going to be at least a few of these each time.
I wish to make it so, that each time the span is clicked, a class is added to the <div data-place-id=""> where the data-place-id is the same as the clicked elements.
I tried doing it this way:
expandOverlay = function(){
$(".expand").each(function(){
$(".top-div").addClass('is-expanded');
})
})
But, this just adds the class to every single element with this class.
Then I tried this:
expandOverlay = function(){
$(".expand").each('click', function(){
var dataAttr = $(this).data();
if($(".place-overlay").data() == dataAttr){
$(this).addClass("is-expanded);
}
})
});
But that didn't work either.
So, how do I get the .data() from my clicked element and how do I find other elements with the same data attribute, so I can assign it a class?

try this,
$('.expand').click(function(){
dataid = $(this).data('place-id');
$('div[data-place-id="'+dataid+'"]').addClass('is-expanded');
})
First grab the data attribute of clicked item
Mave a div selection where data-place-id is same as span's data-place id ny concatenating the attribute selector.

$('span.expand').click(function() {
$('div[data-place-id="' + $(this).data('place-id') + '"]').addClass('is-expanded');
});

Cristian has it right, but it may not need to be that complex. How about this?
$('span.expand').click(function() {
$(this).closest('div[data-place-id]').addClass('is-expanded');
});
Doesn't much matter what the data-place-id value is, does it?

this works?
$('span.expand').click(function() {
$(this).closest('div.top-div').addClass('is-expanded');
});

Related

Using other attribute instead of id in html and javascript

I am making a project of a chat app, I made a code that if the user is not your user it will be in the left side, and if the user is your user it will be on the right side, the code I do works, but there is a single error. The problem is that I do this:
html
<div class="msg right-msg" id="side">
<div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">{{ chat.user }}</div>
<div class="msg-info-time"></div>
</div>
<div class="msg-text">{{ chat.message }}</div>
</div>
</div>
javascript
$( "#side" ).each(function() {
//console.log( index + ": " + $( this ));
var users = $(".msg-info-name").text()
if (users != me) {
$("#side").removeClass("msg right-msg");
$("#side").addClass("msg left-msg");
};
});
The problem is that there are many of the same html code(That has the same id, class, etc..), So I realized that I can use id in only one, I use id and this was the product Image of the product, it only change the place in the first one, So that doesn´t work.
So I try using class but instead of changing the first one side it change nothing, so class doesn´t works. What can I do?, is another way to loop into all of this, ALSO, the javascript example is using id's. thank for the help
use class not id for multiple elements.
$( ".msg" ).each(function() {
var users = $(this).find(".msg-info-name").text();
if (users != me) {
$(this).removeClass("msg right-msg");
$(this).addClass("msg left-msg");
};
});

How to select text value from a variable div id tag?

<div id="Modal<%= index %>">
<div>
<input type="text" id="textvalue">
</div>
</div>
In the above code I need to get value of text field but the problem coming is the div id is variable according to index i.e it may be 'Modal0' or 'Modal1' or 'Modal"n"' depending on value of index. So, if i write $(#textvalue).val() then it is always giving the text entered in id 'Modal0'. What will be solution for this? And the big issue is that I can not use 'Modal0' or 'Modal1' ... id because that is generated dynamically.
you can use closest jquery function like that make dive id is different.
closest will fetch the parent tag.
$(diveid).closest("diveid").inoutid.val();
You should include the parent div in the query as well, for example:
$("#Modal0 input").val();
First you should select the div you´re looking for , then find it's text-input
$('#Modal0').find('#textvalue').val();
$('#Modal1').find('#textvalue').val();
Im not sure if this is what you're trying to do, but if the clicking of buttons will only affect the ID of the same container div of the input.textvalue element then this will do the trick:
$('div[id^=Modal] #textvalue').val());
DEMO:
$(function(){
$('a').on('click', function(e) {
const ID = $(this).attr('href')
const counterID = ID.substring(ID.length-1);
const targetID = $('div[id^="Modal"]').attr('id');
$('div[id^="Modal"]').attr('id', 'Modal'+(counterID-1));
console.log('DIV ID:', 'Modal'+(counterID-1));
});
$('button').on('click', function(){
console.log('DIV ID: ' + $('div[id^=Modal]').attr('id'), ' ,TEXT VAL: ' + $('div[id^=Modal] #textvalue').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Modal 1
Modal 2
Modal 3
<div id="Modal">
<div>
<input type="text" id="textvalue">
</div>
<button>submit</button>
</div>

Jquery 'find' not working with data tag

I'm struggling to get the Jquery 'find' to work in the following code. I've stripped it down to the very basics. In short, what I'm trying to achieve is, I have two lists containing the same names. When the name is clicked on the top list, I want a more detailed box to toggle open below. Then when either is clicked again, the lower box will toggle closed again.
I assume something is wrong in the Jquery with the 'find'. The other part, which collects the ID works fine when the ID is sent to an alert.
I've looked through other answers and that find section is from another answer but it doesn't work in this example, so presumably I'm doing something wrong on some other level.
Bear in mind that just finding the div or paragraph element won't work for my full code. I've just put them in those tags for this example. I basically need to find (in this example), the para inside the correct div (obviously there's only one div here but loads in my full code).
<html>
<body>
<?php
for ($x=0; $x<10; $x++) {
echo "<p class = 'player_name' data-playerid = $x>Player $x</p>";
}
echo "<div class = 'individual_player_reports'>";
for ($x=0; $x<10; $x++) {
echo "<p class = 'player_name' data-playerid = $x>Player $x</p>";
}
echo "</div>";
?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$('.player_name').on('click',
function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[playerid='" + id + "']").toggle();
});
</script>
</body>
playerid !== data-playerid
Data attributes are just like any other attributes. Use the full name of the attribute when using the attribute equals selector.
$('.player_name').on('click',function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[data-playerid='" + id + "']").toggle();
});
$('.player_name').on('click',function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[data-playerid='" + id + "']").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="player_name" data-playerid='1'>1</p>
<p class="player_name" data-playerid='2'>2</p>
<p class="player_name" data-playerid='3'>3</p>
<div class="individual_player_reports">
<p data-playerid='1' style="display: none;">1</p>
<p data-playerid='2' style="display: none;">2</p>
<p data-playerid='3' style="display: none;">3</p>
</div>
As #T.J. Crowder suggests, you don't need to use .data() in this case, it would be more efficient to skip .data and just get the attribute value directly to avoid initializing the data cache unless you are using .data()'s features elsewhere too.
var id = $(this).attr('data-playerid');

jquery toggle not functioning

My Jscript/Jquery is not working. I can alert but I cannot get my div to toggle. Can someone explain to me why please? My code is below. I am using JSP if it matters.
My Javascript
$(window).ready(function(){
$(".moreButtonClass").click(function(e){
var id = this.id;
var cleanid = id.replace(/[^\d]/g, "");
var dog = "post" + cleanid;
alert(dog);
$(dog).toggle();
});
});
My Html
<div id="content">
<h1>Site Update Log:</h1>
<% for(int i = 0; i<2; i++){ %>
<div class="blogPost" id="postGroup<%= i %>">
<div>The ID is :<%out.print(indexModel.miniBlogConnector.GetID(i));%></div>
<div>The DATE is :<%out.print(indexModel.miniBlogConnector.GetDate(i));%></div>
<div>The AUTHOR is :<%out.print(indexModel.miniBlogConnector.GetAuthor(i));%></div>
<div>The MINIPOST is :<%out.print(indexModel.miniBlogConnector.GetShortPost(i));%></div>
<div class="MainPost" id="post<%=i%>">The POST is :<%out.print(indexModel.miniBlogConnector.GetPost(i));%></div>
<button type="button" class="moreButtonClass" id="moreButton<%=i%>">more</button>
</div>
<% } %>
</div> <!-- end #content -->
My CSS
.MainPost {
display:none;
}
Can anyone please explain to me why I can alert dog and get the correct variable name. But when I try to toggle it; it is not functioning. Nothing happens. No errors; no changes. It absolutely does nothing. I even tried using console.log and was unable to get it to react. The button works because the alert works; but the toggle is not functioning.
Can any one let me know how to fix this please?
Here dog is just a variable, and not a DOM node.
You need to do:
$("#"+dog).toggle(); //assuming it is an id. if class, use . instead of #
If the content in the dog is an ID, use this:
$("#" + dog).toggle();
Or, if it is a class, use this:
$("." + dog).toggle();
Since, in your case, it is going to be an ID, you need to use the first one.
You missed the selector # here.Then it will consider as a variable not DOM element
var dog = "#post" + cleanid;
$(dog).toggle();
or
$("#"+dog).toggle();

Consolidate multiple jQuery conditional statements to a single query?

On my web page, I output jQuery for each record that is rendered on the page like this:
if ($.trim($('#attachment<%# Eval("Id")%> .content').html()) == '') {
$('#attachmentClick<%# Eval("Id")%>').hide();
}
Notice there is server binding on the element ID to make sure each record has the jQuery processed. Is there a way to do this only once on the page by embedding the conditional statement, such as "for all $(this.ID + ' .attachmentsClick'), hide only if $('.attachments.content').html() trimmed is blank"?
You could use jQuery's filter function to reduce the set of potential elements to those with empty content, and then hide them:
$('.attachmentsClick').filter(function(){
return $.trim($(this).find('.content').html()) == '';
}).hide();
This assumes that you give the class of "attachmentsClick" to all of your row elements. It does not need the ID of the row elements. Just run this after your content has loaded, and it will hide all elements with a class of "attachmentsClick" that have a child with a class of "content" which is empty when trimmed.
Your HTML might look something like:
<div class="attachmentsClick"><!-- this one will be hidden -->
<div class="content"></div>
</div>
<div class="attachmentsClick"><!-- this one will be hidden too -->
<div class="content"> </div>
</div>
<div class="attachmentsClick"><!-- this one will NOT be hidden -->
<div class="content"><p>some content<p></div>
</div>
You can use .each(). .someCommonClass should be on each one that has the ID.
$('.someCommonClass').each(function(i, e) {
var $e = $(e);
if ($.trim($('.content', $e).html()) == '')
$e.hide();
});

Categories

Resources