Populate html dropdown list dynamically from other dropdown - javascript

I have two dropdown lists, the first is populated from database and works fine, the second dropdown must be populated dynamically from what user has chosen from the first dropdown list. For example, my first dropdown contains many country's name, when user choose a country, the second dropdown will be populated by city's of that country which are in same database. Have anyone an example of this?
This is the first dropdown list
<select size="1" name="listeOrg">
<option value = "0" selected>---Choisir une région---</option>
<?php
$link3 = mysql_connect_db();
$query3 = "SELECT nom_region FROM region ";
$result3 = mysql_query($query3, $link3) or die();
while ($row = mysql_fetch_array($result3)) {
echo '<option value="'.$row['nom_region'].'">'.$row['nom_region'].'</option>';
}
mysql_close($link3); ?>
</select>
And the second:
<?php
$link4 = mysql_connect_db();
$selectregion=$_POST['listeOrg'];
$query4 = "SELECT organisme FROM region_organisme where nom_region='$selectregion' ";
$result4 = mysql_query($query4, $link4) or die();
while ($row2 = mysql_fetch_array($result4)) {
echo '<option value="'.$row2['nom_region'].'">'.$row2['nom_region'].'</option>';
}
mysql_close($link4); ?>
<option value="1" >autre
</select>

I found finally a good solution with a proper code. This is the link to the tutorial if someone has been stacked on this case.
A good explained tutorial with demo

Related

How to add select boxes dynamically through add button then save the values in mysql through php

Okay My problem is little complex which I am unable to solve. I already have two select boxes in which the options are coming from Database Mysql through php. Like when I select an option in Select Box#1, Select Box#2 gets updated through ajax and displays the options against SelectBox#1 from MYSQL Database. I am able to store the values from those two in database as well.
Problem
:
Now the problem is that I want a button like "Add New" that should create same two select boxes with same functionality the number of times i click Add New Button. Example: I filled the original two select boxes, then I click Add New and two new select boxes gets generated.. I fill them and again click Add New and two more select boxes gets generated so total of 6 select boxes with same first Select Box options but options in Second Select Box may differ according to the option selected in first select box. Now, two things I need help in:-
1. How to perform this Add New button thing that generates select boxes with same functionality as the original ones i.e Select Option from First Select Box, Second Select Box gets auto updated according to the option selected in first select box and the options are fetched from Database.
2. How do I read and store those values selected from new fields? I am able to read and store values that were passed from the original two select boxes but how about the new ones? Any unique names or ids of new select boxes I generate through button or some sort of array etc?
Here is my code that I used for my first two select boxes:-
HTML FILE-TOP
function load_country()
{
$connection = new mysqli("localhost","root","","test");
$query = "SELECT * FROM country";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["c_id"].'">'.$row["c_name"].'</option>' ;
}
return $output;
}
HTML FILE-INSIDE
<form method="post">
<p> <select name="country" id="country">
<option value="">Select Country</option>
<?php echo load_country() ?>
</select> </p>
<p> <select name="city" id="city">
<option value="">Select City</option>
</select> </p>
<input type="submit" name="submit" value="submit">
</form>
Jquery/Ajax Function that updates the Second Select Option:-
$(document).ready(function(){
$('#country').change(function(){
var country_id = $(this).val();
$.ajax({
url:"fetch_city.php",
method:"POST",
data:{
"c_id":country_id
},
dataType: "text",
success:function(data)
{
$('#city').html(data);
}
});
});
});
</script>
PHP File used by Ajax to Update Second Select Box:-
$output = '';
$query = "SELECT * FROM cities WHERE country_id = '{$_POST["c_id"]}'";
$result = mysqli_query($connection,$query);
$output = '<option value="">Select City</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["city_id"].'">'.$row["city_name"].'</option>' ;
}
echo $output;
First Change the HTML into something like this, use classes and ids for finding objects better:
<form method="post">
<div id="form-area">
<div class="select-box" id="box_1">
<p>
<select class="country" name="country[]">
<option value="">Select Country</option>
<?php echo load_country() ?>
</select>
</p>
<p>
<select class="city" name="city[]">
<option value="">Select City</option>
</select>
</p>
</div>
</div>
<button id="add_new" type="button"> [+] </button>
<input type="submit" name="submit" value="submit">
</form>
javascript:
$(document).on("change", ".country", function() {
var current_box = $(this).parent().closest('div').attr('id');
var country_id = $(this).val();
$.ajax({
url: "fetch_city.php",
method: "POST",
data: {
"c_id": country_id
},
dataType: "text",
success: function(data) {
$('#' + current_box).find(".city").html(data);
}
});
});
var id = 1;
$('#add_new').click(function() {
id++;
$(".select-box:last").clone().attr("id", "box_" + id).appendTo("#form-area");
});
After that, you should handle Array input in PHP form destination code.
In your case it should be something like this:
$cities = $_REQUEST['city'];
$cuontries = $_REQUEST['cuontry'];
foreach( $cuontries as $key => $cuontry ) {
$row[] = [ "cuontry" => $cuontry , "city" => $cities[$key] ];
}
This array is as same as form array that you created with [+] button in HTML

