I have here a jQuery calculator script that allows me to calculate the values (of a specific css class) for input boxes in each row.
I have 8 rows total, with plans to allow users to dynamically add rows in the future.
My problem is not knowing how jquery library works in it's full potential. I'm not even sure if what I'm requesting is possible, but I tried looking around and couldn't find much,
$(function(){
$('specific-class').each(function() {
$(this).keyup(function(){
calculateTotal($(this));
});
});
});
function calculateTotal(src) {
var sum = 0;
var sumtable = src.closest('tr'); //only calculate the current row
sumtable.find('specific-class').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
sumtable.find(".qty").html(sum.toFixed(0)); //send to front
}
So with the above complete, I will be able to check each individual TD with the specific class and add the values together.
How do I go about storing the values of each row that gets calculated and then sending the stored variables as their own qty such as qty1,qty2,qty3 etc..?
Thank you SO Community you've been a huge help to my many questions.
The only way you can send data from jquery to PHP is using $.post or $.get.
You can post you data to the same file that called it, or some separate file which has the function to manage your data.
My preferred is the second one. Keeps you project modular.
Related
I had implemented multiple checkbox filtering for a job portal using jQuery where in I was calling a function every time a checkbox is checked and that function contained an ajax call which would send the request with the checked values and I would do the querying of database and return the result.
But one of the developers I meet told me you should not hit the database continuously for filtering, it should be done client-side.
He also suggested to use AngularJS or Knockout(js) for the purpose, as they work on content, whereas jQuery works on DOM elements.
But if it has to be done client-side, all of the data must be loaded at once during the first visit to the page, which in turn would slow down the page.
And I cannot use class on each element and show/hide them based on the checkbox ID or value something like that, because there are a lot of checkboxes, which I think will be hectic to handle.
How to achieve the desirable result with good performance?
I'm a Newbie to jQuery, so if I have gone wrong anywhere bear with me.
Below is the sample way in which I have actually done:
HTML:
<input type="checkbox" name="location[]" value="Bangalore" onclick="loadresult()">Bangalore
JS:
function loadresult() {
location array value accessed and passed to ajaxcall
//ajax call to processresult.php
Displaying the DB returned Data
}
PHP (processresult.php):
<?php
//dbconnection + querying db and returning result
?>
There is significant difference. Angular is a framework and jQuery is a library.
With jQuery it much simpler to modify DOM elements deal with events and do some more cool stuff. But you define how you deal with data on your own. You can easily move your data to Js object or array of objects and render this data to your DOM tree.
For example:
//let's presume that you are searching something
var someUsers = [{id: 1,name:'User 1'},{id: 2,name:'User 2'},{id: 1,name:'User 3'}];
var usersTemplate = _.template("<h1>User name: <%= user.name %></h1>");
var $container = $('#someRenderContainer');
someInputFeild.on('keypress', function(){
var searchText = someInputFeild.text();
var foundUsers = someUsers.filter(function(item, index){
item.name.indexOf(searchText) !== -1
});
render($container,foundUsers);
})
function render($container,users){
users.forEach(function(item){
$container.append(usersTemplate(item));
})
}
Here is simple example where you can see that your manipulate with data in the memory but not in DOM. Similar things you can do with your checkboxes.
I would just make one ajax request in the beginning, fill the page with data, marking every row with class name
jQuery.each(d, function(i,data) {
$("table.content").append("<tr class=\""+data.city+"\"><td>" + data.tag + "</td><td>" + data.city + "</td><td>" + data.num + "</td><td>" + data.state + "</td></tr>");
});
and use checkboxes to hide and show marked rows using jQuery hide(), show() methods.
Rows can have multiple classes meaning filtered by multiple columns, but logic will get more complicated.
see example http://jsfiddle.net/elshnkhll/czdongkp/
I would use cache technique to improve my performance.
We can't load our full record on a single page. It will slow down the main page loading.
But we can save loaded data in a variable with some key combination for different filter and page no..
eg. if we are loading data fir index page with no filter, the my key will be index and my variable will be like var cachevar = {"index":{1:"<my response>"}}, here "1" is page number
And if data is using filter, then my variable index key will be combination of filter ids saperated by '-'.
eg var cachevar = {"index":{1:"<my response>"}, "index-2-5-3":{1:"my response"}}
If user request a page, I just have to check if that page is available in cache or no, if it's available in cache variable, then show it, else request it from server.
I have a brand list with about 2000 items, my problem is I want to generate a list of commands In jquery using this format dynamically.
$("select[name='brand']").change(function () {
$("#brand1,#brand2").hide();
if ($(this).val() == "brand1") { $("#brand1").show(); }
else if ($(this).val() == "brand2") { $("#brand2").show(); }
and so on...
});
the list of brands is located in MySQL which I brought into an array called
allBrands[] in php
so if the brands update in the MySQL, it will also update in the jquery script.
Obviously I can manually type in each brand, but i'm worried about when I update the database for newer brands etc..
Edit: that being said, if I can do a MySQL call in jquery and get the list of brands that way, that would also work. Brand1, brand2 = examples, names are random based on brand
If the data is ordered in the same way your 2 examples suggest you could try this:
$("select[name='brand']").change(function () {
$("[id^=brand]").hide(); // all id's starting with the word "brand"
$("#" + this.value).show(); // if the value is the same as the id you want to target
});
About the jQuery ^=, read here.
If the brands do not start with the word brand you can use $(".brands").hide();, and use the rest as I posted.
I'm working on a project that involves returning the id of the checkboxes chosen as well as the text in the corresponding textarea fields for those chosen checkboxes. The data is dynamically displayed and so far my jquery pull of both the checkboxes and textareas work:
var noteList = $("textarea[name='revokeNotes']").map(function(){
return this.value;
}).get().join();
var revokeList = $("input[name='revoke']:checked").map(function(){
return this.id;
}).get().join();
but I'm getting back all of the notes fields and I'm uncertain how to best iterate through them to find the proper notes as their ids aren't sequential but rather based on their id in the table they are being pulled from. The last version of the display code is below:
<td><textarea name=\"revokeNotes\" id=\"".$v["id"]."\" cols=\"30\"rows=\"3\">".$v["notes"]."</textarea></td>
<td><input type=\"checkbox\" id=\"".$v["id"]."\" name=\"revoke\" value=\"".$v["id"]."\" /></td>
Is there a way to reach my goal from this state or should I be using another jquery function, similar to .map()? I thought about using the id field from the checkboxes to iterate through the selected notes and pushing them into an array but I'm not sure 1) if that will work and 2) how to do that.
I need the data back in some form either an array or something I can explode on in php to create an array as I'm passing one value in ajax as there is no set maximum or minimum number of rows that will be displayed per user. Map was working until I threw some commas at it. Extra points for that.
var noteList = $.map(
$("textarea[name='revokeNotes']").filter(function() {
return $(this).closest('td')
.next('td')
.find('input[type="checkbox"]')
.is(':checked');
}), function(el) {
return el.value;
}).join();
adeneo's answer is great, I'd just propose the following improvements:
If possible use class selectors (like '.revoke-notes-area') since those are faster than DOM + attr selectors
Assuming this is a table and there is one textarea checkbox combo per row, you can traverse the tree to the closest <tr> a decouple the JS from depending that the checkbox comes after the text area in the DOM.
var filterMethod = function() {
$(this).closest('tr').find('.revoke-checkbox').is(':checked');
};
var mapMethod = function(el) {
return el.value;
};
var nodeList = $.map($('.revoke-notes-area').filter(filterMethod), mapMethod);
There's no reason you cannot or should not put the filter and map methods inline, I just split them out into variables so it's easier to read here.
You can check out my codepen here: http://codepen.io/aaron/pen/eIpby.
A bit of a random exercise but I want to take content from an existing table and create a new table based on the entries taken.
In the image above, the table on the left is what I have to work with already. The blue table on the right is what I want to create; using the data from the table on the left.
Can this be done with jQuery or some basic PHP?
If you're wondering why I'm doing this its because I don't have access to the SQL database and I want to use Google Charts API to display total number of user registrations for each month.
As always, your help is MUCH appreciated.
Using JQuery it can be done in this way
//initialize monthArray
var monthArr = [{month:'April', occ:0}, {month:'May', occ:0},{month:'June', occ:0}];
//read occurrences for MonthNames in your existing table
$.each(monthArr, function(n,i){
var _occ = $("td:contains('"+monthArr[n].month+"')").size();
monthArr[n].occ = _occ;
});
// create new table and show the values
$.each(monthArr, function(index, value) {
//alert(value.occ+ ': ' + value.month);
$('#inTable').append('<tr><td>'+value.month+'</td><td>'+value.occ+'</td></tr>');
});
Here is fiddle: http://jsfiddle.net/A3WeJ/38/
Note: Table look and feel formatting has not been done in this solution
The question of whether or not you wish to use jQuery or PHP depends on whether the content of these tables is likely to change after the page has loaded. If the page will not change, you should use PHP.
Assuming the table is produced using a while or foreach loop, you can simply set up counts for each option that you have in the table. Within the loop, if you check what is in this column and add to an appropriate arbitrary count, you can count how many are in each.
It would probably be good to check what the contents is, and if it's already in your array.
Hope that provides some initial help to the thinking behind this question!
You may try this (You didn't provide more information, so just may be an idea)
HTML The id maintable could be changed with another id/class or just table
<table id="maintable">
<thead><th>Name</th><th>Join Month</th><th>Join Year</th></thead>
<tbody>
<tr><td>Joe Blogs</td><td>April</td><td>2012</td></tr>
<tr><td>Mr. X</td><td>April</td><td>2012</td></tr>
<tr><td>Andrew Xmen</td><td>April</td><td>2012</td></tr>
<tr><td>Matt Bblogs</td><td>may</td><td>2012</td></tr>
<tr><td>Malcom McGuiness</td><td>June</td><td>2012</td></tr>
<tr><td>Friday Needavodka</td><td>June</td><td>2012</td></tr>
</tbody>
</table>
<div id="myTblDiv"></div>
JS
$(function(){
var rows={};
$('table#maintable tbody tr').each(function(){
var item=$('td:eq(1)', $(this));
if(rows.hasOwnProperty(item.text()))
rows[item.text()]=parseInt(rows[item.text()])+1;
else rows[item.text()]=1;
});
var myTable=$('<table />', {'id':'myNewtable', 'class':'table table-striped'});
var th=$('<thead><th>Total</th><th>Month</th></thead>');
var tbody=$('<tbody></tbody>');
myTable.append(th).append(tbody);
$.each(rows, function(k, v){
var row=$('<tr><td>'+v+'</td><td>'+k+'</td></tr>');
myTable.find('tbody').append(row);
});
$('div#myTblDiv').append(myTable);
});
DEMO or Different Style.
Notice, I've used an id (maintable) for the table generated by google, in this case you have to change the id or class (if it has any) or even you can just use table without any id or class name but make sure there is only one table when you are using only $('table'), also if you can wrap the table within a parent div then you can use $('div#parentDivId table').
Ok I have a table that changes the displayed text once clicked on like the one displayed on http://www.w3schools.com/ajax/ajax_database.asp
I'm trying to update it based on each click.
For example.
Page Load > Load news article 1
onClick 1 > Load news article 2
onClick 2 > Load news article 3
All I want is for it to change based on each click, to a subsequent value. I have a php mysql database script that will pull the data from the database each time called.
The real question: Should I program the php to return a new table data cell with the new
oncLick="showNews($next_number)"
or should I leave that up to the AJAX, before it requests the information, just +1 it up.
I'm new to AJAX programming and not that experienced in PHP. I have searched everywhere and apologize if this is a redundant question. Just point me in the right direction.
write a php function to support to get the content by id. showNews(news ID). and then pass the newid with the ajax request. no need to change the newsid in the PHP.
I'm guessing something like this would be simplest:
var article = 0;
function showNews(){
get_article(article);
// magic
article+=1;
}
To be honest, just pick the way which seems more natural to you. Unless this is only a small part of something huge, it won't matter.
if I understood right, you want to get the next news when clicking on your button...
I suggest you to use jQuery for Ajax request...
It could be like this:
<script type="text/javascript">
$(document).ready(function(){
var result = 0;
$('#myButton').click(function(){
$.post('phpfunction.php',result,function(r){
$(document).append(r);
});
result ++;
});
});
</script>
And in PHP:
<?php
$result_id = $_POST['result'];
//SELECT * FROM WHERE id = $result_id;
?>