Home > OS >  Get a ID Value from Select DropDown and Add in an Input Field
Get a ID Value from Select DropDown and Add in an Input Field

Time:11-16

I want to get an ID value from select dropdown and insert it into an input field.

That is the select option html;

<select name="student_class" class="input_box" onchange="myFunction(this.value);">
                <option value="Play Group" id="1400">Play Group</option>
                <option value="Nursery" id="1400">Nursery</option>
                <option value="Prep" id="1400">Prep</option>
                <option value="1" id="1600">1</option>
                <option value="2" id="1600">2</option>
                <option value="3" id="1600">3</option>
                <option value="4" id="1600">4</option>
                <option value="5" id="1600">5</option>
                <option value="6" id="1800">6</option>
                <option value="7" id="1800">7</option>
                <option value="8" id="1800">8</option>
                <option value="9" id="2500">9</option>
                <option value="10" id="2500">10</option>
            </select>

This is the input field html;

<input type="text" class="input_box" id="actual_fee" style="background: #EFEFEF; border: 1px solid #000; color: #000;" name="actual_fee" size="5" value="" readonly="readonly">

And this is the javascript I am using;

<script type="text/javascript">
function myFunction(element)
{
    document.getElementById("actual_fee").value = element;
}
</script>

But the problem is this code only shows the option's "value" and not its "ID" value.

Please help.

CodePudding user response:

Use selsectedIndex Property of your element:

function myFunction(element)
{
    document.getElementById("actual_fee").value = element.options[element.selectedIndex].id;
}
<select name="student_class" class="input_box" onchange="myFunction(this);">
                <option value="Play Group" id="1400">Play Group</option>
                <option value="Nursery" id="1400">Nursery</option>
                <option value="Prep" id="1400">Prep</option>
                <option value="1" id="1600">1</option>
                <option value="2" id="1600">2</option>
                <option value="3" id="1600">3</option>
                <option value="4" id="1600">4</option>
                <option value="5" id="1600">5</option>
                <option value="6" id="1800">6</option>
                <option value="7" id="1800">7</option>
                <option value="8" id="1800">8</option>
                <option value="9" id="2500">9</option>
                <option value="10" id="2500">10</option>
            </select>

<input type="text" class="input_box" id="actual_fee" style="background: #EFEFEF; border: 1px solid #000; color: #000;" name="actual_fee" size="5" value="" readonly="readonly">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related