Value disappear after dropdown selected

I've searched around to find the answer of my problem but I didn't find any.
I have a table contain 2 columns: kode_barang (Item ID) and nama_barang (Item Name). Kode_barang is a dropdown option which it's data populated dynamically from another table. Each time user select an option, the name of the item will appear automatically.
Here is my code:
<td>
<select name='kode_barang' type = "text" id='kode_barang1' onchange="changeValue(this.value)">
<option>Choose</option>
<?php
$sql="SELECT * FROM input_data_barang ";
$result=mysql_query($sql);
$met = "var kode_barang = new Array();\n";
while ($row = mysql_fetch_array($result)) {
$id=$row["kode_barang"];
echo "<OPTION VALUE=$id>$id</option>";
$met .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
?>
</select>
</td>
<td><input type="text" name='nama_barang' id="nama_barang1"/readonly>
<script type="text/javascript">
<?php echo $met; ?>
function changeValue(id){
document.getElementById('kode_barang1').value = kode_barang[id].name;
document.getElementById('nama_barang1').value = kode_barang[id].desc;
};
</script>
</td>
Dropdown option and Item ID appear perfectly. The problem is, when I select an Item ID, the name of the ID (nama_barang) appear automatically, but then the Item ID disappear. The dropdown become blank. I need the Item ID persist after option selected so the ID can be saved to the database.
Anybody please help me.
The issue that I can see is that you are assigning kode_barang1 the name stored. kode_barang1 is the name of a SELECT object which uses numbers for the ID so when you assign it, it goes to NULL because a name doesn't exist in the <OPTION>.
Create a new input variable called kode_barang2 and change
document.getElementById('kode_barang1').value = kode_barang[id].name;
to
document.getElementById('kode_barang2').value = kode_barang[id].name;
And you will see that would work.

Disable the dropdown value which already exist in database

Can anyone guide me to get a solution. For example , there is a dropdown down in the form contains some animals name. If the user select the one animal from that, it saved in dropdown. Again in selection process, that saved data want to become disabled. The other options only able to select. This is the solution i want.
You can achieve this with a helper method for your view, or you could set instance variables in your controller but here is some pseudo code to get you going.
def disabled_animals
Animal.where(already_selected: true).pluck(:name)
end
def selectable_animals
Animal.all.pluck(:name) - disabled_animals
end
the idea is to get 2 arrays, one without the disabled animals and one with the disabled animals and pass those to your select helper method, then you could do something like this in your view.:
select("post", "animal", selectable_animals, {disabled: disabled_animals})
Which would produce this:
<select name="post[animal]" id="post_animal">
<option value=""></option>
<option value="joke">joke</option>
<option value="poem">poem</option>
<option disabled="disabled" value="zebra">zebra</option>
</select>
Reference: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
Highlevel idea:
Get selected value from UI and pass it to mysql query to exclude it
Code:
Get value from dropdown through jQuery:
var selectedAnimal = $('.animals').find('#animal option:selected').text().trim();
Please change according to your UI
Pass selected animal in query to exclude it
$sql = "SELECT DISTINCT `animal` FROM " . $animalTable . " where animal <> '<selectedAnimal>';
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
if ( $num_rows > 0 ) {
for ($row_no=1; $row_no <= $num_rows; $row_no++) {
$row = mysqli_fetch_array($result);
$dropdown.= "<option value='" .$row['animal']. "'>" .$row['animal']. "</option>";
}
}
echo "<select class='dropdownselect' id='animal'> " .$dropdown. "</select>";
Please change according to your query and language used

Display DB value for selected name and insert that name to another table

I have a drop down that display categories from database and it's display selected category price in textfield.
when select web development it's price(12) display in textfield
this is code for that
<select name="category" class="form-control" id="category">
<?php
$query= "SELECT * FROM category" ;
$result= mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row['cost_for_cat'].'">'.$row['cat_name'].'</option>';
}
?>
</select>
<input name="cat_cost" id="cat_cost" type="text" value="<?php echo ('cost_for_cat'); ?>" onClick="checkprice()" class="form-control" placeholder="£" width="30" required/>
<script>
var select = document.getElementById('category');
var input = document.getElementById('cat_cost');
select.onchange = function(){
input.value = select.value;
}
</script>
also i want to insert category name (Web Development) in another table when button click.but both values(cost_for_cat,cat_name) should come from "option value".like this
echo '<option value="'.$row['cost_for_cat'].'">'.$row['cat_name'].'</option>';
and
echo '<option value="'.$row['cat_name'].'">'.$row['cat_name'].'</option>';
is there any solution?please help.
With the first problem, displaying the cost category when a category is selected, you have to use the "onchange" of you select element and retrieve the corresponding cost then put it on your textfield.
For the second thing, the category value as you said is already there and will be sent when the form submitted, for the text you can include a hidden input, get the text of the selected category and set it there.
The code you will need:
var categoryDropDownList = document.getElementById("category");
var selectedValue = categoryDropDownList.value;
var selectedText = categoryDropDownList.options[categoryDropDownList.selectedIndex].text;

