executing JS function and define variable from html - javascript

What I have is a page which is gathering a large list of data via jQuery. I am trying to limit the amount of results shown to a variable, and change the results shown on the list to create a false-page effect. Everything works via the same JS function, and relies on 1 variable to make everything work. Simple. I've removed all of the extra code to simplify everything
function myFunction() { var page = 1; console.log(page); }
I am looking for a way to call on this function, but change the variable 'page' from within html. Something along the lines of:
2
I have been looking on google (and still am) I just can't seem to find what I am looking for. I'm trying to avoid multiple pages/refreshing as this element is going to be used for a larger project on the same page.
UPDATE: I managed to pass the intended values through to a JS function like so...
function myFunction(page) { console.log(page); }
...and...
<input type='button' onclick='myFunction(value)' value='input page number'>
This seems the simplest way of doing what I need, what do you think?
Thanks for your help btw guys.

To do this you will need to move the page variable to be a parameter of myFunction
function myFunction(page) { console.log(page); }
Then you can just pass in whatever page number you would like
2

Sure, you can add the data-url attribute to your markup and select on the .link class to fetch the data-url attribute for each element thats part of that class.
I'm trying to avoid multiple pages/refreshing as this element is going
to be used for a larger project on the same page.
Sounds like you also want an AJAX solution.
$(document).ready( function()
{
//Add this on your call.html page
$(".link").click(function()
{
//location of test JSON file
var root = 'https://jsonplaceholder.typicode.com';
//your custom attribute acting as your 'variable'
var page = $(this).attr('data-url');
console.log("page = " + page);
//remove any previous html from the modal
$(".modal-content").empty();
//send a request to the server to retrieve your pages
$.ajax(
{
method: "GET",
//this should be updated with location of file
url: root + '/posts/' + page,
//if server request to get page was successful
success: function(result)
{
console.log(result);
var res = result;
var content = "<div class='panel-default'><div class='panel-heading'><h3 class='panel-title'>" + res.title + "</h3></div><i><div class='panel-body'>''" + res.body + "''</i></div><p><u> Master Yoda, (2017)</u></p><p class='page'> Page: " + page + "</p></div>";
$(".modal-content").html(content);
},
//otherwise do this
error: function(result)
{
$(".modal-content").html("<div class='error'><span><b> Failed to retrieve data </b></span><p> try again later </p></div>");
}
});
});
});
.error
{
border: 2px dotted red;
margin: 5px;
}
a
{
font-size: 20px;
}
.page
{
text-align: left;
padding: 0 15px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<a class="link" data-url="1" data-toggle="modal" data-target="#Modal" href="test.html">Show Page 1</a>
<br />
<a class="link" data-url="2" data-toggle="modal" data-target="#Modal" href="">Show Page 2</a>
<div id="Modal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>

I seem to have figured out how to do this. I wanted to stray from using lots of libraries in the project and just wanted to keep things simple, using the above answers for guidance (and a little more digging), basically my end goal was to use jQuery to obtain a long list of data, and format this data into a multiple page list (for which I used a table for formatting purposes). Let's say it's a list of names. The JSON results output as:
[{"first_name":"Bob"},{"last_name":"Jones"}] // (key, value)
But when I passed this through to the HTML Table it was just displaying 1000s of results in a single list, and formatting the list was a pain. This was my solution:
<script>
var pageNum = ""; // define Page Number variable for later.
var resLimit = 35; // variable to specify the number of results per page
function updateList () {
$.getJSON(" Location of JSON results ", function(data) {
var pageCount = Math.round(data.length/resLimit); // calculate number of pages
var auto_id = ((pageNum-1)*resLimit) // use variables to give each result an id
var newListData = ""; // define this for use later
then define and pass "new list data" to HTML Table:
var newListData = "";
$.each(data.slice(auto_id, (pageNum*resLimit)), function(key, value) {
auto_id++;
newListData += '<tr>';
newListData += '<td class="id">' + audo_id + '</td>';
newListData += '<td class="id">' + value.first_name + '</td>';
newListData += '<td class="id">' + value.last_name + '</td>';
newListData += '</tr>';
});
$('# ID of table, data will replace existing rows ').html(newListData);
At this point if you set the value of pageNum to 1 you should see the first 35 results on the list, all with auto-incremented ID numbers. If you change it to 2 and refresh the page you should see the next 35, with the ID numbers following on from the first page.
Next I needed to create a button for each of the pages:
$('# ID of table, data will replace existing rows ').html(newListData);
function createButtons() {
var buttonArray = "";
for(i=0, x=pageCount; i<x; i++) {
buttonArray += '<input type="button" onclick="changePage('
+ (i + 1) + ')" value="' + (i + 1) + '">';
}
$('# ID of Span tags for button container ').html(buttonArray); }
createButtons();
}); }
</script>
Then create changePage() and a function to refresh the data in the list automatically without messing things up
<script>
var pageNum = "";
function changePage(page) {
if (pageNum < 1) { pageNum = 1; } // set pageNum when the page loads
if (page > 0) { pageNum = page; } // overwrite pageNum when 'page' variable is defined
updateList(); }
changePage(); // initialise to prevent delayed display on page load
// refresh function:
function refreshData() {
changePage(0); // define 'page' as 0 so that pageNum is not overwritten
window.setTimeout(refreshData, 5000); } // loop this function every 5 seconds to
refreshData(); //-- keep this list populated with current data.
And that should just about do it! At least it's working for me but I might have missed something (hopefully not lol). Hope this helps someone theres quite a few things involved in this that could be extrapolated and used elsewhere :)
thanks for help everyone.

Related

How to prevent appending multiple times in the table, Once It forcing to double click multiple times the table row using Jquery?

I have module appending the result of response to the other table. looking forward I found a solution in my module. however I found problem on that i will give to you guys the scenario what the problem it does.
First Scenario:
User will choose what condiment he wanted to click, Looking forward Ex. User 1 choose the Second table row, the Condiments *LG FRIES.
Second Scenario:
In the first scenario user choose the *LG FRIES, as you can see here modal will open and the result of response will append to the table B.
Third Scenario: Well First and Second scenario look works and good, but here I will show you, how does appending will multiply in the table once i force double click the table row of *LG FRIES.
So now i will let you show my codes.
This is my function for getting the result of clicking the of table row then the result will append to the table B.
$('table#noun_chaining_order').on('click','tr.editCondiments',function(e){
var allow_to_open_condiments_conditional = $(this).closest("tr").find(".allow_to_open_condiments_conditional").text();
if(allow_to_open_condiments_conditional == 'Yes') {
$('.conditional_table_hidden_noun').hide();
$('.conditional_table_hidden_condiments').show();
$('table#noun_chaining_order tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_condiments = $(this).find('td.condi_section_id').text();
$("table#customer_table_update_chain_order tbody").html('');
$('#customer_modal_update_chain_order').modal('show');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#customer_table_update_chain_order tbody').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
},
error:function(response){
console.log(response);
}
});
}
else
{
}
});
So the question will be, How to stop appending multiple times once I force double click the table row?
I see simple solutions here.
When you appending cart item, you can add that item ID from database
to the element. And before appending check if an item from response
doesn't exist in BODY.
Another solution will be just after you click append - hide that CTA
(button)to prevent it from another click.
Check your database for multiple records.
Anyways, please check when you do ajax request? after click?
Have you tried to debug your code with breakpoints? or console?

