Drop-down menu based on the selection of radio button - php

I have four radio buttons and I would like to get the drop-down menu based on the selected radio button. Is it best if I just write all those drop-downs ready and display them based on the selection or is there a way to do it with ajax (because the drop-down values are coming from database) ?
Here are the radio buttons:
<input type="radio" name="some" value="someValue1">
<input type="radio" name="some" value="someValue2">
<input type="radio" name="some" value="someValue3">
<input type="radio" name="some" value="someValue4">
Here is the drop-down:
<select name="reason">
<?php
$data = WorkReason::all();
foreach ($data as $d) {
?>
<option value="<?php echo $d->code; ?>"><?php echo $d->reason; ?></option>
<?php
}
?>
</select>
I am using php ActiveRecords to get the values from database.
So if anybody knows a good way of doing this I would appreciate some help.

Make the different drop down lists and add a php condition to check which radio button was clicked and display that list.
You can use an array to select the correct code for you.
$radio2select = array ("someValue1" => "<select>..." , "someValue2" => "...", "someValue3" => "..."); // you get the idea
echo $radio2select($_REQUEST['radio']) ;
The use of an array is a trick to avoid using a switch statement, and it works well when your drop down boxes have been precomputed.
Otherwise, make a function which build the drop down box:
function select_reasons($which){
<select name="reason">
<?php
$data = WorkReason::all(array('conditions' => array ( 'reason = ?' => $which)));
foreach ($data as $d) {
?>
<option value="<?php echo $d->code; ?>"><?php echo $d->reason; ?></option>
<?php
}
?>
</select>
}
then just pass the $_REQUEST[‘radio'] to generate the corresponding dropdown list.
Note that I don't know your database schema, but I think that it should get you started.
Also, this code will work either on a regular Get or Post, or could be embedded within an ajax roundtrip (this depends on the framework you are using).
Another advantage is that only the necessary html code get included in the page, compared to a CSS based solution.

Make the different drop down lists and add a php condition to check which radio button was clicked and display that list.
if (isset($_POST['checkbox1']) {
echo '<select>...'
} else if (isset($_POST['checkbox2']) {
echo '<select>...'
}

Just load all Dropdown menues and display the one the user chose earlier with CSS:
display:block
display:none

Related

PHP variable in header function in one drop list with two values [duplicate]

I'd like to post two values in one drop down option and I'm not sure about the best way to approach it.
The drop down list pulls data in from an external service. This data is 'id' and 'name'.
When I select an option in the drop down and then press submit I want the 'id' and the 'name' to be posted.
My code looks like this:
<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
<option value="<?php echo $name['id']);?>">
<?php echo $name['name']);?>
</option>
<?php endforeach; ?>
</select>
I've tried putting in a hidden input field, but that then doesn't render out the drop down (instead it just creates a list).
I am using both the id and name elsewhere, so I don't want to have to post just the id and then have to get the name again, hence I want to post both of them at the same time.
Any recommendations?
You cannot post two values unless both of them appear in the value attribute. You can place both in, separated by a comma or hyphen and explode() them apart in PHP:
// Place both values into the value attribute, separated by "-"
<option value="<?php echo $name['id'] . "-" . $name['name']);?>">
<?php echo $name['name']);?>
</option>
Receiving them in PHP
// split the contents of $_POST['data'] on a hyphen, returning at most two items
list($data_id, $data_name) = explode("-", $_POST['data'], 2);
echo "id: $data_id, name: $data_name";
You may add a hidden field with the name "id" and then bind an onchange event listener to the <select>. inside the onchange function, get the value of the <select> and assign it to the "id" field.
<form>
<select name="name" onchange="document.getElementById('id').value=this.value">
<!--
...
options
...
-->
</select>
<input type="hidden" name="id" id="id" />
<input type="submit" />
</form>
You could output something like:
<option value="<?php echo $name['id']."_".$name['name'];?>">
Then use preg_splitor explode to separate the two once the form data is processed.
The only way to do this is to include both pieces of information in the value for the single option. Just use code like the following, and then when you get the value back, split the string at the first underscore to separate out the values.
<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
<option value="<?php echo $name['id'] . "_" . $name['name']);?>">
<?php echo $name['name']);?>
</option>
<?php endforeach; ?>
</select>
Also, you could just leave the ID alone in your form, and then look up the id again when the user submits the form.
You could make as many hidden inputs as there are options, each with the name of one option value. The input's values are the contents of the options. In the second script, you can look for the dropdown value, and then take the value of the hidden input with that name.
We can pass it with data attribute, and can access in js,
<option value="<?php echo $name['id']);?>" data-name="<?php echo $name['name']);?>">One</OPTION>
var name = $(this).find(':selected').data('name');

