James James - 7 months ago 11
Javascript Question

Select option does not get the value

I have a dropdown list of, for instance occupations, and when the user clicks the option "Other" , a textbox will show up and the user will have to specify his occupation. The part where the user chooses "Other" and input his occupation works, it saves what he input, but when the user is going to just choose or select from the dropdown list, the value is not being recorded when I submit the form.

How will get the value from the select option? Because I only get the value when the user select "Other" and input his occupation. Here's my code.



function CheckOccupation(val){
var element=document.getElementById('occupation');
if(val=='Other')
element.style.display='block';
else
element.style.display='none';
}

<select class="form-control" name="occupation" onchange='CheckOccupation(this.value);'>
<option> Select Occupation</option>
<option> Lawyer </option>
<option> Nurse </option>
<option> Lawyer </option>
<option> Teacher </option>
<option> Programmer </option>
<option> Accountant </option>
<option> Other </option>
</select>

<input type="text" name="occupation" id="occupation" class="form-control" placeholder="please specify your occupation..." style='display:none;'/>




Answer

Set a value attribute for your option fields and also provide different name for both the fields

JS

function CheckOccupation(val){
 var element=document.getElementById('occupation');
 if(val==='Other')
   element.style.display='block';
 else  
   element.style.display='none';
}

HTML

<select class="form-control" name="occupation1" onchange='CheckOccupation(this.value);'>
    <option> Select Occupation</option>
    <option value="Lawyer"> Lawyer </option>
    <option value="Nurse"> Nurse </option>
    <option value="Lawyer"> Lawyer </option>
    <option value="Teacher"> Teacher </option>
    <option value="Programmer"> Programmer </option>
    <option value="Accountant"> Accountant </option>
    <option value="Other"> Other </option>
</select>

<input type="text" name="occupation2" id="occupation" class="form-control" placeholder="please specify your occupation..." style='display:none;'/>