Populate dropdown depending on the value of an other dropdown [duplicate] - javascript

This question already has an answer here:
Populating a select box using JQUERY, AJAX and PHP
(1 answer)
Closed 6 years ago.
I have a PHP form where a dropdown is populated with values from a database table.
$options_demande['orderBy'] = array('id_produit' => 'ASC');
$options_demande['items'] = array('produit');
$data['id_produit'] = $this->produit_model->getListCombo('*',null,$options_demande,'Sélectionner un produit');
$options_demande['orderBy'] = array('id_abonnement' => 'ASC');
$options_demande['items'] = array('abonnement');
$data['id_abonnement'] = $this->abonnement_model->getListCombo('*',null,$options_demande,'Sélectionner un abonnement');
The getListCombo method :
public function getListCombo($select = '*', $conditions = array(), $optional = null, $first_line = null)
{
$dropdown = array();
if ($select != null)
$this->db->select($select)->from($this->table);
if (isset($conditions['where']))
$this->db->where($conditions['where']);
if (isset($conditions['where_in']))
$this->db->where_in($conditions['where_in']);
if (isset($conditions['where_or']))
$this->db->or_where($conditions['where_or']);
if (isset($conditions['like']))
$this->db->like($conditions['like']);
if (isset($conditions['like_or']))
$this->db->or_like($conditions['like_or']);
if (isset($optional['orderBy']))
foreach($optional['orderBy'] as $order => $val)
$this->db->order_by($order,$val);
$rs = $this->db->get()->result_array();
if (isset($first_line))
{
if (is_array($first_line))
$dropdown[$first_line['k']] = $first_line['v'];
else
$dropdown[''] = $first_line;
}
foreach($rs as $item){
$liste = null;
foreach($optional['items'] as $item_liste){
$liste .= $item[$item_liste]." ";
$dropdown[$item['id_' . $this->table]] = $liste;
}
}
return $dropdown;
}
The thing is that I want an other dropdown to be populated with specific values of an other table.
The code of my dropdown :
<div class="form-group">
<label class="col-md-2 control-label" for="id_produit"><?php echo lang('produit'); ?><span class="required"> * </span></label>
<div class="col-md-4">
<?php echo form_dropdown('id_produit', $id_produit, null,'class="form-control" required="required"')?>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="id_abonnement"><?php echo lang('abonnement'); ?><span class="required"> * </span></label>
<div class="col-md-4">
<?php echo form_dropdown('id_abonnement', $id_abonnement, null,'class="form-control" required="required"')?>
</div>
</div>
I think I have to use some javascript, but I don't know how to do that.
At the moment the other is populated with all the values of the other table, but I'd like for example that for a specific value of the first dropdown, the other is populated with the values of the other table where "type_abonnement" = 1. Or 2 for an other value.

Yes, you will need to use JavaScript to achieve this.
There's hundreds of topics on this already, check out: Populating a select box using JQUERY, AJAX and PHP for example.

Related

how do I populate html form fields from a dynamic form dropdown

I am trying to figure out a way to fill html form fields based on the selection of a dynamic form dropdown menu.
I have been looking around and trying to tweek what I have found. So far I am up to filling one of my form fields. But have no gone off piste trying to fill all three, leaving the radio empty when I want it to pick up the 0 value on all my dummy entries and select enable (0)
<option value="<?= $row['ENABLED2'] . " - " . $row['ID2'] . " - " . $row['SOLDTO2'] ?>"> ..</option>
<?php
}
?>
</select>
...
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
});
});
</script>
...
<FORM id='addClient' action='process/process-addclient.php' method='post'>
<input type='text' id='ID2' name='ID2' maxlength='4' placeholder='Four Digit Sage Code' style='display:inline'>
<textarea id='SOLDTO2' name='SOLDTO2' placeholder='Client Name and Address - 6 Lines Max'></textarea>
<input type="radio" name='ENABLED2' id='enable' value='0'> <label for='enable'>Enable Client</label>
<input type="radio" name='ENABLED2' id='disable' value='1'> <label for='disable'>Disable Client</label>
In writing this out I have answered some of my own questions but I cant figure out how to get the last column (radio) to populate.
I am new to JS/JQ
The way to populate the radio field is by using the following code:
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
//Check radio field based on value of GetValueEn
if (GetValueEn == 0) {
$("#enable").prop('checked', true);
}
else {
$("#disable").prop('checked', true);
}
});
});
</script>

Javascript generated select not posting in PHP

