So i have a dropdown list that is filled with data that is pulled from my database. Im stuck with populating the textbox based on the value thats selected from the dropdown box.
My model currently looks like this:
<?php
require_once('../Config/config.php');
class AppCalc
{
public $dbconn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->dbconn = $db;
}
public function fillDropdown () {
$stmt = $this->dbconn->prepare("SELECT AppID, Appliance, PowerConsumption FROM appliances ORDER BY Appliance");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
My Controller:
<?php
require_once('../Model/applianceModel.php');
require_once('../Tool/DrawTool.php');
$newCalc = new AppCalc();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/applianceCalculator.php', array(
'appliances' => $newCalc->fillDropdown()
));
echo $renderedView;
?>
and my View:
$(document).ready(function() {
$('#appliance').on('change', function () {
$('#powerCon').val($(this[this.selectedIndex]).attr('data-powerConsumption'));
});
})
</script>
<div id="mainBody">
<h2 >Energy Consumption and Cost of household appliances</h2>
<div id="appForm">
<form id="applianceCalc">
Typical Appliance:
<select id="appliance" name="appliance">
<option value="" disabled selected>Select your option</option>
<?php
foreach ($appliances as $appliance):
?>
<option value="<?php echo $appliance['AppID']; ?>" data-powerConsumption="<?php echo $appliance['PowerConsumption']; ?>">
<?php echo $appliance['Appliance']; ?>
</option>
<?php
endforeach;
?>
</select>
<br/>
Power Consumption:
<input type="text" id="powerCon" required/>
<br/>
Hours of use per day:
<input type="text" name="hoursPerDay" required/>
<br/>
</form>
And here is the table im working with:
CREATE TABLE IF NOT EXISTS `appliances` (
`AppId` int(11) NOT NULL AUTO_INCREMENT,
`Appliance` varchar(50) NOT NULL,
`PowerConsumption` int(8) NOT NULL,
PRIMARY KEY (`AppId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `appliances` (`AppId`, `Appliance`, `PowerConsumption`) VALUES
(1, 'Hairdryer', 1251),
(2, 'Microwave', 6241);
So the code works fine in terms of populating the dropdown with the values from the database. However im stuck on changing the value for the textbox. For example if i was to select "Hairdryer" from the dropdown then the number "1251" should appear in the powerConsumption textbox however for some reason the textbox value isnt changing. It remains blank.
<option value="foo">bar</option>do you need to copy, and to what element does it need to go?