So
I've defined a simple list and an output
<div class="item-list">
<p id="One">First Item</p>
<p id="Two">Second Item</p>
<p id="Three">Third Item</p>
</div>
<div class="box">Add Stuff in Here!</div>
And
I've written this script
$(".item-list > p").click(function(){
var thisId = (this.id);
$(".box").append('<p>' + thisId + '</p>');
});
I want
each item, on click, to append its id as text inside .box element
Like So
<div class="box>One</div>
And this works
just like you'd expect. JS Fiddle of the simplified Working Example.
But in my more complex example:
the id of the selected element
(this.id)
comes back as ...
Ew..
undefined.
Here's a JS Fiddle of the more complex version of this:
http://jsfiddle.net/pQz3W/4/
What's causing these id's to return undefined?
To be clear, In the more complex example, I'm doing the same thing, it's just crowded by other functionality. Something in there is causing my id to come back as undefined.
I'll keep posting updates to this fiddle as I clean the code up more and more to pertain only to what's necessary to be there for this question!
You have an array
ServiceArray = [
[
["SplashPage", "Splash Page", "hey!"],
["GamingWebsite", "Gaming Website", "yo!"],
["BasicWebsite", "Basic Website", "hi!"],
["AdvancedWebsite", "Advanced Website", "ooh!"],
["FlexWebsite", "Flex Website", "ahh!"],
......etc
and you have ID's that you're trying to look up in that array like this
var thisId = this.id;
var outputList = ServiceArray[0][thisId][2];
but there are no associative arrays in javascript, and the keys you're looking for doesn't exist. You need to rebuild that array with objects that has keys and values that actually match what you're looking for.
try this: var thisId = $(this).attr("id");
Related
What I've done is loaded some HTML from a file and I am attempting to modify some elements within that HTML.
The initialization looks like this:
var id = player_info["ID"];
$("#main_container").append(
$("<div />").attr({class: "player_container", id: "player_" + id}).css("display", "none")
);
// Add all information to the player container
var player_container = $("#player_" + id);
player_container.load("player_layout.html");
With player_layout.html looking like this:
<div class="player_name">
</div>
<div class="player_chips">
Chips:
<br/>
<span class='bidding'></span>/<span class='chips'></span>
</div>
<div class="player_stats">
Wins / Losses
<br/>
<span class="wins"></span>/<span class="losses"></span>(<span class="total_games"></span>)
<br/><br/>
Chips Won / Chips Lost
<br/>
<span class="chips_won"></span>/<span class="chips_lost"></span>
</div>
<button class="player_won">Player Has Won</button>
I then want to modify some of the elements, specifically classes. An example of the way I was initially doing this is:
player_container.find(".player_name").text(player_info['username']);
This wasn't working so I then tried to switch find with children and text with html but that didn't seem to work. I then tried this:
$('> .player_name', player_container).html(player_info['username']);
but that also didn't work. I understand that I can use DOM to grab the childNodes and compare the class names but there are a lot of classes that need modifying and I'd also like to know if this is possible in JQuery. Thanks in advance for any help.
You need to use complete callback method of .load()
var player_container = $("#player_" + id);
player_container.load("player_layout.html", function(){
player_container.find(".player_name").text(player_info['username']);
});
Trying to consolidate these three sub functions into one sub function by passing along a variable from the button itself. I currently have four buttons and each button triggers the primary function. Inside the primary function I have the three sub-functions that changes the contents of the div with one of three new html variables. So each button can then change out the div to its own respective content. This code is working now for me no problems, but I figure there has to be a way to just make that sub-function into just one function instead of three by setting the .replaceWith to a global variable. That inside the function there would be a getter that checks the ID of the button that was clicked and passes it to that replaceWith instead.
<script>
$(document).ready(function(){
$("button.first").click(function(){
$('div.switchMeOut').replaceWith(firstHTML);
});
$("button.second").click(function(){
$('div.switchMeOut').replaceWith(secondHTML);
});
$("button.third").click(function(){
$('div.switchMeOut').replaceWith(thirdhtml);
});
});
var firstHTML = '<div class="switchMeOut"><p>First Section Content</div>';
var secondHTML = '<div class="switchMeOut"><p>Second Section Content</div>';
var thirdHTML = '<div class="switchMeOut"><p>Third Section Content</div>';
</script>
<body>
<div id="parentblock">
<h5>Contacts List</h5>
<div class="switchMeOut">
<script> document.write (firstHTML + seconcHTML + thirdHTML); </script>
</div>
</div>
<button id="firstHTML" class="swapper first">Shows First Only </button>
<button id="seconcHTML" class="swapper second">Shows Second Only </button>
<button id="thirdHTML" class="swapper third">Shows Third Only </button>
</body>
So here is what I think should be next but I am definitely missing something.
<script>
$(document).ready(function(){
$("button").click(function(){
// some code here to get the buttons ID element
// and possibly set a variable to that buttons id.
var passThis = button#;
$('div.switchMeOut').replaceWith(passThis);
});
});
Then have each button have their own id. For example:
<button id="firstHTML" class="swapper first">Shows First Only </button>
Any help on this would be appreciated, I dont quite know what I am missing here but I feel like it's pretty close.
Thanks!
You can get the ID of the clicked element like this:
var passThis = $(this).attr("id");
But I think you need to do this too:
var htmls = {
firstHTML: '<div class="switchMeOut"><p>First Section Content</div>',
secondHTML: '<div class="switchMeOut"><p>Second Section Content</div>',
thirdHTML: '<div class="switchMeOut"><p>Third Section Content</div>'
}
And then your switching statement would look like this:
$('div.switchMeOut').replaceWith(htmls[passThis]);
Regarding your comments:
htmls is not an array, its an object. It's called an object in javascript, but people also call them dictionaries, hashes, associative arrays, key/value pairs etc. See: https://en.wikipedia.org/wiki/Associative_array
Also you can't "call" an array or object. You call a function. The best way to phrase that would be "I retrieved/got the value at index 3" for arrays and "I retrieved/got the firstHtml property" for objects.
You can use "eval('variablename') to get the value of the variable. However you can also use eval to get a reference to an object with that ID "eval('id')". So the first thing to do is change the ID of your buttons to a data attribute. Instead of "id='firstHTML'" make it "data-id='firstHTML'". So that when you eval("firstHTML") it knows you mean the variable and not the button object.
And you can get rid of the inline script tag in the "switchMeOut" div and load that using jquery in the same document.ready function.
Heres a fiddle showing it working: http://jsfiddle.net/ub8wz5Lb/
HTML:
<div id="parentblock">
<h5>Contacts List</h5>
<div class="switchMeOut">
</div>
</div>
<button data-id="firstHTML" class="swapper first">Shows First Only </button>
<button data-id="secondHTML" class="swapper second">Shows Second Only </button>
<button data-id="thirdHTML" class="swapper third">Shows Third Only </button>
Javascript:
var firstHTML = '<div class="switchMeOut"><p>First Section Content</div>';
var secondHTML = '<div class="switchMeOut"><p>Second Section Content</div>';
var thirdHTML = '<div class="switchMeOut"><p>Third Section Content</div>';
$(document).ready(function(){
$("button").click(function(){
var id = $(this).data("id");
$('div.switchMeOut').html(eval(id));
});
$('div.switchMeOut').html(firstHTML + secondHTML + thirdHTML);
});
I have a list of elements (DIVs) on my html page as below.
There is a list of hashtags on the same page.
I need that when the user clicks on the hashtag (e.g. #bacteria) only those DIVs that contain that hashtag are shown.
What would be the most lightweight and easy way to implement that?
<div class='entry'>
<p>#antibiotics destroy #e-coli and that's not good!!!!</p>
<!-- Hashtags: #antibiotics #eColi -->
<!-- UID: 755a2a60-972e-11e3-a464-872f2fc4dea2 -->
</div>
<div class='entry'>
<p>#bacteria can be #friendly, such as #e-coli for example</p>
<!-- Hashtags: #bacteria #friendly #eColi -->
<!-- UID: 6cc66d00-972e-11e3-a464-872f2fc4dea2 -->
</div>
<div class='entry'>
<p>#antibiotics can fight #bacteria</p>
<!-- Hashtags: #antibiotics #bacteria -->
<!-- UID: b37992c0-9686-11e3-8b2c-c97ae6645b3b -->
</div>
I know that Angular is powerful for this kind of stuff, but I'd like to use something lightweight and easy. Like maybe it's possible to do it with jQuery or something...
FYI the whole thing runs on Node.Js / Express.Js with EJS rendering.
Thank you!
UPDATE
Suppose now I have several hashtags I need to check for. Like as if contains variable is not a string but an array and i need to only show entries that contain ALL of this array's values. How would I change the code? Trying to do that, but can't manage... Thank you so much!
Use the :contains jquery selector
$(document).ready(function(){
$('.entry').hide();
$('.links').on('click','a',function(e){
var $ctx = $(e.target);
var contains = $ctx.text();
$('.entry').hide();
$('.entry:contains('+contains+')').show();
return false;
});
});
Sample : http://jsfiddle.net/LA3tD/
EDIT
you can use text with commas and then split, or use data attribute with some separator and split it afterwards for a concatenated filter selector
$(document).ready(function(){
$('.entry').hide();
$('.links').on('click','a',function(e){
var $ctx = $(e.target);
var contains = $ctx.text();
$('.entry').hide();
if(contains.indexOf(',')!=-1){
var tags = contains.split(',');
var filt = '';
$.each(tags,function(i,el){
filt += ':contains('+el+')';
});
// :contains can be concatenated multiple times f.e.: ":contains(foo):contains(bar)"
$('.entry'+filt).show();
}else{
$('.entry:contains('+contains+')').show();
};
return false;
});
});
Updated sample: http://jsfiddle.net/LA3tD/1/
Ideally, you'd incorporate your hash-tag data into the divs themselves...perhaps with the data-* attribute:
<div class='entry' data-hashtags='antibiotics bacteria'>
Then via jQuery you could loop through them hiding the ones that don't match:
var clickedHashtag = x //get the clicked on hashtag however you like
$('.entry').each(function(){
if($(this).data('hashtags').indexOf(clickedHashtag)>=0){
$(this).hide()
}
})
Fiddle: http://jsfiddle.net/Jz3gZ/
Untested:
$('.entry').each(function(item) { $(item).show($item.is('.' + hashtag)); });
You would have to add the hashtag as a class, of course:
<div class="entry antibiotics">
I have an unordered list called test
<ul id='test'></ul>
it is dynamically populated with data via ajax. Each item 'li' is a div containing 'p' paragraphs. Each paragraph contains some information.
Ex:
<li> <div> <p> test </p> </div> </li>
<li> <div> <p> hi how is it going?</p> </div> </li>
<li> <div> <p> not a test</p> </div> </li>
<li> <div> <p> whoa</p> </div> </li>
I also have a search box which i can get a search term from, I use:
var searchTerm = $("#search").val().trim().split(' '); // an array of words searched for
What I am trying to do is find a way to select all 'li' elements which contain all or some of the search words, but I'm not sure how to approach it best.
Currently, I am doing this:
var results = $('p:contains("'+ searchTerm[0] +'")');
to get an exact match on the first term, but I want to search for multiple terms, not just one.
I would want to search for 'test hi' and get back three nodes cause it searches for 'test' and 'hi'.
I also thought of:
var results2 = $('p').filter(function( index ) {
return ( this +':contains("'+ searchTerm +'")' );
});
Anyone point me in the right direction?
You could do some black magic with the selector, like this:
var results = $('p:contains("' + searchTerm.join('"), p:contains("') + '")');
This looks hard, but I'll explain it.
It joins the search terms with "), p:contains(". Then it just adds the missing p:contains(" and ") to the ends of the result string and searches for it.
A combination of $.filter and $.each (or array.forEach, if you don't care about ie8) can also be of use here:
var searchTerms = ["how", "test"];
$('div').filter(function () {
$text = $(this).text();
var found = 0;
$.each(searchTerms, function (index, term) {
found = $text.indexOf(term) > -1 ? found +1 : found;
})
return found;
}).addClass('match');
jsFiddle
I want to select the elements created dynamically using ajax by id, the code is:
$(function(){
$('#loadFeed').bind('click',function(){
$.getJSON('getData.php', function(json) {
var output="<ul id='feedsList'>";
for(var i=json.posts.length-1;i>=json.posts.length-31;i--){
output+="<li class='post'>";
output+="<div class='text' id='"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";
output+="</li>";
}
output+="</ul>"
$(output).appendTo('.posts');
});
});
});
The html codes:
<div class="posts">
<!--dynamic content here-->
</div>
I tried to get the id using $(this).attr("id"):
$(".post").on("click",".text",function(){
var this_id =$(this).attr("id");
alert(this_id);
});
But it said undefined. How could I get the id correctly?Thanks!
$(".post") should be $('div.post'), because you're creating li from ajax request with same class. As div.post is existing in your DOM and you're appending you list to it.
That is,
$("div.post").on("click","li.post div.text",function(){
var this_id = this.id;
alert(this_id);
});
Numbers are not valid ids. Ids need to start with letters.
You will need to use something like this:
output+="<div class='text' id='post_"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";
Here'se the structure of a valid id: What are valid values for the id attribute in HTML?