How to populate multiple textbox based on dropdown selection? - javascript

I have to populate my 2 textboxes based on the dropdown value from a single table.
Here is my table structure:
When I select the product name from the dropdown I want the 2 textboxes values to populate 1.sale_price 2.tax_amt. I have already populated the dropdown value from DB, please help me with the textboxes value.
DROPDOWN:
<select name="select_services[]" class="form-control select_services">
<option value="">--SelectProduct--</option>
<?php
$sql= "SELECT * from products where delete_status='0' ORDER BY id DESC";
$result=$conn->query($sql);
foreach ($result as $r_service) { ?>
<option value="<?php echo $r_service['id'];?>"><?php echo $r_service['name'];?></option>
<?php } ?>
</select>
Textboxes that I need to populate
<div class="col-sm-2">
<input type="text" class="form-control" id="unit_price" name="unit_price[]" placeholder="Sale Price" required>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="tax" name="tax[]" placeholder="Tax" required>
</div>
JAVASCRIPT
<script type="text/javascript">
$('div.mydiv').on("change",'select[name^="select_services"]',function(event){
var currentRow=$(this).closest('.subdiv');
var drop_services= $(this).val();
$.ajax({
type : "POST",
url : 'ajax_service.php',
data : {drop_services:drop_services },
success: function(data){
currentRow.find('input[name^="quantity"]').val(0);
currentRow.find('input[name^="unit_price"]').val(data);
var quantity =currentRow.find('input[name^="quantity"]').val();
var unitprice=currentRow.find('input[name^="unit_price"]').val();
var total = parseInt(quantity) * parseInt(unitprice);
currentRow.find('input[name^="total"]').val(total);
//var total=+currentRow.find('input[name^="total"]').val(total);
// $('#subtotal').val(total);
var sum = 0;
$('.total').each(function() {
if($(this).val()!='')
{
sum += parseInt($(this).val());
}
});
var sub = $('#subtotal').val(sum);
var fsub = $('#final_total').val(sum);
var tot_commi = 0;
}
});
});
</script>
PHP: ajax_service.php
<?php
include('connect.php');
if(isset($_POST['drop_services']))
{
$sql_service1 ="SELECT * FROM products WHERE id = '".$_POST['drop_services']."'";
$result1=$conn->query($sql_service1);
$service1 = mysqli_fetch_array($result1);
echo $service1['sale_price']; exit;
}
?>

Related

populate multiple select dropdownlist using Ajax

Im trying to populate my multiple dropdown list using ajax. but its not working. this dropdown list is dependent on another dropdown list which is single selection dropdown list.
Html Code is :
<div class="form-group">
<label for="InputGender">Select Course</label>
<div class="input-group">
<select class="form-control" name="sub_id" id="sub_id">
<option value="">Select Course Name</option>
<?php
while ($row = $result->fetch_row()) {
?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select>
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label>Second Level Category</label><br />
<select id="chap_id" name="chap_id[]" multiple class="form-control">
</select>
</div>
Ajax Code is:
$(document).ready(function(){
$("#sub_id").change(function(){
var id = $(this).val();
$.ajax({
url: 'AddQuestionAjax.php',
type: 'post',
data: {subId:id},
dataType: 'json',
success:function(response){
var len = response.length;
$("#chap_id").empty();
$("#chap_id").append("<option value=''>Select Chapter</option>");
for( var i = 0; i<len; i++){
var cid = response[i]['id'];
var cname = response[i]['name'];
$("#chap_id").append("<option value='"+cid+"'>"+cname+"</option>");
}
}
});
});
});
below is JSON response or the code writted in AddQuestionAjax.php file
<?php
session_start();
require 'conn.php';
$tSubId = $_POST['subId']; // department id
$sql = "SELECT * FROM chapter WHERE Subject_subId=".$tSubId;
$result = mysqli_query($con,$sql);
$sub_arr = array();
while( $row = mysqli_fetch_array($result) ){
$sid = $row['idChapter'];
$sname = $row['chapName'];
$sub_arr[] = array("id" => $sid, "name" => $sname);
}
// encoding array to json format*/
echo json_encode($sub_arr);
?>
I don't know about PHP section code but i've tried this. Just a example what you are doing here and it is working perfectly
<div class="form-group">
<label for="InputGender">Select Course</label>
<div class="input-group">
<select class="form-control" name="sub_id" id="sub_id">
<option value="">Select Course Name</option>
<option value="1">1</option>
</select>
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label>Second Level Category</label>
<br />
<select id="chap_id" name="chap_id[]" multiple class="form-control">
</select>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#sub_id").change(function() {
var response = [{
id: 1,
name: 'a'
}, {
id: 2,
name: 'b'
}];
for (var i = 0; i < response.length; i++) {
var cid = response[i]['id'];
var cname = response[i]['name'];
$("#chap_id").append("<option value='" + cid + "'>" + cname + "</option>");
}
});
});
</script>
you also need to parse the JSON before looping thorough your records. Which can be done by this
var res = JSON.parse(response);
Then parhaps you can add your records in select picker