How to add last.fm now playing into my site using Api

Hi guys i been trying to figure out for a long time but i suck at this, i found this code on google and i added it adn changed what i need but still doesnt work i really need this for my site: http://www.balkan-party.cf/
I found code here: http://www.samkitson.co.uk/using-json-to-access-last-fm-recently-played-tracks/
My last.fm username i need in js: alicajdin AND
Api key: 24f6b03517ad9984de417be5d10e150b
This is what i did:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=alicajdin&api_key=24f6b03517ad9984de417be5d10e150b&limit=2&format=json&callback=?", function(data) {
var html = ''; // we declare the variable that we'll be using to store our information
var counter = 1; // we declare a counter variable to use with the if statement in order to limit the result to 1
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
} // close the if statement
counter++ // add 1 to the counter variable each time the each loop runs
}); // close each loop
$('.listening-to h5').append(html); // print the information to the document - here I look for the h5 tag inside the div with a class of 'listening-to' and use the jQuery append method to insert the information we've stored in the html variable inside the h5 tag.
}); // close JSON call
});
I created that file and i tried to add on head section, footer section but it wont show recent tracks.
And yea i have scroblr installed on google crome
below </script> add the following code:
<div class="listening-to"></div>
then remove "h5" on
"$('.listening-to h5').append(html);"
so your code like this:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOUR_USERNAME&api_key=YOUR_API_KEY&limit=2&format=json&callback=?", function(data) {
var html = '';
var counter = 1;
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
}
counter++
});
$('.listening-to').append(html);
});
});
</script>
<div class="listening-to"></div>
Hope you can help. Sorry, my English is very Bad (Google Translate)