I have searched far and wide and have not seen an answer for this. Forgive me if one exists.
I have a PHP page, in which user can generate new html select fields by pressing a button. I use Javascript to generate the new select fields. The user can then select one option from the generated select field. I need the value the user chose in PHP code below the form, to submit the form values to database.
My problem is that PHP doesn't seem to recognize the new generated select fields, which is why it won't post.
var_dump($_POST) doesn't show the new select field. I have also tried to name the new select as name="choice1[]", but that also has not posted. Choice1 is always undefined.
All of my code is on the same PHP page, apart from sql query to populate the select options.
This is what Javascript generates inside a form:
<select class="form-control" id="choose1" name="choice1">
<option value="1:x">Text</option>
<option value="2:y">Text</option>
<option value="3:z">Text</option>
</select>
This is where I try to get the value, after submit button is pressed:
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr1[0];
$tName = $arr1[1];
}
The Javascript works fine, the values are shown on the page fine. The only part not working is the post method (well, only for this specific select field. Other's work fine, as those are hard coded to html). Submit button works fine, everything else gets submitted.
My question is if there is a way for me to get the post values in PHP without reloading the page?
Or if reload is needed, how to do this without closing the form modal?
Or even more of a general question would be.. How do I do this?
EDIT:
Here is my form code. I deleted bunch of other stuff from it just to show the parts I have the problem with. If the divs are weird, it's because of that.
<form class="form-horizontal" method="post" action="">
<div class="modal-header">
<h4 class="modal-title">Change</h4>
</div>
<div class='modal-body'>
<div class='row'>
<label class="col-sm-3"> Product: </label>
<div class="col-sm-8" id="selectProd">
<!-- **This is where new select is generated** -->
<select class='form-control' id='valinta' name='choice'>
<?php
$sql0= "SELECT tuotenro, tuotenimi FROM vaateHenkilot WHERE asnro = '". $_GET['b']."' AND henknro = '". $_GET['a']."' GROUP BY tuotenro, tuotenimi";
$req = sqlsrv_query($con, $sql0) or die(print_r(sqlsrv_errors(),true));
$t = '';
while($row = sqlsrv_fetch_array($req)) {
$t = array(
array (
'nro' => $row['tuotenro'],
'nimi' => $row['tuotenimi'],
)
);
$tuotteetIN = array_column($t, 'nimi', 'nro');
foreach($tuotteetIN as $key => $value) {
?>
<option value="<?php echo $key ?>:<?php echo $value ?>"><?php echo $value ?></option>
<?php
}
}
?>
</select>
<br>
</div>
<div class="col-sm-1">
<button type='button' class='btn' onclick='addSelectBox()'>+</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" name="saveButton">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
<?php
if (isset($_POST['saveButton'])) {
$choice = $_POST["choice"];
$parts = $choice;
$arr = explode(':', $parts);
$tNum = $arr[0];
$tName = $arr[1];
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr[0] . ', ' . $arr1[0];
$tName = $arr[1] . ', ' . $arr1[1];
}
*Here is the sql query*
}
?>
I have another select there, which has the same values. That one works well.
I'll add the Javascript here that creates the new select, as well.
<script type="text/javascript">
var j = 0;
function addSelectBox (){
if (j < 3){
var parentDiv = document.getElementById ("selectProd");
var selectElement = document.createElement ("select");
j++;
selectElement.setAttribute("class", "form-control");
selectElement.setAttribute("id", "choose" + j);
selectElement.setAttribute("name", "choice" + j);
var tuotteet = '';
$.ajax({
type: 'GET',
url: 'productHelp.php?asi=<?php echo $asnro; ?>&hen=<?php echo $henro; ?>',
data: tuotteet,
datatype: 'json',
cache: false,
success: function (data) {
var tnimi = data.split(";");
for (var i=0;i < tnimi.length -1;i++){
var tnro = tnimi[i].split(",");
var option = new Option (tnro[1], tnro[0]+":"+tnro[1]);
selectElement.options[selectElement.options.length] = option;
}
}
});
parentDiv.appendChild (selectElement);
parentDiv.appendChild(linebreak);
}
}
</script>
Turns out the problem was as "stupid" and simple as I figured it had to be.
Taking the modals with the functionality out from the table structure made it work fine.
Good to learn something new about formatting everyday!

Validate if more than one item was selected using jquery

