Search code examples
phpforms

How to retrieve input label corresponding to a number input type from an HTML form using php?


I have a form in which there are inputs of type number, each with a corresponding label. I would like to add a "review page" after you submit the form in which you can see what number you answered to each input (though you don't need to fill them all out), as if you were ranking the labels. For example, if I wrote 4 in the input labeled "Mark Twain", I would like to show "Choice 4: Mark Twain". I cannot change the format to be a <select> instead, and in the form, each input box has a unique label.

I made each input like this in HTML:

<label><input type="number" name="num_a"  min="1" max="14" autocomplete="off" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this. Value = this.value.replace(/(\..*)\./g, '$1'); this.setCustomValidity('')" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" class="unique">  <span>Mark Twain</span></label>

I tried the following in the PHP:

if (isset($_POST["num_a"]))
 {$a= "Mark Twain";
echo "Choice ", $_POST["num_a"], ":", $a, "<br>";}

This works well if num_a is actually inputted. However, it always shows up in the review page, even if num_a was NOT filled out, so it looks like this

"Choice : Mark Twain"

How can I make it so that this only shows up if the input was given? That way only inputs that got a number show up?


Solution

  • Don't print the input if it's empty.

    if (isset($_POST['num_a']) && $_POST['num_a'] != '') {
        $a= "Mark Twain";
        echo "Choice ", $_POST["num_a"], ":", $a, "<br>";
    }
    

    Since 0 isn't a valid value for the input, you could simplify it to:

    if (!empty($_POST['num_a'])) {
        $a= "Mark Twain";
        echo "Choice ", $_POST["num_a"], ":", $a, "<br>";
    }