Getting html data from template generated list - JQuery - javascript

I am generating a list from a template engine (Template7) and adding a userID to the data tag in each list item. For example
<li>
<a id='user' data-user-id='5'>
<div>content here</div>
</a>
</li>
<li>
<a id='user' data-user-id='6'>
<div>content here</div>
</a>
</li>
I am trying to get the "user-id" data of the list item clicked on using jQuery, but what I seem to be doing instead is getting the user-id of the first list item - in this case always 5.
$(document).on("touchend", "#user", function(e) {
e.preventDefault();
var userItem = $("#user");
var userID = userItem.data("user-id");
console.log(matchID);
});
Where am I going wrong? A unique ID for each item would work, but then it would need to be parsed etc so there must be a better way! Is there a best practice for this kind of thing?

try replacing #user with this should work in your case
Id selector always selects first element with matching Id. it is advisable not to have multiple element with same id. try to use class name instead.
any ways for your query you can use below code.
$(document).on("touchend", "#user", function(e) {
e.preventDefault();
var userID = $(this).data("user-id");
console.log(userID);
});

Use a css class on each anchor item, like this:
<li>
<a class='user' data-user-id='5'>
<div>content here</div>
</a>
</li>
Id attributes are meant to be unique to that element.

To get the content of the attribute **data-user-id** like in <a id='user' data-user-id='5'> you have to use
$(this).attr("data-user-id") // will return the string "5"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("user-id") // will return the number 5

Related

Using JQuery to replace text in HTML but ignoring certain HTML id's

So I'm currently using Handlebars to grab data from a JSON file to show its data on the screen. Right now it's looking similar to this:
<div class="content" id = "topic">
{{#each topics}}
<a href="{{topic}}" id = "ignore">
<h2>{{topic}}</h2>
</a>
{{/each}}
</div>
I want to replace specific characters within the word topic with another one, for example if the {{topic}} was "Hi%3F" I want to replace the "%3F" part with a '?' everywhere except the part with id="ignore". The replace function I'm using right now is:
$("#topic").html($("#topic").html().replace(/%3F/g,'?'));
this manages to replace everything so far, but I'm not sure how to get it to ignore the tags with the id="ignore". There's probably an easier way to make the link portion work like its supposed to but this is what I have gotten now and I don't want to mess around or change too much.
Thanks!
Is not legal html to duplicate Ids. Ids need to be unique. I'd suggest adding a class="unique" to your anchor tag and use
<div class="content" id = "topic">
<a href="Hi%3F" class = "topic">
<h2>Hi%3F</h2>
</a>
<a href="Hi%3F" class = "topic ignore">
<h2>Hi%3F</h2>
</a>
<a href="Hi%3F" class = "topic">
<h2>Hi%3F</h2>
</a>
<a href="Hi%3F" class = "topic ignore">
<h2>Hi%3F</h2>
</a>
</div>
<script>
$("a.topic").not(".ignore").each(function() {
$(this).html($(this).html().replace(/%3F/g,'?'));
});
</script>
http://jsbin.com/huquyufafe/edit?html,output

Javascript - having trouble selecting an id

I gave my link a an id where if I click the link, I want my javascript to adjust the background image. I made a js-fiddle of a simple version of what I want here:
https://jsfiddle.net/qp8d390b/
<body background="http://www.blueskiescareers.co.uk/wp-content/uploads/2014/05/blue-sky-clouds.jpg">
<li>
<a id = "attempt1" href="#top">SNOOPY1</a>
</li>
<li>
<a>SNOOPY2</a>
</li>
<li>
<a>SNOOPY2</a>
</li>
<div id= "#top">TOP PART </div>
</body>
$(document).ready(function() {
$("a[id='attempt1']").click(function(e) {
e.preventDefault();
alert('works');
document.body.background = "https://upload.wikimedia.org/wikipedia/commons/0/02/Fried_egg,_sunny_side_up.jpg";
});
});
I'm new to selecting with javascript. Any help would be appreciated!
try to use $("#attempt1")
use # to get any id in html
Firstly your HTML is invalid; li must be in either a ul or ol and all a elements must have either a name or href attribute.
Secondly, jQuery uses CSS rules, so to select by id is $('#attempt1').
Lastly, to change the background CSS property to an image the URL string should be wrapped in url(). Try this:
$(document).ready(function() {
$("#attempt1").click(function(e) {
e.preventDefault();
$('body').css('background', 'url("https://upload.wikimedia.org/wikipedia/commons/0/02/Fried_egg,_sunny_side_up.jpg")');
});
});
You can select it with :
$('#attempt1')
You should use id-selector in this case
https://api.jquery.com/id-selector/
$("#attempt1")
The selector you used which is attribute selector is more used in inputs than in links (a elements)
https://api.jquery.com/attribute-equals-selector/
You can find more info on jQuery selectors in
https://api.jquery.com/category/selectors/
Hope it helps

CSS built with javascript only running on first call [duplicate]

This question already has answers here:
How can I apply a jQuery function to all elements with the same ID?
(4 answers)
Closed 9 years ago.
I am using the "replace" function to remove all non-numeric values in a div.
It seems Jquery replace only affects the first element.
Here is my Jquery:
$('#comment').each(function() {
var thz = $(this);
var repl = thz.html(thz.html().replace(/\D+/g, ''));
});
HTML Code:
<a id="comment1" href="#"> c2fđf011. </a>
<a id="comment1" href="#"> c20ff113. </a>
<a id="comment1" href="#"> c201gf76341. </a>
Result:
2011 c20ff113. c201gf76341.
The result I want is:
2011 20113 20176341
You have duplicate ids, Which is invalid and also jQuery ID selector(or any other id selector like document.getElementById which internally jQuery uses because element with ids are indexed by most browsers and are meant to be unique) will return only the first one that appears in DOM. Change it to class and see it working:
$('.comment').each(function() {
var thz = $(this); var repl =
thz.html(thz.html().replace(/\D+/g, ''));
});
HTML
<a class="comment1" href="#"> c2fđf011. </a>
<a class="comment1" href="#">c20ff113. </a>
<a class="comment1" href="#"> c201gf76341. </a>
By the way had your id been like this:-
<a id="comment1" href="#"> c2fđf011. </a>
<a id="comment2" href="#">c20ff113. </a>
<a id="comment3" href="#"> c201gf76341. </a>
Starts with Attribute selector will help you (But slow you down literally, since this is an attribute selector and lose the advantage of using IDs).
$('[id^=comment]').each(function() { // While using this better give a container context $('[id^=comment]', 'container').each(function...
var thz = $(this);
var repl = thz.html(thz.html().replace(/\D+/g, ''));
});
Demo
Moral: IDs must be unique
ID in a HTML page is supposed to be unique
That is the reason it targets only the first instance of the element found.
Replace the elements with class instead
$('.comment').each(function() {
// Your code
});
$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });
replace ur element with id comment to a class comment.
If you use ID several times on elements the selector will only pick the first element with that ID.
But when you use class instead, the selector will pick all the element having that class.
If you really don't want to change the html you can use selector by attribute. But as others suggested, using class instead of id is the best option here.
$('div[id="comment"]').each(function(){})