This code allows the user to select one or more models of cars graphically on a web page. I am in need to check if more than one was selected. How can I get this to count the number of selected items and if it's great than one alert("something")?? In short, I need to know if both Lexus and Inifiti were chosen in the example code here. I really need the count so if it's greater than 1 selected. Any help is great appreciated, not sure what I am doing wrong .
<div class="options-item-wrapper clearfix">
<?php
$modelOptions = array(
0 => array('title' => 'Lexus'),
1 => array('title' => 'Infiniti')
);
foreach ($modelOptions as $modelOption) {
$selected = '';
$optionValue = '';
if(in_array($modelOption['title'], $modelArray)) {
$selected = 'selected';
$optionValue = '<input class="vehicle-option"
type="hidden" name="model[]"
value="'.$modelOption['title'].'">';
}
echo '<div class="options-item '.$selected.'" data-vehicle="'.
$modelOption['title'].'">
<div>'.$modelOption['title'].'</div>
'.$optionValue.' </div>';
}
?>
</div>
I have tried this but no luck thus far :
var checkedNum = $('input[name="model[]"]:selected').length;
alert(checkedNum);
if (checkedNum > 1) {
alert('Validating the form2');
// User didn't check any checkboxes
} else {
die();
}
Your code doesn't work because hidden input elements don't have a selected state.
If I understand your code correctly, you add the class 'selected' to your options items if they're selected. Wouldn't you just need to count the number of options items with the selected class?
var checkedNum = $('.options-item.selected').length;
alert(checkedNum);
if (checkedNum > 1) {
alert('Validating the form2');
// User didn't check any checkboxes
} else {
die();
}

How to pass same class/id name php values from radio button to javascript?

This is my problem. I am looping items from the database that contains items name and id. I have a radio button for each items. The id of that item is stored in the radio buttons value....Now what i want to achieve is when i click on the submit button,it will call a function call save() in javascript and save all the selected items ONLY .... i've been trying this for hours but i cant get it worked.
Here are my codes....
When i do my while looping from the DB, it will display the radio button and the items name...
<?php
$retrieveQuery = "SELECT * FROM `itemdb` WHERE `approve`= 1 AND `userId` = '$userId';";
$retrieveresult = mysqli_query($dbconnect, $retrieveQuery);
if(mysqli_num_rows($retrieveresult) > 0)
{
while($retrieverow = mysqli_fetch_assoc($retrieveresult))
{
?>
<p> </p>
<div style="background-color: rgba(0, 0, 0, 0.16);">
<input style="margin-bottom: -19px;" type="checkbox" class="item" name="item[]" value=<?php echo $retrieverow['itemID'] ?>>
<p style="margin-left: 26px;"><?php echo $retrieverow['itemName'] ?></p>
<p style="margin-top:-10px;margin-left:28px"><i><?php echo $retrieverow['category'] ?></i></p>
</div>
<?php
}
}
else
{
echo "Test : There is no approve Items to be displayed";
echo "Either wait for the admin to approve or upload items to start Trading ! ";
}
?>
This is my script:(How can i save my items?)
function save()
{
var f = document.getElementsByClassName('item').value; //my own items chosen frm invntry
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("confirmTrade").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","trade.php?f="+f,true);
xmlhttp.send();
}
Right after i click the save() function it will send the data to another page using ajax method....
PS: Everything works fine...Other variables are passed successfully but only one item variable is being passed....
Thanks in advance!
Without looking into it too much, take a look at this line:
var f = document.getElementsByClassName('item').value;
document.getElementsByClassName gets an HTMLCollection of elements, so calling value on this doesn't make much sense. You'll need to loop through them and find the selected ones. I have it building an array then joining it into a comma separated list:
var checkboxes = document.getElementsByClassName('item');
var f = [];
for(var i = 0; i < checkboxes.length; i++){
if(checkboxes[i].checked == true)
f.push(checkboxes[i].value);
}
f = f.join();//makes comma seperated list
//proceed with ajax call

Retrieving values from data base, store in input text and textarea, change, pass new one to DB using PHP?