Retrieve specific data stored with JSON

I've used the code posted in THIS STACKOVERFLOW POST to build a prototype of a webbapp, but I can't make the second page show me the data with the format I want.
The code shows me the second page with all the data in a grid format, but I want to know how to make specific data with different formats (bold, italic, color).
For example, one string that I use is a "image.jpg" text to load an image of the user.
I've modified the first part of the code to:
$.each(info, function (i, valor) {
li += '<li><img src="img/'+ valor.foto +'"><h2><i>' + valor.cientifico + '</i></h2><p><b>Familia:</b> <i>'+ valor.familia +'</i> | <b>Subfamilia:</b> <i>'+ valor.subfamilia +'</i></p></li>';
});
to add specific values and apply different format (familia, subfamilia) and to insert the picture with the "foto" value.
Then the code continues:
$("#lista").append(li).promise().done(function () {
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
$("#resultado").data("info", info[this.id]);
$.mobile.changePage("#resultado");
});
$(this).listview("refresh");
});
});
$(document).on("pagebeforeshow", "#resultado", function () {
var info = $(this).data("info");
var info_view = "";
for (var key in info) {
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
$(this).find("[data-role=content]").html(info_view);
});
I know that the for (var key in info) is not what I'm looking for, but I don't know what code I have to use because I'm too new to unsderstand how to do it. How can I accomplish this?
The code next to info_view is HTML, right, but if I replace + key + with + familia + for example this doesnt works like before.
My question is how can I make to retrieve an specific data (for example the foto value) of the selected item listed in the first page? I want to be able to select wich items use. For example, I wanna make the id value invisible for the user, make the id value invisible, the name value in bold, and so on
Hope I was enough clear, sorry for my limited english and coding knowledge
Finnaly I've solved my own question.
For reference, what I do was deleted the
for (var key in info) {
and inside the info_view += part i've used info['value'] for each item I want to manipulate.
Hope this helps someone else.

Adding html while iterating over jquery object

Is there a better way of inserting somewhat complex html into a page other than the way I'm doing now? :
function display(friends) {
$(".row").empty();
$.each(friends, function(index, friend) {
var html = '<div class="profileImage" style="float:left;padding:20px; width:200px">';
html += '<a href="/app/click/' + friend.id + '">';
html += '<img id="' + friend.id + ' " src="https://graph.facebook.com/' + friend.id + '/picture?width=200&height=200 " />';
html += '</a>';
html += '</div>';
$(".row").append(html);
});
Currently I have a list of facebook friends which are styled nicely. When a user searches through the friends, the entire content block is emptied and the result is appended (i'm using autocomplete). However the design could change and get more complex so i'm looking for a scalable way of doing what I have above.
Instead of creating the html inside the javascript, is there a smarter way of doing this? Perhaps with $.load() and passing each friend as an argument? But that seems very slow and server intensive if you have to list 100 friends.
One good way to go would be to use a templating engine, handlebars (as mentioned in the prev answer) is one of them. You could create your own as well if your scenario is simple as this. And another key thing is not to use append inside the loop, instead construct them to a temp array and add it to the DOM in the end. If your list is big and appending to the dom in the array can be expensive.
Add the template html with a placeholder for friendId
<script type="text/html" id="template">
<div class = "profileImage" style = "float:left;padding:20px; width:200px">
<a href = "/app/click/{{friendId}}">
<img id = "{{friendId}}" src = "https://graph.facebook.com/{{friendId}}/picture?width=200&height=200 " />
</a>
</div>
</script>
And
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = [];
$.each(friends, function (index, friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
rows.push(templateHtml);
});
$row.html(rows); //Append them in the end
}
Demo
You could use $.map as well.
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = $.map(friends, function (friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
return templateHtml;
});
$row.html(rows);
}
A scalable solution would be to use a template engine and make the server returns JSON response.
Take a look at Handlebars.js http://handlebarsjs.com/

JavaScript/HTML/CSS - Multiple forms on one page

I'm trying to create a simple web page in JavaScript, HTML, and CSS. The web page generates 5 div elements. Each div element includes a random number, text input, and submit button. My code below does that.
The user then should be able to enter the random number into the text input box and click the submit button. The script should check if they entered the correct answer or not.
I'm not sure if this is possible? I understand how to write the code for just a single form on the page but this example is using 5 forms on a single page that are dynamically generated. Any help would greatly be appreciated.
<html>
<head>
<style type="text/css">
#test {
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
}
</style>
</head>
<body>
<script>
for (i = 0; i < 5; i++) {
document.write('<div id="test">');
var ranNum = Math.floor(Math.random()*10);
document.write(ranNum);
document.write("<p>Enter the number above:</p>");
document.write("<form id=\"form1\" name=\"form1\" method=\"post\" action=\"\"><input type=\"text\" name=\"answer\" id=\"answer\" /><input type=\"submit\" name=\"button\" id=\"button\" value=\"Submit\" /></form>");
document.write('</div>');
}
</script>
</body>
</html>
You don't even interact with the server to check if it was the correct answer.
So, yes, you can easily do that.
Use jquery, make those numbers properties to a global object, properties named after #id of your inputs, so when user clicks, just compare the value of input with the property of your global object with the same name.
eg:
window.myObject = {}
myObject.div1 = // your code for random number
myObject.div2 = // again, code for random number
And so on, even better put your random number code into a function and call
it for each property.
then just set the divs values as properties:
$("div.div1").append("<span class='value'>" + myObject.div1 + "</span>");
Or maybe even you could create a loop to do it so you don't need to type it for all divs.
After that, test your inputs:
$("div.div1").find("submit").click(function(){
// here you collect the data from your form, lazy to type
// and test it for equality with coresponding myObject.div1
// or with the value in <span class="value>
//e.g.
if ($(this).parent().find(".mytextinput").val() == $(this).parent().find("span.value").val())
{ //do something} else {//do something else }
});
Of course, this presumes you can use jquery.
as has been pointed out in the comments, make sure id's are always unique. I wouldn't use ajax for something this simple, you can check the values client side. See below for a working solution.
for (i = 0; i < 5; i++) {
document.write('<div id="div-' + i + '">');
var ranNum = Math.floor(Math.random()*10);
document.write(ranNum);
document.write("<p>Enter the number above:</p>");
document.write("<form id=\"form-" + i + "\" name=\"form-" + i + "\"><input type=\"text\" name=\"answer\" id=\"answer-" + i + "\" /><input type=\"submit\" name=\"button\" id=\"button-" + i + "\" value=\"Submit\" onclick=\"checkAnswer(this); return false;\"/></form>");
document.write('</div>');
}
function checkAnswer(element) {
var thisAnswer=element.form.parentElement.textContent.substring(0,1);
var answerGiven=element.form.children[0].value;
if (thisAnswer==answerGiven) {
alert("correct!");
} else {
alert("wrong!");
}
}

Categories