s.khan
s.khan

Reputation: 395

Getting the value of a select element which is hidden in a multiple select element form

I am working on a form which have multiple select fields with multiple options. But only one select field is displayed while the other is hidden with display: none.

The issue right now is, I am getting the value for both the fields even though one is hidden.

Here's my two select input fields where only one is visible according to the user's choice.

<select id="entry" name="entry">
        <option value="slide-in-center" >Center</option>
        <option value="slide-in-right">Right</option>
</select>

<select id="exit" name="exit" style="display: none;" >
        <option value="slide-out-center" >Center</option>
        <option value="slide-out-right">Right</option>
</select>

After the form is submitted I get output from both the fields. Like:

{
    entry: 'slide-in-center',
    exit: 'slide-out-center'
}

Why am I getting this? I had selected attribute in the first option for both. And I thought it is because of this so I removed this but it is giving out the same output. What am I doing wrong here?

Upvotes: 0

Views: 137

Answers (2)

Andrew L
Andrew L

Reputation: 5486

The select, even with display set to none will still be submitted as part of the form. I believe it used to be enough to prevent it from being submitted, but it changed.

Adding the disabled attribute to your select will prevent it from being submitted with the form.

Upvotes: 1

DCR
DCR

Reputation: 15665

the default value is the first option. add a blank option

var entry = document.getElementById('entry').value
console.log(entry)

var exit = document.getElementById('exit').value
console.log(exit)


var entry2 = document.getElementById('entry2').value
console.log(entry2)

var exit2 = document.getElementById('exit2').value
console.log(exit2)
<select id="entry" name="entry">
        <option value="slide-in-center" >Center</option>
        <option value="slide-in-right">Right</option>
</select>

<select id="exit" name="exit" style="display: none;" >
        <option value="slide-out-center" >Center</option>
        <option value="slide-out-right">Right</option>
</select>


<select id="entry2" name="entry">
        <option value=''></option>
        <option value="slide-in-center" >Center</option>
        <option value="slide-in-right">Right</option>
</select>

<select id="exit2" name="exit" style="display: none;" >
        <option value=''></option>
        <option value="slide-out-center" >Center</option>
        <option value="slide-out-right">Right</option>
</select>

Upvotes: 1

Related Questions