Method to select matching data elements using jQuery

I'm new to jQuery and have a question that goes beyond my knowledge. I have a link with a unique data-number and a div with a matching data-number. The goal is to hide all divs and when each link is clicked by the user the div would be displayed with the matching data-number.
The part that's difficult for me to figure out is how to iterate through all of the links and divs matching them up so when each link is clicked ONLY the matching div with the same data-number will be displayed.
Here is what I have so far in Coffeescript:
$('#task-item').on('click', (event) ->
n = $(#).data('number')
if (n > 0)
event.preventDefault()
$('#task-info').fadeToggle(600)
)
Sample html link:
<li id="task-item" data-number="3">
<span class="label label-purple"> Task</span>
<i class="icon-angle-right"></i>
<span class="label label-success">Open</span>
NEW SAVE METHOD FOR TASKS
..... additional HTML....
</li>
Sample div html:
<div id="task-info" data-number="3" class="span8">
..... #MORE HTML HERE ....
</div>
If there is a better way to accomplish this I'm open to any suggestions.
Firstly, I assume the li and div in your example are repeated multiple times, so you should be using a class to identify them. Secondly, you can use filter to find the element by the required data attribute. Try this:
$('.task-item').on('click', (event) ->
var $item = $(this);
$('.task-info').filter(function() {
return $(this).data('number') == $item.data('number');
}).fadeToggle(600);
Look into jQuery attribute selectors
http://api.jquery.com/attribute-equals-selector/
You should be able to select the div you want like this:
$("div[data-value='3']")
First thing I would recommend is change the li ids to class like <li class="task-item">
Then
<div class="task-info" data-number="3" class="span8">
JS
$(".task-item").click(function(e){
var itemNumber=$(this).data('number');
$('.task-info').filter(function() {
return $(this).data('number') == itemNumber
}).fadeToggle(600);
});

Get tag a id inside listitem id

I'm quite to new to JQueryMobile, JavaScript and HTML. In my screen I have a list of elements that are creates dynamically and when you click on each element it should get you to another screen depending on the name of the list item you clicked.
I have tried to get the a tag id, value, name... but it doesn't work... here is my code for each line:
<li style='height:30px;' id='$object'>
<a class='resume' id='$object' href='javascript:loadGraph(this);'>
<span class='name' style='font-size:10pt;height:5px;' value='$object'>$object </span>
<span class='data' style='background:$alarmColor;font-size:10pt;color:$alarmText;height:15px;'>$debitPrevMax</span>
</a>
<a class='info' id='$object' href='javascript:threshold(this)'>Alarm Info</a>
</li>
The list have split buttons.
"When I tried to access to element.id I get undefined"
When you do this...
href='javascript:threshold(this)'
...this is not a reference to the element. That's why the id is undefined.
You'd need to use onclick= instead.
onclick=':threshold(this)'
Also, as I stated in the comment above, you can not have duplicated IDs on a page. You'll likely only be able to fetch the first.
Even if you're not using them for DOM selection, it still isn't a good idea to have duplicates.

Categories

Resources