I am trying to create a form with three select dropdown lists. user selects an option from select1 and based on the selected option, select2 gets populated, then user selects an option from select2 and based on selection, select3 gets populated.
following an example on stackoverflow I created this. the lists are getting populated fine but values are not passed when I hit submit button. if i select options from select1 and select2 only then values do get passed, but when i select option from select3 then no values are passed.
This is my PHP:
<?php
require "php/db.inc";
$db = new mysqli($hostName, $username, $password,'mms');//set your database handler
$query = "SELECT AcID, AcName FROM accounts WHERE ParentAcID ='0'";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$accountgroups[] = array("id" => $row['AcID'], "val" => $row['AcName']);
}
$query = "SELECT AcID, AcName, ParentAcID FROM accounts";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$accounts[$row['ParentAcID']][] = array("id" => $row['AcID'], "val" => $row['AcName']);
}
$query = "SELECT AcID, AcName, ParentAcID FROM accounts";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subaccounts[$row['ParentAcID']][] = array("id" => $row['AcID'], "val" => $row['AcName']);
}
$jsonAcGroup = json_encode($accountgroups);
$jsonAc = json_encode($accounts);
$jsonSubAc = json_encode($subaccounts);
?>
This is my Javascript:
<script type='text/javascript'>
<?php
echo "var account_group = $jsonAcGroup; \n";
echo "var accounts = $jsonAc; \n";
echo "var sub_accounts = $jsonSubAc; \n";
?>
function loadAccountGroup(){
var select = document.getElementById("AcGroupSelect");
select.onchange = updateAccount;
for(var i = 0; i < account_group.length; i++){
select.options[i] = new Option(account_group[i].val,account_group[i].id);
}
}
function updateAccount(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("AcSelect");
AcSelect.options.length = 0; //delete all options if any present
subcatSelect.onchange = updateSubAccount;
for(var i = 0; i < accounts[catid].length; i++){
subcatSelect.options[i] = new Option(accounts[catid][i].val,accounts[catid][i].id);
}
}
function updateSubAccount(){
var catSelect2 = this;
var catid2 = this.value;
var subcatSelect2 = document.getElementById("SubAcSelect");
SubAcSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < sub_accounts[catid2].length; i++){
subcatSelect2.options[i] = new Option(sub_accounts[catid2][i].val,sub_accounts[catid2][i].id);
}
}
function start() {
loadAccountGroup();
updateAccount();
updateSubAccount();
}
window.onload = start;
</script>
This is my FORM:
<form class="form" method="post" action="form_test.php">
<table class='table table-striped'>
<tr>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Account Group</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Account</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Sub Account</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Debit</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Credit</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<select class="form-control" name="AcGroupSelect" id='AcGroupSelect'></select>
</div>
</td>
<td>
<div class="form-group">
<select class="form-control" name="AcSelect" id='AcSelect'></select>
</div>
</td>
<td>
<div class="form-group">
<select class="form-control" name="SubAcSelect" id='SubAcSelect'></select>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="col-sm-1 form-control" name="DebitAmount" placeholder="Debit Amount">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="col-sm-1 form-control" name="CreditAmount" placeholder="Credit Amount">
</div>
</td>
</tr>
</table>
I had a similar problem. Once you get your values from the drop down list you still need to somehow put them into you form and submit them.
have a look at this I managed to solve it like this.
Populating the third menu based on previous dropdown values
Also have you got a submit button? Can't see how you submit in your form. Also missing closing form tag
Finally I figured it out. this script works just fine. the problem was not in the script but rather in the html. the top menu was hiding one line output n i was banging my head for getting the blank page.
Related
i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
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;
}
?>
i created a dynamic form where you can add a form group. on a second page the input is sent by post. if i add more than one field, the radio buttons don't work anymore and the mail delivery doesn't work either
I tried to make a for-loop, but doesnt worked..
index.php (dynamic form):
<script>
var ct = 1;
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// link to delete extended form elements
var delLink = '<div style="text-align:right;margin-right:65px">Delete</div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
</script>
<style>
#newlink {width:600px}
</style>
<form method="post" action="index2.php">
<div id="newlink">
<div>
</div>
</div>
<p>
<br>
<input type="submit" name="submit1">
</p>
<p id="addnew">
New
</p>
</form>
<div id="newlinktpl" style="display:none">
<div>
<table>
<tr>
<label>Ordner:</label>
<td> <input type="text" name="linkurl[]" value="" placeholder="New Folder" required></td>
</tr>
<tr>
<td>
<label>Write</label>
<input type="radio" name="berechtigung[] " value="W">
</td>
<td>
<label>Read</label>
<input type="radio" name="berechtigung[] " value="R">
</td>
<td>
<label>None</label>
<input type="radio" name="berechtigung[] " value="K ">
</td>
</tr>
</table>
</div>
</div>
index2.php: (POST-DATA)
<?php
if(count($_POST))
{
$len = count($_POST['linkurl']);
for ($i=0; $i < $len; $i++)
{
echo $_POST['linkurl'][$i] . '<br>';
echo $_POST['berechtigung'][$i] . '<br>';
}
}
?>
I have one search box on home page. when user enter the some value on home.php then that page goes to select.php. On select page i have filters with checkboxes, radio button & price range filter.
I have tried some jquery on click of radio button but its value are coming and sql query giving error. I want to filter out my result according to selection of radio button, checkboxes & price range. so please suggset any to me.
i have tried following code for this,
$("#localityid2").click(function () {
var search_keyword = $("#localityid2").val();
$.ajax({
type: "POST",
url: "select.php",
data: search_keyword ,
success: function () {
window.location.href = "select.php?locality="+search_keyword;
}
});
return false;
});
<table class="sbox">
<tr>
<td>
<div class="radiobtn">
<input type="radio" name="location" class="locality" id="localityid1" value="Aundh" style="float: none;">
</div>
<div class="text">Aundh</div>
</td>
</tr>
<tr>
<td>
<div class="radiobtn">
<input type="radio" name="location" class="locality" id="localityid2" value="Baner" style="float: none;"> </div>
<div class="text">Baner</div>
</td>
</tr>
<tr>
<td>
<div class="radiobtn">
<input type="radio" name="location" class="locality" id="localityid3" value="Ravet" style="float: none;">
</div>
<div class="text">Ravet </div>
</td>
</tr>
<tr>
<td>
<div class="radiobtn">
<input type="radio" name="location" class="locality" id="localityid4" value="Wakad" style="float: none;">
</div>
<div class="text">Wakad</div>
</td>
</tr>
</table>
<h3 style="margin-top: 19px;">Price Range</h3>
<div class="slide-result">
<div id="price-range"></div>
<div class="slide-result">
<input disabled class="amount1" type="text" id="pr1" value="1000" />
<input disabled class="amount2" type="text" id="pr2" value="600000" />
</div>
<div class="clear"></div>
</div>
<h3>AC/Non AC</h3>
<table class="sbox">
<tr>
<td>
<div class="radiobtn">
<input type="checkbox" name="actype[]" class="checkboxclass" value="&actype=1" style="float: none;" />
</div>
<div class="text">AC</div>
</td>
</tr>
<tr>
<td>
<div class="radiobtn">
<input type="checkbox" value="&actype=0" name="actype[]" class="checkboxclass" style="float: none;" />
</div>
<div class="text">Non Ac</div>
</td>
</tr>
</table>
include("db.php");
$city = $_POST['city'];
list($localitys, $citys) = explode(' - ', $city, 2);
$_SESSION['city'] = $citys;
$_SESSION['localitys'] = $localitys;
$_SESSION['event'] = $_POST['events'];
if(isset($_GET['locality']))
{
$sql= mysql_query("SELECT * FROM hall_search_data_1 WHERE city_name='".$_SESSION['city']."' AND hall_evnt_type LIKE '%".$_SESSION['event']."%' AND locality = '".$_GET['locality']."' ")or die(mysql_error());
}
else
{
$sql= mysql_query("SELECT * FROM hall_search_data_1 WHERE city_name='".$_SESSION['city']."' AND hall_evnt_type LIKE '%".$_SESSION['event']."%' ")or die(mysql_error());
}
while($row=mysql_fetch_row($sql))
{
///here my content will print
}
here some screen shot my select.php page
when i select any radio button then giving error like this
From the comments, I can suggest following fixes to your code.
<?php
include("db.php");
$city = '';
if(isset($_POST['city']))
{
$city = $_POST['city'];
list($localitys, $citys) = explode(' - ', $city, 2);
$_SESSION['city'] = $citys;
}
if(isset($_GET['localitys']))
{
$_SESSION['localitys'] = $localitys;
}
if(isset($_POST['events']))
{
$_SESSION['event'] = $_POST['events'];
}
$sql = "";
if(isset($_GET['locality']))
{
$sql .= "SELECT * FROM hall_search_data_1 WHERE 1 = 1 ";
if(isset($_SESSION['city']) && !empty($_SESSION['city']))
$sql .= " AND city_name='".$_SESSION['city']."' ";
if(isset($_SESSION['event']) && !empty($_SESSION['event']))
$sql .= " AND hall_evnt_type LIKE '%".$_SESSION['event']."%' ";
if(isset($_GET['locality']) && !empty($_GET['locality']))
$sql .= " AND locality = '".$_GET['locality']."' ";
mysql_query($sql) or die(mysql_error());
}
else
{
$sql .= "SELECT * FROM hall_search_data_1 WHERE 1 = 1 ";
if(isset($_SESSION['city']) && !empty($_SESSION['city']))
$sql .= " AND city_name='".$_SESSION['city']."' ";
if(isset($_SESSION['event']) && !empty($_SESSION['event']))
$sql .= " AND hall_evnt_type LIKE '%".$_SESSION['event']."%' ";
mysql_query($sql) or die(mysql_error());
}
?>
Also try printing $_POST and $_SESSION arrays so that you can come to know whether all parameters are passing/ passing correctly and all the sessions are setting up properly.
I create a search form that using ajax as the action. In success ajax, how can I just load some specific div without load all refresh page.
This is my form
<?php
$properties = array('id' => 'form1');
echo form_open("", $properties);
?>
<fieldset>
<div class="controls" id="chekboxes">
<label class="checkbox "><input type="checkbox" name="criteria[]" id="nomorcb"/> Nomor Request </label>
<input type="text" class="input-xlarge focused" id="no" name="no" placeholder="Masukkan No Request..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="namacb"/> Nama User </label>
<input type="text" class="input-xlarge focused" id="nama" name="nama" placeholder="Masukkan Nama User..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="departementcb" /> Departement</label>
<div class="control-group">
<div class="controls">
<select class="input-xlarge" id="selectError" name="dep">
<option value="">-- Pilih departement --</option>
<?php
foreach ($dep as $data) {
echo "<option value='" . $data['nama_departement'] . "'>" . $data['nama_departement'] . "</option>";
}
?>
</select>
</div>
</div>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="rentangcb"/> Rentang waktu</label>
<div class="controls" id="tanggal-rentang">
<input type="text" class="input-small datepicker" id="tanggal" value="" name="tgl_awal"><span> s/d </span>
<input type="text" class="input-small datepicker" id="tanggal2" value="" name="tgl_akhir">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit">Cari</button>
<button type="reset" class="btn" id="cancel">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
this is the action's code for execute the form.
public function search() {
$id_request = $this->input->post('nomor');
$nama_user = $this->input->post('nama');
$departement = $this->input->post('departement');
$awal = $this->input->post('tgl_awal');
if ($awal != "") {
$awal = $this->input->post('tgl_awal');
} else {
$awal = "2014-01-01";
}
$timestamp_awal = strtotime($awal);
$tgl_awal = date("Y-m-d H:i:s", $timestamp_awal);
$akhir = $this->input->post('tgl_akhir');
if ($akhir != "") {
$akhir = $this->input->post('tgl_akhir');
} else {
$akhir = "2020-01-01";
}
$timestamp_akhir = strtotime($akhir);
$tgl_akhir = date("Y-m-d H:i:s", $timestamp_akhir);
$data = $this->model_request->search($id_request, $nama_user, $departement, $tgl_awal, $tgl_akhir);
echo json_encode($data);
}
and this is the Ajax jquery for form above :
$('form').on('submit', function() {
var nomor = $('#no').val();
var nama = $('#nama').val();
var departement = $('#selectError').val();
var tgl_awal = $('#tanggal').val();
var tgl_akhir = $('#tanggal2').val();
$.ajax({
url: '<?php echo base_url() . 'it_team/control_it/search' ?>',
type: 'POST',
data: {nomor: nomor,
nama: nama,
departement: departement,
tgl_awal: tgl_awal,
tgl_akhir: tgl_akhir},
dataType: 'json',
success: function(obj) {
//Please give me an idea
}
});
return false;
For testing, I try seearch and thank God, it gives me a success on json like this:
[{"id_request":"015","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 02:51:05"},
{"id_request":"017","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 13:32:46"}]
My problem is, the result of search form above will be displaying into a table in same page with the form above. You know, in tbody's table will be generate the object on based the return of json. I am newbie using json. The table looked like this
<div class="box-content" id="things_table2">
<table class="table table-bordered table-striped table-condensed" id="table1">
<thead>
<tr>
<th>No. </th>
<th>No Request</th>
<th>Nama user</th>
<th>Departement</th>
<th>Tanggal Request</th>
<th>Action</th>
</tr>
</thead>
<tbody id="hasil-pencarian">
// Result will be showing here
</tbody>
</table>
</div>
Any help it so appriciated.
Try like this (beware there are less fields in your json than in your table):
var data = [
{
'id_request': '015',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 02:51:05'
},
{
'id_request': '017',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 13:32:46'
}
];
var html = '';
for (var i = 0; i < data.length; i++) {
var td="";
for(var key in data[i]){
td+='<td>'+data[i][key]+'</td>';
}
html+="<tr>"+td+"</tr>";
}
$('#hasil-pencarian').html(html);
There is nothing special about json. Treat it like any js object, ie after parsing it.
Since its just an array of objects, you can iterate over it and do whatever.
var html = '';
$.each(data, function (index, element) {
// build your html
html += '<tr>;'
html += '<td>'+ index + 1 + '</td>';
html += '<td>'+ element.id_request + '</td>';
// same for other elements use `element.<key-name>`
// end tr after all the td's are done
html += '</tr>;'
});
Once you have iterated over all the elements, inject it in the dom.
$('.DOM-ELEMENT').html(html);