display result based on drop down list

I would like to display the result which I have selected based on the drop down list. This is my drop down list code which is retrieved from the finish_product under bom table (calculate.php)
<tr>
Select product:
<select class="itemTypes">
<?php
while ($row1 = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row1['finish_product']; ?>">
<?php echo $row1['finish_product']; ?>
</option>
<?php } ?></select>
<br/><br/>
</tr>
For example, under the drop down list I selected 'Table', how do I display the result in doCalculate.php?
Right now I just hard code Table which is not feasible. Anyone to help me out?
There are many, many ways which you could accomplish your goal. I would suggest using a JavaSctipt "onchange" event, detect the selected option, and then update the DOM with its contents.

Best practise populate Bootstrap HTML form SELECT dropdown with values from database

UPDATE:
I have made some changes and updated the code.
It works better now and when loading the form, the value from the database is automatically shown in the form field, this is done by adding "selected" to the OPTION tag.
However, I still have a bug somewhere:
When selecting a new value it is stored correctly in the DB and displayed in the field when submitting the form, but only if I choose a value below the previous value in the drop-down. If a value above the previous value is selected, the new value is stored in DB but the old value is still displayed in the form field.
When debugging the HTML output I can see that for some reason both the old value and the new value is listed as "selected" options. I use the "if...elseif....else" Statement and believed this was correct but I do not understand why I get two options "selected" after submit. Have I understood the usage of IF statement wrong?
A part of the HTML output:
<option value="MDV">Maldives</option>
<option value="MLI" selected>Mali</option>
<option value="MLT" selected>Malta</option>
<option value="MHL">Marshall Islands</option>
ORGINAL QUESTION:
I have seen many examples of methods for populating a drop-down in an html form with the use of PHP and values from a MySQL database. I have chosen one that for me looks efficient and easy to understand.
However my problem is that the rest of my form pre-populates form fields with data from the database and I am struggling to find out how I can do the same with my SELECT tag. I would like to ask what is best practice for this task? Is my code correct from a general point of view when populating a drop-down or shall I use a third party script like "Selectize" or "bootstrap-select" to accomplish this?
Worth mentioning is that I am aiming for a solution where if the value do not already exist, the user can suggest their own value and add it to the DB. Any variant of type-ahead would also be preferred for those drop-downs containing a large number of options. But for now I have only been focused on learning the basics.
My existing code, which is working for providing the drop-down with the correct values and store the selected value in the DB. I have failed to show the chosen value after pressing submit and instead the first value in the array is shown ad default value for the drop-down.
PHP Code:
//Get countries
$sth = $db->prepare ("SELECT iso3, short_name FROM country ORDER BY short_name ASC");
$sth->execute();
$CountryList = $sth->fetchAll(PDO::FETCH_ASSOC);
HTML code:
<div class="form-group">
<label class="control-label col-sm-2" for="country">Country</label>
<div class="col-sm-10">
<select class="form-control" name="country" id="country">
<?php
foreach ($CountryList as $row) {
if ($row['iso3'] == $_POST['country']) {
echo "<option value={$row['iso3']} selected>";
} elseif ($row['iso3'] == $country) {
echo "<option value={$row['iso3']} selected>";
} else {
echo "<option value={$row['iso3']}>";
}
echo $row['short_name'];
echo '</option>';
}
?>
</select>
</div>
</div>
I think you may be ending your foreach loop too early, you also need to specify a value for your option, like so:
<div class="form-group">
<label class="control-label col-sm-2" for="country">Country</label>
<div class="col-sm-10">
<select class="form-control" name="country" id="country">
<?php foreach ($CountryList as $row): ?>
<option value="<?=$row["short_name"]?>">
<?=$row["short_name"]?>
</option>
<?php endforeach ?>
</select>
</div>
</div>
Another thing to mention is that you are missing a greater than sign on your opening div

