Using other attribute instead of id in html and javascript - 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");
};
});

Related

Insert variable into file path string in javascript

Depending on the user selection the variable "team" contains different team names as string. I want then display the according team logos which are saved as .png files. Therefor I want to insert the variable's string into the file path. How to do that?
Thank you.
JS:
$('ul.subbar li a').on('click', function(e) { // User clicks on a team in the navbar
e.preventDefault(); // Stop loading new link
var team = $(this).html(); //assign clicked team name to variable
console.log(team);
$('.selectedClub').html(team);
$('.teamLogo').src("'images/Clubs/Germany/' + 'team' + '.png'").alt(team);
});
html:
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="images/man united.png" alt="Manchester United">
</div>
<div class="selectedClub">Manchester United</div>
</div>
</div>
You have a problem here:
$('.teamLogo').src("'images/Clubs/Germany/' + 'team' + '.png'").alt(team);
Should probably be something like:
$('.teamLogo').attr('src', 'images/Clubs/Germany/' + team + '.png').alt(team);
(without the extra quotes)
Better answer is to use string interpolation
$('.teamLogo').src(`images/Clubs/Germany/${team}.png`).alt(team);

Unable to Clone HTML & Values into jQuery Datatables 1.10

This question has been asked on a few occasions, for example:
Store Cloned Element in Variable
Copy DOM Element
However, I'm having issues selecting say <div id="XYZ"></div> and cloning it to a variable for the jQuery DataTable fnStateSaveParams to save. When the page refreshes it is then meant to reload the cloned object back into the HTML via fnStateLoadParams. I am trying to use .clone() over .html() because I also need the values stored within the dynamically generated textboxes.
If I'm not saving and loading via the Datatables plugin, then it works perfectly. As soon as I try calling code similar to the below then it ceases to work (please bare in mind I've tried a number of variations to the below code). Has anyone got any ideas or suggestions?
"fnStateSaveParams": function (oSettings, oData) {
var clonedHtml= $("#XYZ").clone(true);
oData.storedHtml = clonedHtml;
},
"fnStateLoadParams": function (oSettings, oData) {
//$("#displayHtml").append(oData.storedHtml);
//$("#displayHtml").html(oData.storedHtml);
//$(oData.storedHtml).prependTo("#displayHtml")
}
<div id="XYZ">
<div data-template="">
<label class="bolder"></label>
<div class="input-append">
<div class="inline-block advancedSearchItem">
<input type="text" id="test1" value="Test Scenario" />
</div>
<a href="#" data-id="" class="btn btn-small btn-danger removeField">
<div class="hidden-phone">Remove</div>
<i class="icon-trash icon-only hidden-tablet hidden-desktop"></i>
</a>
</div>
</div>
</div>
The end scenario will be more complex, however the above is the simplest form of what I am trying to create. If you need more information, feel free to ask and I'll update the question accordingly.
I didn't find a way of utilising .clone() to grab all HTML and Text Box values. However, I did come up with a solution and the code below is for anyone who needs a reference point.
Using .html() (as most will know) will only copy the available HTML and ignore what is essentially 'placeholder' text within text fields. My solution though is to force the value into the HTML rather than being treated as 'placeholder' text, this allows it to be used again when the page is loaded.
$(document).on("click", "#advancedSearchButton", function(event) {
event.preventDefault();
// DO SOME STUFF HERE
$("[data-value]").each(function(index) {
if (index > 0) {
fieldCount++;
$(this).attr("value", $(this).val());
}
});
oTable.fnFilter("");
});
function loadData() {
// ... ... ...
"fnStateSaveParams": function(oSettings, oData) {
oData.advancedSearchHtml = $("#addedSearchFields").html();
oData.fieldCount = fieldCount;
oData.isAdvancedSearch = isAdvancedSearch;
},
"fnStateLoadParams": function(oSettings, oData) {
$("#addedSearchFields").html(oData.advancedSearchHtml);
if (oData.isAdvancedSearch == true) {
$("#collapseElement").removeClass("collapsed");
$("#collapseIcon").removeClass().addClass("icon-chevron-up");
$("#filter").hide();
}
isAdvancedSearch = oData.isAdvancedSearch;
advancedSearchFields = oData.fieldCount;
}
// ... ... ...
}

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

Can I create an interactive list that displays only one sublist at a time?

for my website, I'm trying to create a list of artists. when a user clicks the name I want to display a list of tracks. when the user clicks on a track, a video displays. Is this possible in HTML? I know very little js. I've spent a few hours on this and haven't been able to get anything working.
Thanks in advance!
I would do it with AJAX.
Let's say you have such HTML code:
<div id="artists">
<div class="artist" data-art-id="1">Artist name 1</div>
<div class="artist" data-art-id="2">Artist name 2</div>
<div class="artist" data-art-id="3">Artist name 3</div>
</div>
<div id="tracks"></div>
<div id="video"></div>
Then you have to white jQuery code:
$(function() {
$('.artist').click(function() {
var artId = $(this).attr('data-art-id');
$('#tracks').load('/get_tracks_list.php?art_id=' + artId, function() {
$('.track').click(function() {
var trackId = $(this).attr('data-track-id');
$('#video').load('/get_video.php?track_id=' + trackId);
});
});
});
});
Your get_tracks_list.php should have something like this:
<?php
mysql_connect(YOUR_HOST, YOUR_LOGIN, YOUR_PASS);
mysql_select_db(YOUR_DB);
$artId = intval($_GET['art_id']); //prevent SQL injection
$res = mysql_query('SELECT track_id, track_name FROM tracks WHERE art_id="'.$artId.'"');
while ($track = mysql_fetch_assoc($res)) {
echo '<div class="track" data-track-id="'.$track['track_id'].'">'.htmlspecialchars($track['track_name']).'</div>';
}
And get_video.php should contain information about the video.
This approach requires that you have all your data in DB (table names and field names may be different)
I think this is the most common practice.
Good luck!

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