jquery toggle not functioning - javascript

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();

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");
};
});

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');

JavaScript add an HTML class to div. If statement. Bootstrap

You may have seen the input box with success tick glythicon.
I'm trying to make a form where the input box is normal (not green and no tick showing) and upon successful validation in JavaScript, I want it to change to to the green border and display the glythicon tick. I think that adding the class is the way to do it and I can't quite get it working.
I tried to use the following for adding a class:
document.getElementById('id').className.add('addditional classes');
But I can't figure out the correct syntax to get this code to work.
function validateName() {
var name = document.getElementById("first_name").value;
if(name.match(/^[A-Za-z]*\s{0}$/)){
document.getElementById('firstcheck').classform-group, has-feedback.add(' has-success');
document.getElementById('firstcheck2').classglythicon, glythicon-ok.add(' form-control-feedback');
}
HTML code
<div id="firstcheck" class="form-group has-feedback">
<input onblur="validateName()" id="first_name" type="text" class="form-control" id="inputSuccess2" aria-describedby="inputSuccess2Status">
<span id="firstcheck2" class="glyphicon glythicon-ok" aria-hidden="true"></span>
</div>
Any help would be appreciated!!!
Please always check your code carefully after copy+paste.
The placement of quotation marks is important, as is placement of dots
And this is jquery code:
$('id').addClass('addditional classes');
Try this instead:
function validateName() {
var name = document.getElementById("first_name").value;
if(name.match(/^[A-Za-z]*\s{0}$/)){
document.getElementById('firstcheck').className += 'form-group has-feedback has-success';
document.getElementById('firstcheck2').className += 'glythicon glythicon-ok form-control-feedback';
}
Also dont include , in the classnames string
Try to add the class this way:
//first get the element
var elem = document.getElementById("id");
//append new classes to your existing class
elem.className = elem.className + " additional classes";
//apply the same login in your remaining code
if(name.match(/^[A-Za-z]*\s{0}$/)){
elem = document.getElementById('firstcheck');
elem.className = elem.className + " has-success";
elem = document.getElementById('firstcheck2');
elem.className = elem.className + " form-control-feedback";
}
OR
You can easily achieve this with jquery like this:
$('id').addClass('additional-classes');
Since Bootstrap's JS needs jQuery you can make your life a bit easer here. I've created a small example https://jsfiddle.net/eg8dsgh2/. Just use jQuery's addClass()
Hope it helps
document.getElementById('firstcheck').classform-group, has-feedback.add(' has-success');
Is this invented? Where do you see something like this'
To add a class use className.
document.querySelector('#firstcheck').className += " has-success";

Add class to element with dynamically added data attribute

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');
});

JQuery onclick attribute undefined in each() loop

Please forgive my awful coding style. I am learning to write a Chrome extension and can't figure out some JQuery stuff. I am trying to parse a document with some rows, each containing a (dynamically generated?) link, the HTML code looks like this:
<div class="row" id="rand">
<div class="display">
<div class="link">
<a name="actionLink" href="#" alt="action" onclick="listener.postAction('form', 'http://***/')" class="alink"><span>Confirm</span></a>
</div>
</div>
I am grabbing the info the following way:
$(".row").each(function(index)
{
var $itemArea = $(this).find(".display");
var id = $(this).attr("id");
var alink = $(this).find(".link").find("a");
var onclick = alink.attr("onclick");
console.log("id=" + id);
console.log("alink=" + alink);
console.log("onclick=" + onclick);
});
Here's the output from JSBin:
"id=rand"
"alink=[object Object]"
"onclick=listener.postAction('form', 'http://***/')"
However, when I debug this in Chrome, the value of "onclick" returned by my code is undefined. To make things more confusing, when I inspect the onclick attribute of alink, it shows the correct value? What am I doing wrong?
Try the following to get your var instead
var onclick = $('.link a:first',this).attr('onclick');

Categories

Resources