2 drop down menus w/o submit button

I would like to know how to submit two drop down menus w/o a submit button. I want to populate the second drop down menu on selection of the first and then be able to echo out the selection of the second drop down menu. Data for the second drop down menu is obtained from a mySQL database. I am using two forms on my page, one for each drop down menu.
<form method="post" id="typeForm" name="typeForm" action="">
<select name="filterType" onchange="document.getElementById('typeForm').submit()">
<option <?php if ($_POST['filterType'] == 'none') print 'selected '; ?> value="none">Filter by...</option>
<option <?php if ($_POST['filterType'] == 'employee') print 'selected '; ?> value="employee">Employee</option>
<option <?php if ($_POST['filterType'] == 'taskName') print 'selected '; ?> value="taskName">Task</option>
</select>
<noscript><input type="submit" value="Submit"/></noscript>
</form>
<form method="post" id="categoryForm" name="typeForm" action="">
<select name="filterCategory" onchange="document.getElementById('categoryForm').submit()">
<option <?php if ($_POST['filterCategory'] == 'none') print 'selected '; ?> value="none"></option>
<?
$count2 = 0;
echo $rowsAffected2;
while ($count2<$rowsAffected2) {
echo "<option value='$filterName[$count2]'>$filterName[$count2]</option>";
$count2 = $count2 + 1;
}
?>
</select>
<noscript><input type="submit" value="Submit"/></noscript>
</form>
I can submit the first form with no problem. It retrieves values into the second drop down menu successfully.But on selecting a value from the second menu the page refreshes and I'm left with an two unselected drop down menus. I tried echoing the $_POST['filterCategory'] and didn't get a result. I tried using onchange="this.form.submit();" in both forms and I still get the same result. Is there a way to do this without using AJAX, JQuery or any complex Javascript script? I require to this completely in PHP.
I want to avoid the second refresh but still be able to gather the $_POST[''] data from the second selection.
use the same form for both selects
You have two ways of doing that.
You can either submit the form using AJAX; that will prevent the whole page from refreshing, and hence, losing the data in both select elements; that is also the coolest way to have it done.
OR
Using a single form, when both the first and second select elements are submitted, use their values to re-create the select elements.
The cleaner way to do it is still the first option; at least, that's what I'll use if I have to do it.

how do i trigger the javascript event with dropdown and change the values?

I am creating a form where the users will have to select the country from the drop down list. as soon as they selects it should activate another drop down list where it should show the states belonging to the country and hence it should process the value from country Id of element. and as soon as the user selects the states another drop down list should activate listing the cities belonging to that particular states, and hence so on to areas.
for that i have written the php and html code like this.
Select Countries : <select name="countries"><br/>
<?php
foreach($property->getAllCountries() as $countries)
{
?>
<option value="<?php echo $countries['id']; ?>"><?php echo $countries['name']; ?></option>
<? } ?>
</select><br/>
Select State : <select name="state">
<?php
foreach($property->getStatesFromCountryId($countryId) as $states)
{
?>
<option value="<?php echo $states['id']; ?>"><?php echo $states['name']; ?></option>
<? } ?>
</select>
the javascript should automatically insert $countryId from and populate the states after the user selects it.
i am noob at javascript i would appreciate if someone could guide me how to achieve this?
thank you.
sorry for bad english.
you should add onchange="showstates()" to select countries and a div to add states of country to it
function showstates()
{
var country=document.getElemtById("countries").value;
if (country=="anywhere")
{
document.getElemtById("statesofcountries").innerHTML='<div>"states list"</div>';
}
}
check this link
You can always google it up:
http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html

Categories