How to pass for loop php to javascript - javascript

I have multiple edit records. I used script below to compare the value of textbox1 in textbox 2. But the problem is, when I try to edit multiple records. The script function only on the first record. How I can pass the for loop in php to javascript?
For Loop
$id=$_POST['checkbox'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
This gets all records depends on number of checkbox that have been checked. And when I get all the value in for loop opens records depends on counter value. Just like this how I can pass this for loop functions to javascript?
<script>
$('#sbtBtn').live('click',function(){
var textBox1=document.getElementById('pr_qty[]').value;
var textBox2=document.getElementById('pr_total').value;
if((+textBox2) > textBox1){
alert('value is greater than quantity');
return false;
}else{
}
});
</script>
<div class="container">
<form class="form-horizontal" action="" method="post">
<?php
$id=$_POST['checkbox'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$result1 = $mysqli->query("
SELECT a.item_name, a.item_description, a.counter, b.counter, b.pr, b.total_quantity
FROM app a
LEFT OUTER JOIN purchase_request b
ON a.counter=b.counter
WHERE a.counter='$id[$i]'
");
while ($row = $result1->fetch_assoc())
{ ?>
<div class="thumbnail">
<div style="display:none;">
<div class="control-label"></div>
<div class="controls">
<input name="counter[]" class="textbox" type="text" value="<?php echo $row['counter'] ?>" readonly="readonly"/>
</div>
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>Item</div>
<div class="controls" style='float:left;width:65%;margin-bottom:3px;'>
<input name="firstname[]" class="textbox" type="text" value="<?php echo $row['item_name'] ?>" readonly="readonly"/>
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>Description</div>
<div class="controls" style='float:left;width:65%;margin-bottom:3px;'>
<input name="lastname[]" class="textbox" type="text" value="<?php echo $row['item_description'] ?>" readonly="readonly"/>
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>PR Quantity</div>
<div class="controls" style='float:left;width:65%;margin-bottom:3px;'>
<input name="pr_qty[]" id="pr_qty[]" class="textbox" type="text" value="<?php echo $row['total_quantity']; ?>" />
<input id="pr_total" class="textbox" type="text" value="<?php $result2 = $mysqli->query("SELECT *, SUM(quantity) total_quantity FROM purchase_order WHERE counter='$id[$i]'");
while($rows = $result2->fetch_assoc()){ echo $rows['total_quantity']; }
?>">
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>PR #</div>
<div class="controls">
<input name="pr[]" class="textbox" type="text" value="<?php echo $row['pr'] ?>" />
</div>
</div>
<br>
<?php
}
}
?>
<input name="submit" type="submit" id="sbtBtn" value="Update">
</form>
</div>

You can not give same id to multiple elements, you have to give unique id to your textboxes. In your function you getting textboxes byh Id, change it to class and also give separate classes to your textbox1 and 2. Otherwise your script will work on only first record.
js change
var textBox1=document.getElementsByClassName('tb1');
var textBox2=document.getElementsByClassName('tb2');
for(var i=0; i< textBox1.length; i++){
if((textBox2[i].value) > textBox1[i].value){
alert('value is greater than quantity');
return false;
}else{
}
}
and html change
<input name="pr_qty[]" id="pr_qty[]" class="textbox tb1" type="text" value="<?php echo $row['total_quantity']; ?>" />
<input id="pr_total" class="textbox tb2" type="text" value="<?php $result2 = $mysqli->query("SELECT *, SUM(quantity) total_quantity FROM purchase_order WHERE counter='$id[$i]'");
while($rows = $result2->fetch_assoc()){ echo $rows['total_quantity']; }
?>">

In your onclick event you can read input fields value like:
EDIT:
var val1 = $("input[name='UR_ELE1_NAME']").val();
var val2 = $("input[name='UR_ELE2_NAME']").val();
And you can compare like: if(val1 > val2){ .....}
I hope this helps.

Related

How to pass multiple inputs into a single query?

In my app I want the user to mention how many columns he wants for the table and then enter the data for those columns and create a table with those values.
Here is what I have:
<form action="" method="post">
<label for="numOfCols">Enter Number of Fields</label>
<input name="numOfCols" type="number" id="numOfCols">
<button type="submit" class="btn btn-info" name="numOfColsSubmit" >Generate</button>
</form>
<?php if(isset($_POST["numOfCols"])): ?>
<form action="" method="post">
<label for="tbName">Enter Layout Name</label>
<input type="text" name="tbName" id="tbName" class="form-control">
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<div class="row g-4">
<div class="col-sm">
<label for="col_name<?php $colNum ?>">Name</label><br>
<input class="form-control" id="col_name<?php $colNum ?>" type="text"
name="col_name<?php $colNum ?>" >
</div>
<div class="col-sm">
<label for="col_types<?php $colNum ?>">Type</label><br>
<select name="col_types<?php $colNum ?>" class="form-control" id="col_types<?php $colNum ?>">
<option value="int">INT</option>
<option value="varchar" >VARCHAR</option>
<option value="text">TEXT</option>
</select>
</div>
<div class="col-sm">
<label for="col_length<?php $colNum ?>">Length</label><br>
<input type="text" class="form-control" name="col_length<?php $colNum ?>" id="col_length<?php $colNum ?>">
</div>
<div class="col-sm">
<br><button type="submit" class="btn btn-success" name="submitaddcol<?php $colNum ?>">Submit</button>
</div>
</div>
<?php endfor; ?>
<button type="submit" name="createtb" class="btn">Create Layout</button>
</form>
<?php endif;?>
<?php if(isset($_POST["tbName"])){
$table->createTb($_POST['tbName']);
} ?>
and the function for creating the table :
function createTb($tb){
$arr = [];
if(isset($_POST['col_name'])){
$colName = $_POST['col_name'];
}
if(isset($_POST['col_types'])){
$colTypes = $_POST['col_types'];
}
if(isset($_POST['col_length'])){
$colLength = $_POST['col_length'];
}
echo $tb;
array_push($arr , $colName , $colTypes , $colLength);
$stmt = $this->pdo->prepare("CREATE TABLE $tb ($colName $colTypes($colLength)) ");
$stmt->execute([$_POST['name'], 29]);
$stmt->execute();
$stmt = null;
}
I was thinking of getting the data from the user, pass it to an array and then use that array in my query.
The problem is I cannot get all of the user data. If the user has 2 or more columns, it will always get the last column. Any insight?
(Putting the createTb($_POST['tbName']) inside the for loop for some reason results in now showing or calling the function at all)
You can name your input-fields as an array like:
<input type="text" name="col_name[]" value="foo" />
And get it with var_dump($_POST['col_name']);
In your example you could do like this:
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<input class="form-control" id="col_name_<?=$colNum ?>" type="text" name="col_name[<?=$colNum ?>]" >
<input type="text" class="form-control" name="col_length[<?= $colNum ?>]" id="col_length_<?=$colNum ?>">
<?php endfor; ?>
And get the result:
if(isset($_POST['col_name']) && is_array($_POST['col_name'])) {
for($i = 0; $i < count($_POST['col_name']); $i++) {
var_dump($_POST['col_name'][$i]);
var_dump($_POST['col_length'][$i]);
}
}

Q: Calculate two inputs with javascript

I have created the following code and on the last 3 inputs, I would like to calculate INPUT1 with INPUT2 and automatically get the result on INPUT3.
At the moment it's not working ofc, but if I change the INPUT3 to suddenly it works, but ofc I cannot get any data to be posted onto the database. How can I output the result of the calculation without having to use a span tag?
Here is the Code.
<script>
function divideBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num2 % num1;
}
</script>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Create new Route</h2>
</div>
<p>Enter the route<i><strong>"YYYY-MM-DD</i></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($reason_err)) ? 'has-error' : ''; ?>">
<label>Reason</label>
<input type="text" name="reason" class="form-control" value="<?php echo $reason; ?>">
<span class="help-block"><?php echo $reason_err;?></span>
</div>
<div class="form-group <?php echo (!empty($startdest_err)) ? 'has-error' : ''; ?>">
<label>Start Destination</label>
<input type="text" name="startdest" class="form-control" value="<?php echo $startdest; ?>">
<span class="help-block"><?php echo $startdest_err;?></span>
</div>
<div class="form-group <?php echo (!empty($enddest_err)) ? 'has-error' : ''; ?>">
<label>End Destination</label>
<input type="text" name="enddest" class="form-control" value="<?php echo $enddest; ?>">
<span class="help-block"><?php echo $enddest_err;?></span>
</div>
<div class="form-group <?php echo (!empty($startkm_err)) ? 'has-error' : ''; ?>">
<label>INPUT 1</label>
<input type="text" name="startkm" class="form-control" id="firstNumber" value="<?php echo $startkm; ?>">
<span class="help-block"><?php echo $startkm_err;?></span>
</div>
<div class="form-group <?php echo (!empty($endkm_err)) ? 'has-error' : ''; ?>">
<label>INPUT 2</label>
<input type="text" name="endkm" class="form-control" id="secondNumber" onChange="divideBy()" value="<?php echo $endkm; ?>">
<span class="help-block"><?php echo $endkm_err;?></span>
</div>
<div class="form-group <?php echo (!empty($totalkm_err)) ? 'has-error' : ''; ?>">
<label>INPUT3</label>
<input type="text" name="totalkm" id="result" class="form-control" value="<?php echo $totalkm; ?>">
<span class="help-block"><?php echo $totalkm_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
If i change it from:
<div class="form-group <?php echo (!empty($totalkm_err)) ? 'has-error' : ''; ?>">
<label>Total Km</label>
<input type="text" name="totalkm" id="result" class="form-control" value="<?php echo $totalkm; ?>">
<span class="help-block"><?php echo $totalkm_err;?></span>
</div>
To this it works but ofc as I said no data is posted:
<div class="form-group <?php echo (!empty($totalkm_err)) ? 'has-error' : ''; ?>">
<label>Total Km</label>
<span type="text" name="totalkm" id="result" class="form-control" value="<?php echo $totalkm; ?>">
<span class="help-block"><?php echo $totalkm_err;?></span>
</div>```
#KIKO Software I solved after reading your comment a couple of times :) code that was changed "document.getElementById("result").value" and it solved the issue now upon changing the last input it automatically calculates the result from those two inputs mentioned before, and this was the result I was looking for.
<script>
function divideBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").value = num2 % num1;
}
</script>
Thank you for your help :)

How to fill more than one input form using onlick

I'm trying to create a live search with AJAX.
Then when I click the result I want the result to fill 5 input fields.
Here is what I have tried:
Here is my cari.php file:
while ($cari_karyawans = $cari_karyawan->fetch()) { ?>
<div class="result" onclick="fill('nik','<?php echo $cari_karyawans['nik_k_ptayp']; ?>')">
<div class="result" onclick="fill('nama','<?php echo $cari_karyawans['nama_k_ptayp']; ?>')">
<div class="result" onclick="fill('lokasi','<?php echo $cari_karyawans['jabatan_k_ptayp']; ?>')">
<div class="result" onclick="fill('divisi','<?php echo $cari_karyawans['divisi_k_ptayp']; ?>')">
<div class="result" onclick="fill('jabatan','<?php echo $cari_karyawans['lokasi_k_ptayp']; ?>')">
<a><small class="text-muted"><i><?php echo $cari_karyawans['nik_k_ptayp']; ?></i></small> / <small class="text-muted"><i><?php echo $cari_karyawans['nama_k_ptayp']; ?></i></small></a>
</div></div></div></div></div>
<?php } ?>
Here is how I try to fill the result:
function fill(nik, nama, lokasi, divisi, jabatan) {
$('#nik').val(nik);
$('#nama').val(nama);
$('#lokasi').val(lokasi);
$('#divisi').val(divisi);
$('#jabatan').val(jabatan);
$('#display').hide();
}
Here is my input file:
<input type="text" class="form-control" id="nik">
<input type="text" class="form-control" id="nama">
<input type="text" class="form-control" id="lokasi">
<input type="text" class="form-control" id="divisi">
<input type="text" class="form-control" id="jabatan">
Your JS function fill should be :
function fill(id, value) {
$('#'+id).val(value);
}
Because you already sending the id as the first argument and the value as the second.

PHP Multiple loops to read multiple tables and display in single select element HTML?

I need to display all the values from two table in my HTML input. It has info about a user called recruit who has info from two multiple tables. But only interview_id and course_id I need to display all values in the select menu. The problem is I am just getting last value of each loop. So it displays only one value in echo $interviewrow[date_time]; and echo $courserow[name];
Sorry if the formatting is wrong.
Here is my php read values from database which is just before the select element:
<?php
$interviewlist = $dbcon->exec("select idinterview, date_time from interview");
for($i=0;$i<$interviewlist;$i++){
$interviewrow=$dbcon->data_seek($i);
?>
<?php
$recruit= $dbcon->exec("select * from recruit where user_id=".quote_smart($userid));
if($recruit>0){
$recruitrow=$dbcon->data_seek($i);
}
$recruitcourse= $dbcon->exec("select idcourse, name from course where idcourse=".quote_smart($recruitrow[course_id]));
if($recruitcourse>0)
$recruitcourserow=$dbcon->data_seek($i);
$courselist= $dbcon->exec("select * from course");
for($i=0;$i<$courselist;$i++){
$courserow=$dbcon->data_seek($i);
?>
Here is my html in javascript which appears if select type is recruit which is just after the php read.
else if( $(this).val() == 'Recruit' || $(this).val() == 'Recruit-Edit'){
$('.new-field').remove();
$('.new-input').append(' <div class="new-field"> <input type="hidden" name="idinterview" value="<?php echo $interviewrow[idinterview];>"><div class="form-group" id="opt"><label class="col-sm-2 control-label">Date</label><div class="col-sm-10"><select class="form-control" id="date" name="date"><option selected disable>Choose Date</option><option><?php echo $interviewrow[date_time]; ?></option></select></div></div> <?php } ?><div class="form-group"><label class="col-sm-2 control-label">Applied For</label><div class="col-sm-10"><input name="applied" type="text" class="form-control" value="<?php echo $recruitrow[applied_for]; ?>"></div></div> <div class="form-group"><label class="col-sm-2 control-label">CV</label><div class="col-sm-10"><input accept="application/pdf" class="enable-attache" data-geometry="150x150#" data-value="[<?php echo htmlentities($recruitrow[file]); ?>]" data-uploadurl="<?php echo ATTACHE_DOMAIN; ?>/upload" data-downloadurl="<?php echo ATTACHE_DOMAIN; ?>/view" data-uuid="<?php echo $uuid; ?>" data-expiration="<?php echo $expiration; ?>" data-hmac="<?php echo hash_hmac('sha1', $uuid.$expiration, ATTACHE_SECRET); ?>" type="file" name="cv" id="cv" /></div></div><div class="form-group"><label class="col-sm-2 control-label">Phone</label><div class="col-sm-10"><input name="phone" type="text" class="form-control" value="<?php echo $recruitrow[phone]; ?>"></div></div> <div class="form-group"><label class="col-sm-2 control-label">Date Applied</label><div class="col-sm-10"><input name="datea" type="date" class="form-control" value="<?php echo $recruitrow[date_applied]; ?>"></div></div> <input type="hidden" name="idcourse" value="<?php echo $courserow[idcourse];?>"><div class="form-group" id="opt"><label class="col-sm-2 control-label">Course Enrolled (if any)</label><div class="col-sm-10"><select class="form-control" id="course" name="course"><option selected disable><?php echo $recruitcourserow[name]; ?></option><option><?php echo $courserow[name]; ?></option></select></div></div><?php } ?></div>');

Insert value from javascript to database

I am making a type of slider form for restaurant management system in which user will select items in each form and the selected values will be displayed at last "confirm form" and i want to insert values of selected items obtained at confirm form to be inserted into database.
<script>
function changeColor(obj){
obj.style.color = "red";
var selected_val = obj.innerHTML;
document.getElementById('target_div').innerHTML=document.getElementById('target_div').innerHTML+" "+selected_val;
}
</script>
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Roti</legend>
<?php
$qu = mysql_query("select * from submenu WHERE menu_id=33") or die(mysql_error());
while($f = mysql_fetch_array($qu)){
?>
<p>
<label for="name" onclick="changeColor(this)"><?php echo $f['submenu']; ?></label>
<input id="name" name="name" type="hidden" AUTOCOMPLETE=OFF value="<?php echo $f['id']; ?>"/>
</p>
<?php } ?>
</fieldset>
<fieldset class="step">
<legend>Sabji</legend>
<?php
$qu2 = mysql_query("select * from submenu WHERE menu_id=34");
while($f2 = mysql_fetch_array($qu2)){
?>
<p>
<label for="name" onclick="changeColor(this)"><?php echo $f2['submenu']; ?></label>
<input id="name" name="name" type="hidden" AUTOCOMPLETE=OFF value="<?php echo $f2['id']; ?>"/>
</p>
<?php } ?>
</fieldset>
<fieldset class="step">
<legend>Salad</legend>
<?php
$qu3 = mysql_query("select * from submenu WHERE menu_id=35");
while($f3 = mysql_fetch_array($qu3)){
?>
<p>
<label for="name" onclick="changeColor(this)"><?php echo $f3['submenu']; ?></label>
<input id="name" name="name" type="hidden" AUTOCOMPLETE=OFF value="<?php echo $f3['id']; ?>"/>
</p>
<?php } ?>
</fieldset>
<fieldset class="step">
<legend>Sweets</legend>
<?php
$qu4 = mysql_query("select * from submenu WHERE menu_id=36");
while($f4 = mysql_fetch_array($qu4)){
?>
<p>
<label for="name" onclick="changeColor(this)"><?php echo $f4['submenu']; ?></label>
<input id="name" name="name" type="hidden" AUTOCOMPLETE=OFF value="<?php echo $f4['id']; ?>"/>
</p>
<?php } ?>
</fieldset>
<fieldset class="step">
<legend>Confirm</legend>
<p>
<label id="target_div" for="name"></label>
</p>
<p class="submit">
<button id="registerButton" type="submit" name="confirm">Confirm</button>
</p>
</fieldset>
</form>
I want to insert the value obtained at confirm form into database using PHP.
This is the essential part:
while($f = mysql_fetch_array($qu)){
?>
<p>
<label for="name" onclick="changeColor(this)"><?php echo $f['submenu']; ?></label>
<input id="name" name="name" type="hidden" AUTOCOMPLETE=OFF value="<?php echo $f['id']; ?>"/>
</p>
<?php } ?>
You repeat it for other categories (salas, sweets, etc), so let's look at that first.
And a few things are wrong with it.
First, your label says for="name". Name should be a UNIQUE identifier in the document. An identifier is an id="whatever". So if you want to target a specific element with your label, be sure to make the id="" match the for="".
In your case this is most easily done by adding a unique key from the underlying database-table.
But I cannot help because I cannot see your columns in the database. You use:
select * from submenu WHERE menu_id=33
Please stop using the lazy * and NAME the columns you need.
I hope you have a column that is the primary key in tblsubmenu. Let's say it is id. (I think a better name would have been submenuid.)
Then you can use that to do the labeling and id's right, like this:
<?php
$qu = mysql_query("select submenuid, submenu, from submenu WHERE menu_id=33") or die(mysql_error());
while($f = mysql_fetch_array($qu)){
?>
<p>
<label for="name<?php echo $f['id']; ?>" onclick="changeColor(this)"><?php echo $f['submenu']; ?></label>
<input id="name<?php echo $f['id']; ?>" name="submenuid[]" type="hidden" AUTOCOMPLETE=OFF value="<?php echo $f['id']; ?>"/>
</p>
<?php } ?>
That way you have matching for="" and id="", for example: in the label: for="name181" and an id="name181".
Also note I changed your input form-element, now it's name is "submenuid[]"
If you now post the form, you will receive an ARRAY in $_POST["submenuid"].
Print it out with:
echo "<pre>".print_r($_POST,true)."</pre>";
And see if it matches what you wanted to send.
If so, you can now start with inserting, for example:
foreach ($_POST["submenuid"] as $submenuid){
$id = (int)$submenuid; // force it to be an integer
$SQL = "INSERT INTO tblorders (submenuid, customerid) VALUES ($id, 111)";
// execute here against database, see links below
}
w3schools-link for starters
PHP website mysqli.query.php

Categories