Trouble setting the HTML of a variable in JQuery - javascript

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

Related

consolidate javascript function by passing a variable from html object ID such as button ID

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

Filtering data in Javascript

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">

Jquery - $(this) id from selector group

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

Get next textarea outside div without id

I need to get the next textarea, but I'm not being able with next or even find.
Sample code HTML:
<div>
<div class="guides_chapters_button" onclick="surroundtest('[center]', '[/center]');">Center</div>
<div class="guides_chapters_button" style="text-decoration: underline;" onclick="surround('[u]', '[/u]');">u</div>
</div>
<textarea class="guides_chapters_textarea" id="textareamatch" name="matchupm" rows="7" cols="25"></textarea>
JS:
window.surround = function surround(text2,text3){
$("#textareamatch").surroundSelectedText(text2, text3);
}
function surroundtest(text2,text3){
var c = $(this).parent().next('textarea');
c.surroundSelectedText(text2, text3);
}
JS FIDDLE: http://jsfiddle.net/qmpY8/1/
What I need working is surroundtest, the other is an example working but using the id. I would love to replace that one because Im usinc cloned objects.
The this statement in surroundtest applies to the window object and not the element. What you should do is to change the function definition as so:
function surroundtest(element, text2,text3){
var c = $(element).parent().next('textarea');
...
}
And the HTML accordingly:
<div class="guides_chapters_button" onclick="surroundtest(this, '[center]', '[/center]');">Center</div>
If this is the HTML you are going with, then .closest() can also be used to get the textarea element.Like below:
var c = $(element).parent().closest('textarea');

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

How do I change/replace the <h3> text: "Featured Offers" using javascript to say "Public Offers" instead?
</div> <!-- FEATURED OFFERS -->
<div class="panel">
<div class="head">
<h3>Featured Offers</h3>
</div>
<div class="body">
<table>
<thead>
<tr>
If you can select it, you can manipulate it.
Try this:
$(".head h3").html("your new header");
But as others mentioned, you probably want head div to have an id.
you don't - not like this.
give an id to your tag , lets say it looks like this now :
<h3 id="myHeader"></h3>
then set the value like that :
myHeader.innerText = "public offers";
$("h3").text("context")
Just use method "text()".
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method.
http://api.jquery.com/text/
Give an id to h3 like this:
<h3 id="headertag">Featured Offers</h3>
and in the javascript function do this :
document.getElementById("headertag").innerHTML = "Public Offers";
try this,
$(".head h3").html("New header");
or
$(".head h3").text("New header");
remember class selectors returns all the matching elements.
Something like:
$(".head h3").html("Public offers");
jQuery(document).ready(function(){
jQuery(".head h3").html('Public Offers');
});
You can try:
var headingDiv = document.getElementById("head");
headingDiv.innerHTML = "<H3>Public Offers</H3>";
Hope that help someone:-
Element with a class attribute with the value of "className":
<h3 class="className"></h3>
You will make a refernce of by the class name:
const newTitle = document.querySelector(".className");
Then change the content:
newTitle.textContent = "New Title";

Categories