Auto add checkbox values and keep their name for storing in database

I have checkboxes retrieved from my database with respective item_name and value which happen to be displayed correctly, but the values are being added/subtracted automatically when selected/checked. However, i want to save the selected check box item_names and also the total sum of the values from the checkboxes. I can't accomplish this because the value option holds numeric data which should have been the checkbox item_name; here is so far what i have.
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 0;
for (i=0;i<document.listForm.sel_car.length;i++) {
if (document.listForm.sel_car[i].checked) {
sum = sum + parseInt(document.listForm.sel_ca[i].value);
}
}
document.listForm.total.value = sum;
}
</script>
HTML/PHP Snippet
<h4>Available Cars | Click on desired car(Multiple Selections enabled) | Total Price: <input type="text" size="2" name="total" value="0"/></h4>
<div class="form-group">
<?php
$stmt = $DB_con->prepare('SELECT * FROM cars ORDER BY car_id DESC');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="col-md-3"><label class="btn btn-primary">
<img src="user_images/<?php echo $row['userPic']; ?>" alt="..." class="img-thumbnail img-check"><input type="checkbox" name="sel_car[]" id="item4" value="<?php echo $row['car_price']; ?>" class="hidden" autocomplete="off" onchange="checkTotal()"/>
<h5><?php echo $row['se_car_model']; ?> | UGX <?php echo $row['car_price']; ?>/=</h5>
</label></div>
<?php
}
}
?>
You should also retrieve id along with Item name and value and assign the id to the checkbox.
Add the hidden field in the form
<input type="hidden" name="itemsArr" id="itemsArr" value="">
checkbox
<input onclick="checkTotal(this)" type="checkbox" id="itemId" name="ItemName" value="ItemPrice">
Div showing total amount
<div id="totalDiv"></div>
script
<script type="text/javascript">
var arr = [];
var total = 0;
function checkTotal($this)
{
var varId= $this.id;
if ($($this).is(":checked")) {
arr.push(varId);
}
else
{
arr.splice( $.inArray(varId,arr) ,1 );
}
$("#itemsArr").val(arr);
// get the price of the item from the controller by passing id to controller
$.ajax({
type: 'POST',
url: BASE_URL+"controllerName/methodName",
data: {'id':varId},
success: function (data) {
data = JSON.parse(data);
total += data.price;
$("#totalDiv").html(total);
}
});
}
On sumbitting the form you will be getting the hidden value and then store it in the database
When you want to retrieve the value from the database you can get the field and convert that string into an array using explode function and do the further tasks.

Use value from a form in a redirect button outside the form

Fetch selected value from dropdown which is in one form and onClick of the button outside the form send the value to php page
<div class="drpvendorname">
<font style="color: white;">
<label>Distribution Point:</label>
</font>
</div>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option onClick="distribution('.$result['pointshortname'].')" value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form><!--form1 ends here-->
<form action="../customer/form.php"><!--form2 starts here-->
<button class="btn pos7" name="abc" method="GET" style="margin-left:5%;">New Customer</button>
</form><!--form2 ends here-->
<div class="dailybreakupbtn">
<input class="btn" type="submit" id="dailybreakupbutn" name="dailybreakup" value="Enter Daily Breakup" onClick="distribution(<?=$pointname?>)"/>
</div>
<?php
if(isset($pointname)){
?>
<script type="text/javascript">
function distribution(pointname){
var pointname;
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<?php
}
?>
I have tried this sending selected dropdown box value to next page using function name distribution
I ended sending undefined to the next page.
can any one help me sending the selected value to the next page with out putting the button in the <form>
May this will be help you :)
Html code:
<form action= "" method= "post">
<select class="form-control drpvendor" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="'.$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form>
JQuery Code:
$(doucment).on('change','.drpvendor',function(){
var data=$(this).attr('selected','selected');
$.ajax({
url: "dailybreakup.php",
data:'query='+ data,
type: "POST",
success: function(data) {
window.location.href='customer/form.php';
}
});
});
Use code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> // please link the path or use cdn
<script type="text/javascript">
function call_me(){
var pointname=document.getElementById("drpvendor").value;
alert(pointname); // comment it after testing
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<form>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
<input type="button" onclick="call_me()"/>
</form><!--form1 ends here-->
Note : 1) Code is not tested
2) use your select id instead of your_select_id
3) check variable

