I am building an invoice system, where I will use jQuery, to update fields.
I was thinking to pull the price, and description for the number (if available), and put them into the textfields, thus making it easy to change, if there should be some 'at-the-counter' adjustments to the invoice.
The html code looks like this:
<table>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
</table>
The jQuery code, which is the part I am not so familiar with, looks like this:
$(document).ready(function() {
$(".partNo").keyup(getInfo);
});
function getInfo(){
var row = $(this).parents('.item-row');
var partNo = row.find(".partNo").val();
row.find(".description input")
.load("script.php", {vorunr: $(".partNo").val(), type: "desc"});
row.find(".price input")
.load("script.php", {vorunr: $(".partNo").val(), type: "price"});
}
This code works fine, the file script.php returns the values from the database.
My problem is that, all my table rows are updated, when I edit the first partNumber input field.
Can someone help me out?
you are using the selector ".partNo" many times but I see no html dom element with a class of "partNo". I see a input field with the name "partNo".
so bind the keyup event to
$('input[name="partNo"]').keyup(getInfo);
Also, here is my suggested solution for your getInfo function...
function getInfo(){
var row = $(this).parents('.item-row');
var partNo = $(this).val();
row.find(".description input")
.load("script.php", {vorunr: partNo, type: "desc"});
row.find(".price input")
.load("script.php", {vorunr: partNo, type: "price"});
}
Try using .closest() instead of .parents(). Also, you don't have a class named "partNo", just an input under the td with class "partNumber" (maybe try $('.partNumber input').keyup(...);
Also, you may want to look into json_encode and populate the fields with a single query to script.php instead of a couple of loads. You could do:
script.php
<?php
$partNo = $_GET['vorunr'];
// perform query to gather the data and populate $dbrow
header('Content-Type: application/json'); // make sure browser knows what it is
echo json_encode(Array(
'desc' => $dbrow['description'],
'price' => $dbrow['price']
));
?>
then use something like
$('.partNumber input').keyup(function(){
var row = $(this).closest('.item-row');
var partNumber = $(this).val();
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{vorunr:partNumber},function(data,textStatus,xhr){
$('.description input',row).val(data.desc);
$('.price input',row).val(data.price);
});
});
EDITv2
Here's a sample (Self-sufficient) file you can run and see what I mean.
<?php
// handle the ajax query
if (isset($_GET['vorunr'])) // make sure you validate this variable; I'm not doing so for the sake of demo.
{
header('Content-Type: application/json');
echo json_encode(Array(
'desc' => $_GET['vorunr'],
'price' => sprintf('%0.2f',rand(100,99999)/100)
));
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Ajax Sample</title>
<!-- MAKE SURE YOU DON'T USE THIS REFERENCE IN PRODUCTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="Text/javascript">
$(document).ready(function(){
$('.partNumber input').keyup(function(){
var row = $(this).closest('.item-row');
var partNumber = $(this).val();
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{vorunr:partNumber},function(data,textStatus,xhr){
$('.description input',row).val(data.desc);
$('.price input',row).val(data.price);
});
});
});
</script>
</head>
<body>
<table>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
</table>
</body>
</html>
Related
I have found a very nice jQuery script that helps me to get values from checkboxes sent to the URL as an array. This works perfectly, but I need the page to refresh after each selection, but by doing this, the checkboxes uncheck in Google Chrome (works fine in FF). The URL keeps fine, but the checkboxes all uncheck.
Is there any way in jQuery to keep the checked checkboxes checked after a refresh? Normally for me, when wanting a checkbox to be checked after a post or refresh, I can use an if-statement within the checkbox that i.e. says if($_GET[selected] == $value){ echo "checked"; }
You can test the code here: http://mazey.dk/bato/temp.php
The code looks like this:
<?
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Konfigurator</title>
<link rel="stylesheet" href="main.css" />
<style type="text/css">
body,td,th {
font-family: Tahoma, "Titillium Web", sans-serif;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
</head>
<body>
<div class="flowers">
<?
$hent_access = mysql_query("SELECT * FROM bato_produkter WHERE typen = 2");
while($hent_access_data = mysql_fetch_array($hent_access)){
$erstat2 = str_replace('BATO','bata',$hent_access_data[navn]);
?>
<div class="flowers">
<label>
<table width="100%" border="0" cellspacing="0" cellpadding="0" >
<tr>
<td><img src="images/<?=$hent_access_data[vnr]?>.jpg" width="150" class="apply_image" /></td>
</tr>
<tr>
<td class="product_list_header"><?=$erstat2?></td>
</tr>
<tr>
<td class="product_list_header">kr. <?=$hent_access_data[pris]?></td>
</tr>
<tr>
<td class="product_list_header"><input type="checkbox" name="selected[]" value="<?=$hent_access_data[vnr]?>" /></td>
</tr>
</table>
</label>
</div>
<?
}
?>
</div>
<script>
$('input[type="checkbox"]').on('change', function(e){
var data = [],
loc = $('<a>', {href:window.location})[0];
$('input[type="checkbox"]').each(function(i){
if(this.checked){
data.push(this.name+'='+this.value);
}
});
data = data.join('&');
$.post('<?=$actual_link?>', data);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?cart=<?=$_GET[cart]?>&'+data);
location.reload();
}
});
</script>
</body>
</html>
---- EDIT ----
After reading the comments and researching for a while, I am now trying to do it all through jQuery and AJAX calls, as I can read would be the most correct to do (and I get to learn something entirely new). So this is what I've got so far:
<form action="" method="post">
<?
$hent_access = mysql_query("SELECT * FROM bato_produkter WHERE typen = 2");
while($hent_access_data = mysql_fetch_array($hent_access)){
$erstat2 = str_replace('BATO','bata',$hent_access_data[navn]);
?>
<label>
<table width="100%" border="0" cellspacing="0" cellpadding="0" >
<tr>
<td><img src="images/<?=$hent_access_data[vnr]?>.jpg" width="150" class="apply_image" /></td>
</tr>
<tr>
<td class="product_list_header"><?=$erstat2?></td>
</tr>
<tr>
<td class="product_list_header">kr. <?=$hent_access_data[pris]?></td>
</tr>
<tr>
<td class="product_list_header"><input type="checkbox" name="selected[]" value="<?=$hent_access_data[vnr]?>" /></td>
</tr>
</table>
</label>
<?
}
?>
</form>
<script>
var data = $("form").serialize();
var checked = []
$("input[name='selected[]']:checked").each(function ()
{
$.ajax({
url: "hello.php",
type: "POST",
async: true,
cache: false,
data: data,
success: function(data){
alert(data)
}
});
});
</script>
The hello.php file looks like this:
<?php
include('../settings.inc.php');
foreach ($_POST[selected] as $value) {
$list_valg = mysql_query("SELECT * FROM bato_produkter WHERE vnr = '$value'");
$list_valg_data = mysql_fetch_array($list_valg);
$pris += $list_valg_data[pris];
$space_used += $list_valg_data[funktion];
}
echo $pris." - Space used ".$space_used."<br/>Total Space available ".$vogn_space;
?>
Now I've gotten the alert to show me the result, but only when I refresh the page manually (CTRL+R), and furthermore it loads an alert-box for every checkbox checked.
What I am trying to accomplish right now, is for the alert box to show the results from hello.php when checking a checkbox, but only once with all the checkboxes accumulated.
----- EDIT -----
Everything now works like I wanted it to, so that's absolutely perfect!
As an extension I have one more thing:
If you look at the site - http://mazey.dk/bato/temp.php
When you have picked the first item with the radio button the checkboxes show. When you check a checkbox you can see in the upper left hand corner the status of the selection and also the space availible. For the products with the checkboxes they all require a certain amount of space. Visually it is displayed in the last part of the text (1/3, 2/3 or 1/1) but it is also stored in a table row for every product (stored as integers; 1,2,3).
Can you lead me on the way in how to accomplish the products + checkboxes to be hidden if the products space exceeds the space available?
Thanks a bunch!
You are iterating through the selected boxes on page load instead of on the change event.
You have 2 options, a submit button or post every time a checkbox is clicked.
You mentioned you wanted to wait until all checkboxes are done being checked, but the script will never know that the user is done clicking checkboxes unless you have a submit button. However, in this case you don't want a submit button according to your question.
The following will post the selected values upon clicking the checkboxes on or off. The event will be fired each time a checkbox is manipulated and your returned data can be used to manipulate a table or it can return HTML. In this example its returning the data as HTML from hello.php which then places that response in a div element with the id of "result"
<form action="" method="post">
**** ADDED FOR NEW QUESTION ****
<input type="hidden" id="totalSpaces" value="12">
<?
$hent_access = mysql_query("SELECT * FROM bato_produkter WHERE typen = 2");
while($hent_access_data = mysql_fetch_array($hent_access)) {
$erstat2 = str_replace('BATO','bata',$hent_access_data[navn]);
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" >
<tr>
<td><img src="images/<?=$hent_access_data[vnr]?>.jpg" width="150" class="apply_image" /></td>
</tr>
<tr>
<td class="product_list_header"><?=$erstat2?></td>
</tr>
<tr>
<td class="product_list_header">kr. <?=$hent_access_data[pris]?></td>
</tr>
<tr>
*** EDITED FOR NEW QUESTION ***
<td class="product_list_header"><input type="checkbox" name="selected[]" value="<?=$hent_access_data[vnr]?>" data-spaces="<?=$hent_access_data['pris']?>" /></td>
</tr>
</table>
<?
}
?>
</form>
<div id="result"></div>
<script>
*** ADDED FOR NEW QUESTION ***
var totalSpaces = $('#totalSpaces').val();
var usedSpaces = 0;
// triggered when user clicks a checkbox
$('input[name="selected[]"]').on('change',function () {
*** ADDED FOR NEW QUESTION ***
currentSpaces = parseInt($(this).data('spaces');
if ($(this).is(':checked')) usedSpaces += currentSpaces;
else usedSpaces -= currentSpaces;
if (usedSpaces > totalSpaces) {
alert('Will not fit');
return false;
}
// grabs the selected checkbox values
var data = $("form").serialize();
// Sends the data via POST to hello.php
$.ajax({
url: "hello.php",
type: "POST",
dataType: 'html',
async: true,
cache: false,
data: data,
success: function(data) {
*** ADDED FOR NEW QUESTION ***
if (usedSpaces == totalSpaces) {
alert ('All spaces used');
$('input[name="selected[]"]').not(':checked').prop('disabled',true);
}
else {
$('input[name="selected[]"]').prop('disabled',false);
}
$('#result').html(data);
}
});
});
</script>
Please see the edits marked ADDED or EDITED
My requirement is fairly simple...I want to drill down on a table row to display more detailed data below. Thanks to several posts here and elsewhere, the jquery API site and various other resources I am sooooo close, but there seems to be one critical element I am missing.
I am able, in a single page to enter a value and submit that value as a variable to my PHP script. And I am able using JQuery to click on a row in a table and have that pop up an alert that displays that data as a variable. But I cannot pass the Jquery variable to my PHP script. I have read so many posts with similar requirements, but none quite like this.
In the code below I want to use the $data variable that I have created when I click on a table row and post that to my PHP script.
Any guidance would be most appreciated. Code below:
Thanks,
Rob
<?php
require("dbconn.php");
?>
<html>
<head>
<title></title>
<table border='1'>
<tr>
<th>user_name</th>
<th>sec_level</th>
</tr>
<tr>
<td><a u_name="test">test</td>
<td>test</td>
</tr>
<tr>
<td><a u_name="goat">goat</td>
<td>goat</td>
</tr>
</table>
<script src="jquery-1.10.2.js"></script>
<script>
$("tr").click(function() {
var $data = ( $(this).find("a").attr("u_name") )
alert( $data );
});
</script>
<form method="post" action="">
<dl>
<dt>Hobby No.
<dd><input id="field_" name="dynfields[]" type="text">
</dl>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php if (!isset($_POST['submit_val'])) { ?>
<?php } ?>
<body>
<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
}
}
$q = "select * from my_hobbies where hobbies = '$values'";
$r = mysql_query($q);
while ($row=mysql_fetch_array($r,MYSQL_NUM))
{
echo '<br>'.$row[1];
}
mysql_free_result($r);
mysql_close();
}
?>
</body>
</html>
AJAX..
$(function(){
$(":submit").click(function(){
$.ajax({
type:"POST",
url:"Ajax.php",
data:"WebName="+$("#WebName").val(),
success:function(data){
//...
}
});
});
});
I am trying to create a popup page from a parent page, which will return a value to the parent page and will close eventually.
What I have done so far:
main.php:
<tr>
<th>Project Name</th>
<td><input type="text" name="project_name" id="pid" disabled="disabled" />
<input type="button" name="choice" onClick="selectValue('id')" value="?"></td>
</tr>
<head>
<script type="text/javascript">
function selectValue(pid){
// open popup window and pass field id
window.open('search_project.php?id=' + encodeURIComponent(pid),'popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}
function updateValue(pid, value){
// this gets called from the popup window and updates the field with a new value
document.getElementById(pid).value = value;
}
</script>
</head>
search_project.php:
<head>
<script>
function closeWin(){
myWindow.close();
}
</script>
<script type="text/javascript">
function sendValue(value)
{
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<?php
$sql = mysql_query("SELECT project_id from prjct where project_id like 'default'");
$num = mysql_num_rows($sql);
<tr>
<td><input type="button" value="Select" onClick="sendValue('<?php echo $sql['project_id']; ?>')" /></td>
<td align="center"><? echo $sql['project_id']; ?></td>
</tr>
So, it is supposed to close the popup(search_project.php) and return the value of project_id in the input field of main.php. But, nothing is happening when I'm clicking on the select button. The popup doesn't close and the value is not returned. Seems sendValue(value) is not working.
Need help.
Do you really want encodeURIComponent(pid) here?
Try without encodeURIComponent:
window.open('search_project.php?id=pid','popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
The following code is used for getting two values from two textboxes , calculate the sum using javascript and display the result in third textbox. When I click the button, I just want these textbox values (both input and result) to be inserted into mysql database. I want to do this in the same page. How can I get the javascript values to php for inserting them into database? It would be great if you could help.
Thanks
Jeny
Code:
<html>
<head>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
}
</script>
</head>
<body>
<form>
<table width="306" border="0">
<tr>
<td width="146">Enter A </td>
<td width="144"><input name="text" type="text" id="in1"/></td>
</tr>
<tr>
<td>Enter B </td>
<td><input name="text2" type="text" id="in2"/></td>
</tr>
<tr>
<td height="41" colspan="2"> <center>
<button type="button" onclick="getText3()"> Get calculated result</button></center> </td>
</tr>
<tr>
<td><strong>RESULT</strong></td>
<td><input name="text3" type="text" id="in3"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
For this you should use jQuery (http://jquery.com/)
Just send them to your php file like the following:
// JS:
var in1 = $('#in1').val();
var in2 = $('#in2').val();
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
$('#in3').val( in3 );
$.post('file.php', { one: in1, two: in2, three: in3 }, function(data) {
alert( data );
} )
PHP file get's them as normal POST params:
// file.php
echo $_POST['one'] . " + " . $_POST['two'] . " = " . $_POST['three'];
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
$.ajax({
type: "POST",
url: "your_php_file_path.php",//you can get this values from php using $_POST['n1'], $_POST['n2'] and $_POST['add']
data: { n1: in1, n2: in2, add: in3 }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
You can Pass the JavaScript Values to a HIDDEN Value in FORM and then POST the form to the PHP Page. Below is an example of how to set hidden value.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function setPrice(el){
var prices=[30, 20, 10];
var p=el.options.selectedIndex;
el.form.elements['price'].value=prices[p];
}
</script>
</head>
<body>
<form>
<select name="category" onchange="setPrice(this);">
<option value="men">
Men
</option>
<option value="women">
Women
</option>
<option value="under18">
Under 18's
</option>
</select>
<input name="price" type="hidden" value="30">
</form>
</body>
</html>
Hope this will help you!
i can not use this keypad plugin on multiple fields. The first one works perfect but the other ones do not work. what do i need to do to make it work on all?
<script type="text/javascript">
$(function () {
$('#item_fee').keypad();
});
</script>
</head>
<body>
<tr>
<?
$query="SELECT * FROM item WHERE orderr_reference ='$ref' order by item_name";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$item_fee = mysql_result($result,$i,"item_fee");
?>
<td><input name="item_fee[]" id="item_fee" type="text" value="<?=$item_fee;?>" size="6" /></td>
</tr>
<? $i++; } ?>
ID's are unique in any one html page try this:
JS
<script type="text/javascript">
$(function () {
$('.keypad input').keypad();
});
</script>
Make it work for all inputs in another element with the keypad class
HTML
<body>
<table class="keypad">
Also make sure to update your html and remove the duplicate ID's.
id's are supposed to be unique for each html element in a webpage.
so change id="item_fee" to class="item_fee"
like so <td><input name="item_fee[]" class="item_fee" type="text" value="<?=$item_fee;?>" size="6" /></td>
and then you cane write in jquery
$(function () {
$('.item_fee').keypad();
});