I have a problem in my code. My jQuery code is only implement of the first row of table not on others. Here is my code:
<tr>
<td><?php echo $row['serial no.'] ?></td>
<td><?php echo $row['pname'] ?></td>
<td><input type="text" class="form-control" id="prate" name = "uprice" value="<?php echo $prate = $row['uprice'];?>"></td>
<td> <input type="number" class="form-control" id="pqty" name = "quantity" value ="<?php $quant = ""; echo $quant; ?>"></td>
<td> <input type="text" class="form-control" id="pTotal" name = "price" value = "<?php $tprice = ""; echo $tprice; ?>" ></td>
</tr>
This is my HTML code:
<script>
$("#prate").keyup(function(){
// console.log('presssed');
var prate = document.getElementById('prate').value;
var pqty = document.getElementById('pqty').value;
var ptotal = parseInt(prate) * parseInt(pqty);
document.getElementById('pTotal').value = ptotal;
});
$("#pqty").keyup(function(){
// console.log('presssed');
var prate = document.getElementById('prate').value;
var pqty = document.getElementById('pqty').value;
var ptotal = parseInt(prate) * parseInt(pqty);
document.getElementById('pTotal').value = ptotal;
});
</script>
What can I try to resolve this?
What you have to do is (1) Gather all those classes in a Variable. (2) Run Foreach loop on each element. (3) While looping each element, you must sum all of these elements' values.
// Step 1: Fetch Classes
var FetchedClasses = document.getElementsByClassName("myclass");
var Sum = 0;
// Step 2: Iterate them
Array.prototype.forEach.call(FetchedClasses, function(element) {
// Step 3: Sum up their values
Sum = Sum + element.value; //
});
// Now Show it anywhere you like.
Use class selector (not id selector) and each method to emplement your desired commands on all rows.
ID must be unique, instead put a class as a reference for each table data and try each method:
$('.pqty').each(function(i, element){
$(element).keyup(function(evt) {
/* anything */
})
})
As you know, id must be unique on whole page. So on each row and items, either you have make unique id (Which will be complicated to bind event), so you can go with class or as below script for binding the events.
<script>
$('input[name="uprice"]').keyup(function(){
var prate = $(this).val();
var pqty = $(this).parent().next().find('input[name="quantity"]').val();
var ptotal = parseInt(prate) * parseInt(pqty);
$(this).parent().next().next().find('input[name="price"]').val(ptotal);
});
$('input[name="quantity"]').keyup(function(){
var prate = $(this).parent().prev().find('input[name="uprice"]').val();;
var pqty = $(this).val();
var ptotal = parseInt(prate) * parseInt(pqty);
$(this).parent().next().find('input[name="price"]').val(ptotal);
});
</script>
Not have tested but should help you.
Related
I am trying to calculate tax also get the id for each in a single dropdown like this
<td><select name="tax[]" class="form-control tax" id="tax_1" style="width:80px;">
<option value="">Tax</option>
<?php $s1 = mysqli_query($con, "select * from taxes"); while($s2 = mysqli_fetch_array($s1)) {
$options .= "<option value='". $s2['tax_id']."_".$s2['name']."'>".$s2['name'].'-'.$s2['rate'] . "</option>";
?>
<option value="<?php echo $s2['tax_id']."_".$s2['rate']; ?>"><?php echo $s2['name'].'-'.$s2['rate']; ?></option>
<?php
}
?>
</select></td>
These values i am passing to jquery for auto calculation purpose. Values will be like id_rate (1_5) , I have to split it and rate i should use for calculations. How to split it there.
now i am calculating it like this
$('body').on('change', '.quantity,.price,.discount,.tax', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var tax = tr.find('.tax').val();
var dis = tr.find('.discount').val();
var amt = (qty * price) - (qty * price * dis) / 100;
var tax1 = (amt * (tax / 100));
tax1 = Number((tax1).toFixed(2));
But i am not getting how to split
You can try split function.
$('body').on('change', '.quantity,.price,.discount,.tax', function() {
if($(this).hasClass("tax")){
var taxVal= $(this).val();
var tax_id=taxVal.split('_')[0];
var rate=taxVal.split('_')[1];
}
}
function Splitval(obj) {
alert("Your Value :" + $(obj).val());
alert("Split Value :" + $(obj).val().split('_')[1] + "_" + $(obj).val().split('_')[0]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="abc" type="text" onChange="Splitval(this)">
I am trying to populate a html table based on a select box (with staff numbers) changing. The data is being retrieved from a mysql database. I then want to highlight a row when it is hovered over using jquery.
Am I going about this the right way?
main.php
<div id="logHistory">
<label id="historyTableLabel">Your Log History</label>
<table id="logTable">
<tr id="headers">
<td>Log Date</td>
<td>LogType</td>
<td>Start Time</td>
<td>End Time</td>
<td>Duration</td>
</tr>
</table>
</div>
select.php
$staffNum = isset($_POST['staffNumber']) ? $_POST['staffNumber'] : 0;
if($staffNum > 0)
{
populateLogHistory($con, $staffNum);
}
function populateLogHistory($con, $staffNum)
{
//Retrieve data from entries table
$result = mysqli_query($con, "SELECT EntryID, LogDate, LogType, StartTime, StartDate, FinishTime, FinishDate FROM Entries WHERE StaffNumber=$staffNum");
while($row = mysqli_fetch_array($result))
{
$entryID = $row['EntryID'];
$logDate = $row['LogDate'];
$logTypeID = $row['LogType'];
$resulting = mysqli_query($con,"SELECT LogType FROM logType WHERE LogTypeID=$logTypeID");
$logTypeStr = mysqli_fetch_array($resulting);
$startDate = $row['StartDate'];
$startTime = $row['StartTime'];
$start = $startDate . " " . $startTime;
$start = new DateTime($start);
$finishDate = $row['FinishDate'];
$finishTime = $row['FinishTime'];
$finish = $finishDate . " " . $finishTime;
$finish = new DateTime($finish);
$duration = $start->diff($finish);
echo "<tr id=".$entryID.">";
echo "<td>".$logDate."</td>";
echo "<td>".$logTypeStr[0]."</td>";
echo "<td>".$startTime."</td>";
echo "<td>".$finishTime."</td>";
echo "<td>".$duration->h."hr ".$duration->i."</td>";
echo "</tr>";
}
}
jquery code
$(document).ready(function()
{
$("#staffMember").change(function()
{
//Check the mandatory first
var selectedIndex = $("#staffMember").prop('selectedIndex');
isMandatory(selectedIndex, $(this));
if(selectedIndex != -1)
{
//If there is a staff number call the select to populate the log history
var staffNum = $("#staffMember").val();
var dataString = 'staffNumber=' + staffNum;
$.ajax({
type: "POST",
url: "select.php",
data: dataString,
cache: false,
success: function(html)
{
$("#logTable").html(html);
}
});
}
}).change();
});
Use this CSS for the hovering part:
.datarow:hover {
background-color: #ccc;
}
Assuming that you put a class tag to your populated row:
echo '<tr id="'.$entryID.'" class="datarow">';
For the populating part, use .on() for every call so you can still do another call on Javascript DOM elements.
$(document).on("change", "#staffMember", function(){
And if you want to do another event handler on the populated data, let's put it as a class tag instead and the data ($entryID) will be on another data tag.
echo '<tr data-artid="'.$entryID.'" class="datarow">';
So when you try to call it, you can just do:
$(document).on("click", ".datarow", function(){
var entryid = $(this).attr('data-artid'); /* ENTRY ID OF THE CLICKED ROW */
I have a form with a repeating section that uses jQuery to clone the section and increment the ids. Now I need to initialize the variables in order to send the form via PHP.
HTML:
<div class="repeatingSection">
<label for="poste_1">Poste :</label>
<input type="text" name="poste_1" id="poste_1"/>
<label for="date_1">Date :</label>
<input type="text" name="date_1" id="date_1"/>
</div>
JQUERY:
jQuery('.cloneButton').click(function(event){
event.preventDefault();
var currentCount = jQuery('.repeatingSection').length;
var newCount = currentCount+1;
var lastRepeatingGroup = jQuery('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone(false).find('.cloneButton').remove().end();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("input").each(function (index, input) {
input.id = input.id.replace("_" + currentCount, "_" + newCount);
input.name = input.name.replace("_" + currentCount, "_" + newCount);
});
newSection.find("label").each(function (index, label) {
var l = jQuery(label);
l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
});
return false;
});
jQuery(document.body).on('click','.removeButton', function(){
jQuery(this).closest('div.repeatingSection').remove();
return false;
});
PHP :
$poste1 = '';
$date1 = '';
$poste1 = trim($_POST['poste_1']);
$date1 = trim($_POST['date_1']);
I know I would need to put them in an array and loop through them but I'm not sure how to go about it.
You can use a for loop and a count variable from javascript and do something like :
for($i=1; $i<$currentCount; $i++) {
${"poste".$i} = trim($_POST["poste_$i"]);
${"date".$i} = trim($_POST["date_$i"]);
}
You would have variables $poste1 and $date1. Using ${''} creates dynamic variables.
I have a page that has three checkbox lists, the three are dynamically generated
what I want and that as the User is clicking the checkbox values are passed via post, but I only managed to catch Esto values of the first list
I did the code like this:
$("body").find(".fcID").click(function(){
// var v = $(this).val();
//alert(v);
var form = jQuery('#form');
valor = form.serialize();
$.ajax({
type : "POST",
url:"biblioteca/filtra.php",
data: valor,
success: function(data){
$("#tabelafiltro").html(data);
}
});
in html, I put a form with the id of her form and name the form
within that form, I have the checkboxes, so:
<form name="form" id="form" action="" method="post">
<table>
<tr>
<td><input type="checkbox" class="fcID" value="<?php echo $linha['fm-cod-com'] ?>" name="fcID[]"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" class="fcID" name="fam[]" value="<?php echo $linha['fm-codigo'] ?>" /></td>
</tr>
</table>
</form>
and the php:
$id = $_POST['fcID'];
$fam = $_POST['fam'];
echo(count($fam)) . " + " . count($id);
somebody help me?
Your code is correct, are u sure that the fam[] checkboxes are checked? Checkboxes will serialize only if they have atribute checked="checked".
Unfortunately the "name" is not converted to an array by jQuery.. so instead of this:
echo $_POST['fcID'][0]; // undefined
you have this
echo $_POST['fcID[]']; // expected value
I created the following. It has some limitations, but should do what you want. I appreciate if you can rate my answer.
var form = jQuery('#form');
valor = form.formToObj();
// formToObj (c) 2012 Frank Forte.
// Please contact me for a free license to use on personal or business website
// #frankforte or frank # interactinet .com!
jQuery.fn.formToObj = function()
{
var obj = {}
jQuery("input,select,textarea",this).each(function(){
if(jQuery(this).attr("disabled")){
return;
}
var n = jQuery(this).attr("name") || jQuery(this).attr("id")
var v = jQuery(this).val();
// e.g.<input name="test[one][two][three]" value="hello world">
if(!n.match(/\[/))
{
obj[n] = v
}
else
{
// get keys of array, e.g. "one","two","three"
var keys = []
nkeys= n.split('[')
var i = 0;
for(k in nkeys)
{
if(i > 0)
{
var nk = nkeys[k]
if(typeof nk == "string")
{
if(nk.match(/\]/))
{
nk = nk.replace("]","")
}
keys.push(nk);
}
}
i++
}
// name e.g. "test"
n = n.replace(/^([^\[\]]+)\[.*$/i,"$1");
// create object and add value then array keys from bottom up
var iobj = {}
for(i = keys.length; i > 0; i--)
{
j = i-1;
var k = keys[j]
if(k==""){k = 0;}
if(i == keys.length)
{
iobj[k] = v
}
else
{
iobj[k] = iobj
}
}
// Need to start with obj[n] and add new values under appropriate keys
// prevents unsetting or overwriting keys deeper than n
if(typeof obj[n] == "undefined")
{
obj[n] = {}
}
obj[n][k] = iobj[k]
}
})
return obj
}
i want to do a very simple thing. I want to populate the list of a drop-down box based on the value of the 1st drop-down box. So these 2 boxes are the only elements in a table, which creates rows dynamically(on the click of a button). I am a newbie in html.. and have almost spent 2 entire days in vain in this...
This is the code:
HTML Code:
<table border="1" id="areas">
<tr>
<th colspan="3">Areas Serviced</th>
</tr>
<tr>
<td>
<select name='city1' id='city1' onChange="dynamic1(this,'txtRow1');">
<option value="">Please select a city</option>
<option value='Bangalore'> Bangalore </option>
<option value='Mumbai'> Mumbai</option>
</select>
<option></option>
</td>
<td>
<select name="txtRow1" id="txtRow1">
<option value="">Please Select an area</option>
<option></option>
</select>
</td>
</tr>
</table>
<input type="button" value="Add another Area" onClick="addRowToTable();" /> <input type="button" value="Remove" onClick="removeRowFromTable();" />
</br>
</br>
<input type="submit" name="submit" id="submit" value="Submit" />
Javascript:
function dynamic1(parent,child){
var parent_array = new Array();
parent_array[''] = ['Please select a city'];
parent_array['Bangalore'] = ['Marathahalli','Kadubeesanahalli'];
parent_array['Mumbai'] = ['Andheri','Santacruz'];
var thechild = document.getElementById(child);
thechild.options.length = 0;
var parent_value = parent.options[parent.selectedIndex].value;
if (!parent_array[parent_value]) parent_value = '';
thechild.options.length = parent_array[parent_value].length;
for(var i=0;i<parent_array[parent_value].length;i++){
thechild.options[i].text = parent_array[parent_value][i];
thechild.options[i].value = parent_array[parent_value][i];} }
function addRowToTable()
{
var tbl = document.getElementById('areas');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var col = document.createElement("TR");
var cell1 = document.createElement("TD");
var txt0= document.createTextNode(iteration);
var combo1=document.createElement("select");
var combo11=document.createElement("option");
var combo12=document.createElement("option");
var combo2=document.createElement("select");
var combo21=document.createElement("option");
var combo22=document.createElement("option");
var id2=combo2.id;
combo1.setAttribute("name","city");
combo1.setAttribute("onChange","dynamic1(this,id2);");
combo11.setAttribute("value","Bangalore");
combo11.innerHTML="Bangalore";
combo12.setAttribute("value","Mumbai");
combo12.innerHTML ="Mumbai";
combo2.setAttribute("name","area");
combo2.setAttribute("id","txtRow"+iteration);
combo1.appendChild(combo11);
combo1.appendChild(combo12);
combo2.appendChild(combo21);
combo2.appendChild(combo22);
var cell2 = document.createElement("TD");
cell2.appendChild(combo1);
var cell3 = document.createElement("TD");
cell3.appendChild(combo2);
col.appendChild(cell2);
col.appendChild(cell3);
tbl.appendChild(col);
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
This code does not work.
Alternate Javascript code:
function SetMedia(objCity,iteration) {
var objArea = document.getElementById("txtRow"+iteration);
objArea.options.length = 0;
objArea.disabled = false;
switch (objCity.value) {
case "Bangalore":
objArea.options.add(new Option("Marathahalli"));
objArea.options.add(new Option("Kadubeesanahalli"));
break;
case "Mumbai":
objArea.options.add(new Option("Andheri"));
objArea.options.add(new Option("Santacruz"));
break;
default:
objArea.options.add(new Option("select"));
objArea.disabled = true;
break;
}
}
function addRowToTable()
{
var tbl = document.getElementById('areas');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var col = document.createElement("TR");
var cell1 = document.createElement("TD");
var txt0= document.createTextNode(iteration);
var combo1=document.createElement("select");
var combo11=document.createElement("option");
var combo12=document.createElement("option");
var combo2=document.createElement("select");
var combo21=document.createElement("option");
var combo22=document.createElement("option");
combo1.id="city"+iteration;
var id1=combo1.id;
combo2.id="txtRow"+iteration;
var id2=combo2.id;
combo1.setAttribute("name","city");
combo1.onChange=func(){SetMedia(id1,iteration);}
combo11.setAttribute("value","Bangalore");
combo11.innerHTML="Bangalore";
combo12.setAttribute("value","Mumbai");
combo12.innerHTML ="Mumbai";
combo2.setAttribute("name","area");
combo2.setAttribute("id","txtRow"+iteration);
combo1.appendChild(combo11);
combo1.appendChild(combo12);
combo2.appendChild(combo21);
combo2.appendChild(combo22);
var cell2 = document.createElement("TD");
cell2.appendChild(combo1);
var cell3 = document.createElement("TD");
cell3.appendChild(combo2);
col.appendChild(cell2);
col.appendChild(cell3);
tbl.appendChild(col);
}
Basically, I am not able to link the dynamically created object(drop-down number 2) to drop-down number 1 since I am not able to get the 'id's of the elements dynamically generated...
After this, I also need to use these values entered in another php script using POST...
This part doesn't work. You can't write to the .length property of an array or collection.
thechild.options.length = 0;
var parent_value = parent.options[parent.selectedIndex].value;
if (!parent_array[parent_value]) parent_value = '';
thechild.options.length = parent_array[parent_value].length;
for(var i=0;i<parent_array[parent_value].length;i++){
thechild.options[i].text = parent_array[parent_value][i];
thechild.options[i].value = parent_array[parent_value][i];} }
replace with
while (thechild.options[0]) thechild.removeChild(thechild.options[0]);
var parent_value = parent.options[parent.selectedIndex].value;
if (parent_array[parent_value]) {
for(var i=0;i<parent_array[parent_value].length;i++){
var o = document.createElement('option');
o.text = parent_array[parent_value][i];
o.value = parent_array[parent_value][i];} }
thechild.appendChild(o);
}
}
In the first javascript you are attempting to read the id attribute of combo2 before you have set it.
In the second javascript you are just adding two empty options to the select element (combo2).