Option Menu with 2 Values

I have the following option menu in a form that will insert the fields into a table:
<option value="">select staff</option>
<?php
do {
?>
<option value="<?php echo $row_Staff['Staff_Name']."||".$row_Staff['Email']?>">
<?php echo $row_Staff['Staff_Name']?></option>
<?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
I have 2 fields from source table in value of option from technique explained in How to post two values in an option field?: Staff_Name and Email.
I am trying to insert both fields from the form into a table using:
<input type="hidden" name="Staff_Name" class="form-control" id="Staff_Name" value=<?php
$staff =$_POST['Staff_Data'];
$staff_name = explode("||", $staff);
echo $staff_Name[0];
?> />
and
<input type="hidden" name="Email" class="form-control" id="Email" value=<?php
$staff =$_POST['Staff_Data'];
$email = explode("||", $staff);
echo $email[1];
?> />
Unfortunately, I can see the 2 fields separated by "||" in the table if I insert the option menu value but cannot seem to insert Staff_Name or Email into individual fields. On insert both fields are blank. Any help would be appreciated.
Instead of combine staffname and staffemail in the dropdown value. Please staffname in dropdown value and staffemail in the property of dropdown and onchange of the dropdown set those values in the hidden inputs so you will easily get those values on the form submission.
Please go through below code and let me know if you have any query.
//Dropdown
<select id="ddStaff">
<option value="">select staff</option>
<?php
do { ?>
<option value="<?php echo $row_Staff['Staff_Name']; ?>" staff-email = "<?php echo $row_Staff['Email'];?>">
<?php echo $row_Staff['Staff_Name']?>
</option> <?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
//Input hidden fields to store staff name and staff email
<input type="hidden" id="txtStaffName" name="txtStaffName">
<input type="hidden" id="txtStaffEmail" name="txtStaffEmail">
//Jquery code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ddStaff").on('change',function(){
var staffName = $(this).val();
var staffEmail = $('option:selected', this).attr('staff-email');
$("#txtStaffName").val(staffName);
$("#txtStaffEmail").val(staffEmail);
});
});
</script>
Please check it on https://jsfiddle.net/z4a0fywp/
For testing purpose I have not made the inputs hidden in the fiddle.

Add form fields dynamically with php

Referring to this post. Add form fields dynamically populated dropdown list with php I have used his code but will modify it to fit my needs since I pretty much nothing about javascript. I have everything working except when you press the + button it never creates more input boxes. Any help would be great.
This my php file
<?php
session_start();
require_once("dbconfig.php");
?>
<html>
<head>
<script type="text/javascript" src="addfish.js"></script>
</head>
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
while($speciesq = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value=\"" . $speciesq['species'] ."\">" . $speciesq['species'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
</html>
My addfish.js file
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
;
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1')
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.speciesnumber1.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.speciesweight.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
This is my getlist.php
<?php
session_start();
include("dbconfig.php");
$stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
$result = array();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = array(
'value' => $rows['species'],
);
}
echo json_encode($result);
?>
Your code is using jQuery, but I don't see where you include this library. Try to put this code before include addfish.js in header :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you need to add rows with this fields dynamically I suggest you make a row which is the original row:
<div class="rows" data-rows="1">
<div class="row row-first">
<select name="row[0][select_name]">
<option value="1">Some value</option>
</select>
<input type="text" name="row[0][text_name]" />
</div>
</div>
and the javascript
<script type="text/javascript">
$('#add_row').on('click', function(){
var row = $('.row-first').clone(); // Clone the first row
var rows = parseInt($('.rows').attr('data-rows'));
rows++;
$('.rows').attr('data-rows', rows);
row.removeClass('row-first'); // Prevent multiple rows cloning
$(row).find('[name]').each(function(){
var name = $(this).attr('name');
name = name.replace(/\[[0-9+]\]/, '[' + rows + ']');
$(this).attr('name', name);
$(this).val("").change(); // Null the select
});
$('.rows').append(row);
});
</script>
So what you do is clone the first row and remove the class, which you search. Increment the rows count and replace all names in you row with the new row number e.g. row[0][name] becomes row[1][name], and append the row.
Also when you edit the rows you MUST put set the data-rows to the exact number. You can do it like count($myRows). And when you write the remove row function DO NOT REMOVE the first row.
Hope it hepls.
// You can use this
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);

Categories