JoC
JoC

Reputation: 1

PHP form handling - how to reference the value or id attribute when the name is the same: in input type = radio

Can anyone help me with getting PHP to reference the value or id attribute in form handling. I can only see how to reference the name using $_POST, how can this work with radio input type when the name is not unique? Thanks in advance for any advice.

input type="radio" name="fuel" value="Unleaded" id="fuel_0" 
/>Unleaded</label><br />
    <label>
    <input type="radio" name="fuel" value="Diesl" id="fuel_1" 
/>Diesel</label><br />
  <label>
    <input type="radio" name="fuel" value="Super Unleaded" id="fuel_2" 
/>Super Unleaded</label><br />
  <label>
    <input type="radio" name="fuel" value="Premium Diesel" id="fuel_3" 
/>Premium Diesel</label></p>
<p>
  <input type="submit" name="Submit" id="Submit" value="Calculate" /><br />

Upvotes: 0

Views: 1048

Answers (3)

JoC
JoC

Reputation: 1

I guess I should have rephrased the question to ask how to choose a different function depending on which option was chosen as you can't differentiate by using the name if they are all the same. I've got this working using the below code. I didn't realise before today that you could just refer to the value. Thanks to those of you who answered my earlier question.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{if(isset($_REQUEST['amount'])&&is_numeric($_REQUEST['amount'])){    
$litres=$_REQUEST['amount'];}
else {echo "please enter a valid amount";$litres=0;}
$choice = $_POST ['fuel'];
if ($choice == "Unleaded"){echo "litres=amount= " . $litres  . " final cost 
is " .     unleaded($litres)         ;}
if ($choice == "Diesl"){echo "litres=amount= " . $litres  . " final cost is 
" .          diesel($litres)         ;}
if ($choice == "Super Unleaded"){echo "litres=amount= " . $litres  . " final 
cost is " . Superunleaded($litres)         ;}
if ($choice == "Premium Diesel"){echo "litres=amount= " . $litres  . " final 
cost is " . premiemdiesel ($litres)        ;}
}

Upvotes: 0

Marc Schroth
Marc Schroth

Reputation: 57

Radio buttons work by giving all of inputs in a particular group the same name. However, when the form is submitted, only the value from the selected radio button is sent to the server. PHP will only end up seeing the one value.

Upvotes: 0

Rvdrichard
Rvdrichard

Reputation: 335

You do reference the name using $_POST. The name is still unique even if the radio button name fuel shows 4 times. It is unique for the whole group and only one will be selected so you only have one value.

$radioValue = $_POST["fuel"];

Upvotes: 2

Related Questions