Update text input on select option change (where both are initially populated from a database)

A dropdown select box is populated from a database and the selected option is matched against a variable $comp_cntry currently on the page:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
Then later on a telephone prefix (dialling code) box is populated from the same database, matching the dialling code to the country:
<?php
// Get Dialling Codes
$telephone_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country = $tq['country_name'];
// Show Prefix
if ($country == $comp_cntry) {
$prefix = $tq['dialling_code'];
}
}
?>
<input type="text" name="telephone_prefix" value="+<?=$prefix?>" readonly>
How, using JavaScript, can I get the telephone prefix to automatically change on page when a new option is chosen from the country dropdown? I have no real knowledge of JavaScript at all, unfortunately, but assume I would need to somehow convert my PHP associated array in to JSON so that I can use it?
I know I haven't provided any JavaScript code to show that I've made a start on this part of the problem, but if someone could point me in the right direction that would be swell.
Disclaimer: please ignore my terrible use of the mysql_ extension
I would add a data attribute (here it might be called data-prefix) to the element, like
<option value='country' data-prefix='+44'/>
and get this when the onChange event is fired for the select. In jQuery you could do something like
$('[name="country"]').change(function(){
$('[name="telephone_prefix"]').val($(this).find(':selected').data('prefix'));
});
which would update the value accordingly.
I would say the best way of doing this would be joining the two PHP codes like this:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $cq['dialling_code'];
// Select Current Country
echo "<option data-prefix='{$prefix}' value='{$country}' ";
if($country == $comp_cntry) echo "selected";
echo ">{$country}</option>";
}
?>
</select>
<input type="text" name="telephone_prefix" value="" readonly>
And this would return a list of the countries in a dropdown each with a data-prefix attribute of the appropriate prefix that they have.
We would then need to trigger jQuery on change and update the value, and this would look something like:
$("select[name=country]").on('change', function() {
var prefix = $("option:selected", this).attr('data-prefix');
$("input[name=telephone_prefix]").attr('value', prefix);
})
And this would have the following effect: http://jsfiddle.net/Tm75y/1/
I hope that's what you need.
Simply pass the prefix as an attribute of the select options:
<select id="country-select" name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $tq['dialling_code'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" prefix="<?=$prefix?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
<input id="prefix-input" type="text" name="telephone_prefix" value="" readonly>
JAVASCRIPT
Then add a change handler to your select to get the prefix attribute of the selected option and set the text input:
$(function(){
$("#country-select").change(function(){
var prefix = $(this).find("option:selected").attr("prefix");
$("#prefix-input").val(prefix);
});
});
My suggestion would be to saving a javascript object which maps countries to phone codes, so when your country select has a change, you can trigger a change to the telephone prefix via javascript.
So let's assume you have a map (associative array) in javascript that is something like this:
$country_to_phone_prefix_map = array(
'country name A' => 'phone prefix A',
'country name B' => 'phone prefix B',
...
);
This could be built in your query while loop:
$country_to_phone_prefix_map = array();
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country_to_phone_prefix_map[$tq['country_name']] = $tq['dialing_code'];
}
Then when rendering the page, inject this map into javascript
<script type="text/javascript">
var countryToPhonePrefixMap = <?php echo json_encode($country_to_phone_prefix_map); ?>;
</script>
Now, you build a change event listener on the country dropdown to change the value:
$('select[name="country"]').change(function() {
// get phone prefix from map
var selectedCountry = $(this).val();
var phonePrefix = countryToPhonePrefixMap[selectedCountry];
// change value of telephone prefix input
$('input[name="telephone_prefix"]').val(phonePrefix);
}

Categories