This question already has answers here:
JQuery Update data- attribute/value
(3 answers)
Closed 4 years ago.
You're probably going to tell me to just do this all in jQuery, but I'm asking anyway.
I have an animation library that uses a counter to count from 0 to X. This was part of an HTML template I don't really want to modify.
I have built an AJAX script to GET the data I need to count to from a RESTful API source. Yes, I know, the api-key (secret) is still there, but there's no sensitive data and I'll cycle it after we're done here.
This HTML properly displays the value, but I can't for the life of me figure out how to get the value of the jQuery var $numClients into the "data-to" attribute.
Can anyone help me figure this out? I was hoping I could just reference the variable like "data-to=$varFromQuery" but I am a backend guy, not a JS guy, so I'm totally lost on this.
$(document).ready(function() {
$.ajax({
url: "https://path.to.url"
}).then(function(data) {
$('.totalTransferredGB').append(data.totalTransferredGB);
$('.numClients').append(data.numClients);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="counter-item">
<span class="counter-number numClients" data-from="1" data-to="WHAT DO I PUT HERE" data-speed="20"></span>
<span class="counter-text">Unique Devices Connected</span>
</div>
EDIT:
I ended up solving it with the following code:
...then(function(data) {
document.getElementById('totalGB').innerHTML=data.totalGB;
document.getElementById('totalGB').setAttribute('data-to',data.totalGB);
document.getElementById('numUsers').innerHTML=data.numUsers;
document.getElementById('numUsers').setAttribute('data-to',data.numUsers);
document.getElementById('numClients').innerHTML=data.numClients;
document.getElementById('numClients').setAttribute('data-to',data.numClients);
});
You can use the data() method to update a data attribute on an element:
$(document).ready(function() {
$.ajax({
url: "https://store.zapier.com/api/records?secret=5226d37cd13b40edbb97036f523d0a4e"
}).then(function(data) {
$('.totalTransferredGB').append(data.totalTransferredGB);
$('.numClients').data('to', data.numClients);
// for testing:
console.log($('.numClients').data('to'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="counter-item">
<span class="counter-number numClients" data-from="1" data-to="WHAT DO I PUT HERE" data-speed="20"></span>
<span class="counter-text">Unique Devices Connected</span>
</div>
One caveat with this is that it does not update the DOM. The data is stored in an in-memory object which jQuery creates for better performance. If you require the data-to attribute within the DOM itself to be updated then you would need to use attr() instead:
$('.numClients').attr('data-to', data.numClients); // set the value
var numClients = $('.numClients').attr('data-to'); // get the value
Related
This question already has answers here:
How can I get the data-id attribute?
(17 answers)
Closed 3 years ago.
Im trying to write a little filter script for a ajax-table and im trying to open a overlay when someone clicks on the element:
<div class="at-filter" data-filter-val="{some_value}" data-filter-type="{some_type}">
...
</div>
How do i access the data-filter-type and value via javascript/jquery? Cant find anything at all via google.
Something like this is what im looking for:
this.table.find( '.at-filter' ).each(
function(index, element) {
var type=$(element).data-filter-type();
var val=$(element).data-filter-val();
self.data.filter[type] = {};
$(element).bind('click', {self:self, val:val, type:type}, type.openContextMenu);
}
)
edit: Mistakes were made!
To get attrbiute value use jquery attr() or in plain JavaScript getAttribute
But
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
Or
In plain JavaScript setAttribute
console.log($('.me').attr('data-attribute'));
console.log($('.me').attr('data-second-attr'));
$('.me').each(function() {
console.log(this.getAttribute('data-attribute'));
console.log(this.getAttribute('data-second-attr'));
this.setAttribute('data-second-attr', 'foo-bar');
console.log('after change', this.getAttribute('data-second-attr'));
})
$('.me').prop('data-attribute', 'baz')
console.log('after change', $('.me').prop('data-attribute'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="me" data-attribute="foo" data-second-attr="bar">yo</div>
You use attr:
var type = $(element).attr("data-filter-type");
You could also use data:
var type = $(element).data("filter-type"); // Read the note below, though
... but it isn't necessary or really appropriate if all you want to do is access the values of those attributes. Contrary to popular belief, data is not an accessor for data-* attributes. (It's both more and less than that.)
I am counting my user specificated and dynamically appearing divs...
My situation:
<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">
<div id="streamcontainer1" class="streamcontainer grid-stack-item" data-bind="attr: {'data-gs-x': $data.x, 'data-gs-y': $data.y, 'data-gs-width': $data.width, 'data-gs-height': $data.height, 'data-gs-auto-position': $data.auto_position}">
</div>
</div>
In PHP i can simply write my COUNT variable inside the html. That would look something like this:
<div id="streamcontainer<?php echo $count ?>" class="" ... and so on...>
How can i archive the same with JS/Jquery?
It's a DOM manipulation question. What do we have to work with? We're adding divs to the page, they have a particular class, and we want to give them an ID.
function assignIds(){
var list = document.getElementsByClassName('streamcontainer');
for(var i=0; i<list.length;i++){
if(list[i].id == undefined) // skip the ones that have already been done.
list[i].id = 'streamContainer' + i.toString();
}
}
Now we just have to run that function on some event so it will keep updating. If you just want to do it on an interval, that's simplest. (setInterval) But that could give you a bug, where there's a small amount of time where that ID hasn't been assigned yet. You could try listening to whatever AJAX/websocket process is streaming these things onto the page.
We'd need to know a bit more about your use case to know which event to attach it to.
Without a Javascript Reactive Framework (Vue.js, React, AngularJS) you can't do this.
What you can do with JS is set a content in element when DOM is loaded, example:
document.getElementById("myElement").textContent = "Hello World!";
Or
document.getElementById("myElement").innerHTML = "<span>Hello World!</span>";
OBS: .innerHTML can insert HTML tags and .textContent just insert texts.
You can make use of the text bindings in knockoutjs to display the javascript value in the HTML. There are lot of ko bindings which can help you. More reference here
var viewModel = {
javascriptVariable: "I am javascript string"
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: javascriptVariable"></span>
I'm a beginner programmer and I'm building a game. Whenever the player clicks on the gold image, he should get 1 gold. So I have the following HTML piece of code:
<li id="gold">Gold: 0</li>
That's the starting gold, and through JQuery I update that with:
$('#gold-image').click(function() {
gold++;
$('#gold').replaceWith('<li id="gold">Gold: ' + gold + '</li>');
});
But I don't feel that's the best way to update how much gold the player has. Is there a way that I can write in the HTML to update the variable whenever it's being changed or something like that without having to replace that whole item?
Later in the game there will be many functions running at the same time and increasing the gold number, so I think replacing HTML code is not the optimal way.
Try this with your existing div <div id="gold">Gold: 0</div>:
$('#gold-image').click(function() {
gold++;
$('#gold').html('Gold: ' + gold);
});
Although the above code would work. I would NOT use jQuery for something like this. There are other frameworks which would be way better for such applications. For example you can take a look at AngularJS or Ember.
The same functionality can be achieved using the two-way binding with AngularJS.
1) the markup:
<div controller="GameCtrl">
<img src="/path/to/img.png" ng-click="goldClicked()">
<div>Gold {{ gold }}</div>
</div>
2) the javascript code
app.controller('GameCtrl', function($scope) {
$scope.gold = 0;
$scope.goldClicked = function() {
$scope.gold += 1;
};
});
The code is very very simple and you do not need to deal with selectors. Every time you change the gold (or any other variable) it will automatically be updated in the DOM. You will automatically get modular code and dependency injection. In addition you will write everything declaratively and your code will be much easier to read and easy to change in future.
UPDATE: Here is a working AngularJS fiddle: http://jsfiddle.net/absolutemystery/7WgYK/
Or, using a div only around the number (e.g., <div id="gold">0</div>),
$('#gold-image').click(function() {
$('#gold').html(++gold);
});
You could user Ember.js for this kind of thing. Ember.js its a MVC javascript library.
In this case:
<li id="gold">Gold: {{YourController.goldAmmount}}</li>
and them in your controler you only have to call the function updateAmmount():
var YourController= Em.ArrayController.create({
goldAmmount : 0,
updateAmmount : function(){
this.goldAmmount++;
}
})
If you can add a <span> element it would make it a little cleaner:
HTML:
<li>Gold: <span id="gold">0</span></li>
JAVASCRIPT:
$('#gold-image').click(function() {
gold++;
$('#gold').text(gold);
});
You can use custom events for that. Everytime gold value updates, you can trigger an event, passing an argument, for example:
$('#gold-image').click(function() {
gold++;
jQuery.event.trigger({type: "onGoldUpdate",val:gold});
});
After that, you can be always listening to that event and do whatever you want with this information, like this:
jQuery(document).on("onGoldUpdate", function(e){
var goldValue = e.val;
jQuery('.gold .value').html(goldValue);
});
And on HTML part, you can put a span around the value:
<li id="gold">Gold: <span class="value">0</span></li>
You could use a simple MVVM solution for your needs, for example Knockout.js. You can create a model and bind it's values to a place in your html and anytime you update a value in the model the rendered html is automatically updated without your interference. Quick example of how you could use it here...
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<script>
function PlayerModel() {
// the player score
this.playerGold = ko.observable(0);
// The increase gold function to add 1 to the player score
this.increaseGold = function() {
var oldScore = parseInt(this.playerGold());
this.playerGold(++oldScore);
};
}
var model = new PlayerModel();
$( document ).ready(function() {
ko.applyBindings(model);
});
</script>
</head>
<body>Gold : <strong data-bind="text: playerGold"></strong></li>
<button onclick="javascript:model.increaseGold()">Standard JS - Increase gold</button>
<button data-bind="click: increaseGold">KO Data bound -Increase gold</button>
</body>
</html>
Its as easy as that. You can add more variables easily to your player model then if you want. I like this approach because it keeps things easy but also affords you a lot of control over the implementation etc. Ember is another great alternative though.
I'm having some difficulty getting this to work. What I want to do is take dynamic variables from the onclick and place them into a div I am appending to another div in the document. Since each each item will have variables associated from a database query, I figured populating the buildTicket() variables from the database would be easier.
I know I'm doing something wrong. I just can't figure out what.
If you have a better way, I'm all ears.
Here is my javascript:
<script type="text/javascript">
$(document).ready(function(){
$(function() {
buildTicket = function(eventname,ticketprice,venueid,userid) {
$(".ticketbtn").click(function(){
$(".ticketwindow").append("<div class='ticket'>" + eventname + " - " + eventprice + "</div>");
});
}
});
</script>
Here is my HTML:
<div class="ticketbtn" onclick="buildTicket('Some Show','12.00','1','2');">
<img src="assets/images/tixicon.png" alt=""> <div class="eventname">Some Show</div>
<div class="ticketprice">Adult - 12.00 </div>
</div>
<div id="ticketwindow">
</div>
Can someone help me figure this out?
(sorry for the code formatting. Still trying to figure out how to use stackoverflow's forms properly.)
Thanks,
Joe
Firstly, $(function() { is equivalent to $(document).ready(function() { so you only need one of them.
Secondly, you don't need to use the onclick attribute if you are binding to click() with jQuery, or vice versa.
If you just use the onclick attribute, then you can remove your document ready handler, and your click() binding, all together and simply define the buildTicket() function.
Thirdly, the eventprice variable is misnamed in buildTicket().
Here is a working fiddle, using jQuery to bind to the click event of your button div. http://jsfiddle.net/BdJAL/
You are binding the onClick listener on click of your button.
If you must use the onClick element attribute then the following code will work although you should become familiar with the principles of Unobtrusive JavaScript.
$(document).ready(function(){
var buildTicket = function(eventname,ticketprice,venueid,userid) {
$("#ticketwindow").append("<div class='ticket'>" + eventname + " - " + eventprice + "</div>");
});
});
I quote from your question:
"I figured populating the buildTicket() variables from the database would be easier."
If you want to get hold of database data in your JavaScript how about making an HTTP request to get it. Obviously, you could do this in the normal XJAX way using XMLHttpRequest:
http://www.w3schools.com/xml/xml_http.asp
Or you could call up some server side code to produce JSON for you and reference it in a <script> tag e.g.
<script type="text/javascript" src="../js/jsonFromServerSideCode.jsp"></script>
I want to get text from Nested SPAN element in Following HTML code:
<span id='result_box'>
<span class="hps">text_content</span>
</span>
I want to get "text_content" value using JavaScript.
I have tried this but have a problem:
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);
EDIT: Actually i want to do this from Online Page
your code works fine. i guess your problem is you are executing these code when DOM not loaded completely.if you are testing something, you can try this.
window.onload = function () {
//put your code here,it will alert when page loaded completely.
};
or put the script after your span element. like this.
<span id='result_box'>
<span class="hps">text_content</span>
</span>
<script type='text/javascript'>
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);// it will alert
</script>
you get the element by classname.. document.getElementsByClassName() and then grabbing the first item off the resulting node list
window.onload = function () {
document.getElementsByClassName("hps")[0].innerHTML
};
jsfiddle
var resBox=document.getElementById('result_box');
var strTrans=document.getElementsByTagName('span')[0].innerText;
alert(strTrans);
or better
strTrans = document.querySelector(".hps").innerText ;
got you, i guess you embed a link in your html page,then you wanna manipulate DOM in the page you embed,right? if so, you can check browser same origin policy.
if you wanna implement online translation via google, you can google 'google translate api', google provides a api to others for implementing online translation in their own applications.
it seems like bing also provides a api.i'm not sure.