John Davidson

php - Populate dropdown based on checkbox

0 comments
Message:


I have a form that contains a checkbox and a dropdown list. I use PHP to populate the dropdown list from two MySQL tables. Which table I use depends on whether the checkbox was checked or not. But, as you can see from my code sample, I can only populate that dropdown list after I submit the form. I want to be able to keep clicking on the checkbox and keep re-populating the dropdown list without having to submit the form. I am still new to this, so, please, give me as simple a solution as possible.


PS. I have a small bug in the code that doesn't keep the checkbox checked/unchecked after I submit the form. Working on fixing it.


Thank you




<?php
$Prc_Earn = 'Prc';
if (isset($_POST['submitBtn']))
{
if (isset($_POST['chkbox']))
{
$sql = 'select distinct Symbol from price_history.quarterly_earnings_history';
$Prc_Earn = 'Earn';
}
else
{
$sql = 'select distinct Symbol from price_history.stock_symbol_list';
$Prc_Earn = 'Prc';
}
}
// Connect to the database
include ('../Connections/mysql_connect.php');
if ($dbcon)
{
?>
<form method='post'>
<label for=''>Earnings / Prices</label>
<input type='checkbox' name='chkbox' id='chkbox' <?php if ($Prc_Earn == 'Prc') { echo "checked"; };?>><br><br>

<label for='symbol'>Stock Symbol:</label>
<select name = 'symbol' id='symbol'>
<?php
$result = mysqli_query($dbcon, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{ echo '<option value="' . $row['Symbol'] . '">' . $row['Symbol'] . '</option>'; }
}
?>
</select><br><br>
<button class='button' type='submit' name='submitBtn' id='submitBtn'>View Data</button><br><br>
</form>
<?php
}
?>


My Answer:
You can achieve this using JavaScript to dynamically populate the dropdown list based on the checkbox state without having to submit the form. Here's a simple example to get you started:

html



Populate Dropdown Based on Checkbox












In this example, the `populateDropdown` function is called whenever the checkbox state changes. It clears the existing options in the dropdown and populates it with options based on the checkbox state. You can modify the options array to fetch data from your MySQL tables using AJAX if needed.

As for the bug that doesn't keep the checkbox checked/unchecked after form submission, you can set the `checked` attribute of the checkbox based on the form data submitted. You can do this by checking the form data in PHP and adding the `checked` attribute to the checkbox element if needed.

Rate this post

4 of 5 based on 5315 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us