I'm Trying to change the values in the database using PHP and MySQL.
I am getting the values from database and storing them in placeholder for each input but when i submit the form again it submit the inputs with empty values, i tried storing them in Value attribute for each input again the old value is overwriting what i write in the input field so nothing in the database change.
How can i keep the old value in the input fields but in case the content of these fields changed the new value is passed back to the database instead of the old one.
Here is my Code :
function list_products () {
$get = mysql_query('SELECT `id`, `SKU`, `sub`, `pname`, `desc`, `price`, `ship`, `qty`, `cat` FROM `products` ORDER BY `id` DESC');
if (mysql_num_rows($get) == 0) {
echo "There are no product to display!";
} else {
while ($get_row = mysql_fetch_assoc($get)) {
echo
'<h5>'.$get_row['pname'].' id: '.$get_row['id'].'</h5>
<form action="delete_product.php" method="post">
<input type="hidden" value="'.$get_row['id'].'" name="id">
<input type="submit" name="submit" value="DELETE" class="btn btn-lg btn-danger">
</form>
<form action="update_p.php" method="post">
<input type="hidden" placeholder="'.$get_row['id'].'" name="id" value="'.$get_row['id'].'">
<label>SKU:</label>
<input type="text" placeholder="'.$get_row['SKU'].'" name="SKU" value="'.$get_row['SKU'].'" required="">
<label>Name:</label>
<input type="text" placeholder="'.$get_row['pname'].'" name="pname" required="" value="'.$get_row['pname'].'">
<label>Subtitle:</label>
<textarea rows="2" maxlength="46" name="desc" placeholder="'.$get_row['sub'].'" required="">'.$get_row['sub'].'</textarea>
<label>Description:</label>
<textarea rows="4" name="desc" placeholder="'.$get_row['desc'].'" required="">'.$get_row['desc'].'</textarea>
<label>Price:</label>
<input type="text" placeholder="'.number_format($get_row['price'], 2).'" name="price" value="'.number_format($get_row['price'], 2).'" required="">
<label>Shipping:</label>
<input type="text" placeholder="'.number_format($get_row['ship'], 2).'" name="ship" value="'.number_format($get_row['ship'], 2).'" required="">
<label>Quantity:</label>
<input type="text" placeholder="'.$get_row['qty'].'" name="qty" value="'.$get_row['qty'].'" required="">
<label>Category:</label>
<input type="text" placeholder="'.$get_row['cat'].'" name="cat" value="'.$get_row['cat'].'" required=""><br>
<input type="submit" name="submit" value="EDIT" class="btn btn-success btn-lg">
</form>
<hr>
';
};
}
}
The update_p.php page:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$update_data = array(
'pname' => $_POST['pname'],
'desc' => $_POST['desc'],
'price' => $_POST['price'],
'ship' => $_POST['ship'],
'qty' => $_POST['qty'],
'cat' => $_POST['cat']
);
update_product($id, $update_data);
The update_data function :
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `products` SET " . implode(', ', $update) . " WHERE `id` = $id");
}
#MaveRick Thanks for the effort, but my question is how to overwrite the value of the input fields on the page before we send the information to the server, i think its can be done using JavaScript more than php, however to make more clear these input fields refers to values in the database already stored and i would like to give the option for the user to change them in his admin panel by retrieving the content of these fields from the database and print them in the actual input fields so in case the customer pressed edit(submit) with out touching anything the same values will be sent again to the database this way nothing will be change, and in another case where the customer added or changed any value in any of these fields then the new value will be passed. hopefully i clarified my issue now. Thanks for your help anyway.
#Prafful Garg i already tried the value field but it didn't work thanks for your help anyway
You can retrieve the data again from the database in file update_p.php as follow:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM `products` WHERE `id` = '$id';");
$get_row = mysql_fetch_assoc($get);
$update_data = array(
'pname' => (empty($_POST['pname'])?$get_row['pname']:$_POST['pname']),
'desc' => (empty($_POST['desc'])?$get_row['desc']:$_POST['desc']),
'price' => (empty($_POST['price'])?$get_row['price']:$_POST['price']),
'ship' => (empty($_POST['ship'])?$get_row['ship']:$_POST['ship']),
'qty' => (empty($_POST['qty'])?$get_row['qty']:$_POST['qty']),
'cat' => (empty($_POST['cat'])?$get_row['cat']:$_POST['cat'])
);
update_product($id, $update_data);
But this is not a professional way to do it.
What you can do is a loop to create the update statement and test each input; if not empty then add to the update statement , name=value otherwise to skip this input and process the next one in the array POST. something similar to the following:
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$query = "UPDATE `products` SET `id` = '$id'";
foreach($update_data AS $k=>$v){
if(!empty($v) && strlen($v)>0)
$query .= ", `".$k."` = '".$v."'";
}
$query .= " WHERE `id` = '$id';";
mysql_query($query);
}
IMPORTANT NOTE: mysql() is vulnerable and deprecated, please try to avoid using mysql() and use mysqli() or dbo() extensions instead.

Categories

Resources