Luca Reghellin
Luca Reghellin

Reputation: 8103

Is there a way to get SELECT value in $_POST only if really selected?

I've got a maybe unusual problem. I've got some 'screw shapes', and for each shape, some 'screw type'.

So, I've got several form SELECTS, related to 'screw type'. They are all hidden. They appear upon user selection on a 'screw shape' select. In other words, after the user selects a screw shape, then the related screw type select menu will appear. Thus only 1 type select will be visible at a time.

SELECT[shape]
   shape-1
   shape-2
   etc

SELECT[types for shape 1] // visible only if shape-1 is selected
   type-1
   type-2
   etc

SELECT[types for shape 2] // visible only if shape-2 is selected
   type-1
   type-2
   etc

...and so on...

The data I need to retrieve is just the shape and the related type of the screw.

Issue: $_POST will contain all the types of all shapes: not good. Otherwise, I could name each type select as an array (screw[type]) and I'll end up with just one value, but that value will always be the selected (or default) option of the last type select: even worse.

What I want to get is just $_POST['screw-shape'] and $_POST['screw-type'], each with the value that user really selected.

Is there a way?

Upvotes: 0

Views: 168

Answers (2)

geco17
geco17

Reputation: 5294

You can have multiple form elements with the same name; it's still valid HTML. Since one select will always be hidden out of the two selects for screw_type, your post variable will only have one entry for screw type. Consider

<form action="...">
    <select name="screw_shape">
        ...
    </select>
    <select name="screw_type" class="hidden shape1">
        ...
     </select>
     <select name="screw_type" class="hidden shape2">
        ...
     </select>
</form>

Toggling hidden classes as appropriate with JavaScript will take care of the form submit with the request params as you need them.

Upvotes: 0

eduCan
eduCan

Reputation: 180

Try not only hide the inputs, disabled it as well, disabled inputs should not travel in requests

Upvotes: 2

Related Questions