Reputation: 47
I've got a form with a select box like this:
<select name="damage">
<option value="100 Euro">Exhaust</option>
<option value="200 Euro">Brakes</option>
</select>
After submit, I want to display both 'name' and 'value' via echo like this:
"You selected Exhaust, this will cost you approximately 100 Euro."
So, how can I echo the 'name' and 'value' of a select?
Thank you.
Upvotes: 0
Views: 273
Reputation: 71384
Unfortunately your POST can only post the value of the input. The way this case is typically address however, is by defining these value-display text relationships in code.
So you may have an array defined in PHP like this:
$damage_options = array(
'100 Euro' => 'Exhaust',
'200 Euro' => 'Brakes'
);
You could use this array both for generating the select input dynamically and for matching up key-values on the resulting POST.
I would perhaps say however that your values don't make much sense in this case. What if you had two types of damage that have the same cost value? Perhaps it makes more sense to simply use the same string for both value and display in the option (i.e. 'Exhaust', 'Brakes'), etc.) and put the cost value in an array like this:
$damage_options = array(
'Exhaust' => '100 Euro',
'Brakes' => '200 Euro'
);
This way you could look up the cost based on the selected damage, not the other way around.
Using this second array type, When the form is posted echoing value would look like this.
if (!empty($_POST['damage'])) {
$damage_type = $_POST['damage'];
if(array_key_exists($damage_type, $damage_options)) {
echo 'You selected ' . $damage_type . ', this will cost you approximately ' . $damage_options[$damage_type];
} else {
// damage type doesn't match any key in array
//perhaps give error message
}
} else {
// no damage value was posted
// perhaps give error message or do something else
}
Upvotes: 1
Reputation: 5361
Ideally it should be:
<select name="damage">
<option value="100">Exhaust</option>
<option value="200">Brakes</option>
</select>
And I assume you want to display that message somewhere on the browser when selection changes. You won't need PHP for that. You can do that using jQuery.
$('select[name="damage"]').on('change', function(){
var result = "You selected" + $(this).find('option:selected').text() +", this will cost you approximately " + $(this).val() + " Euro."
});
Upvotes: 0