user2210516
user2210516

Reputation: 683

Select value to Hidden input

I know there's already lots of topics about this and i think i read them all but i still can't get it to work.

I need to update the choosen value from my select to a hidden input field.

When i try this code for example it doesn't work. When i check the source code the value is still empty..

What am i doing wrong?

 <form>
    <select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
        <option value="j.hotmail.com">Jens</option>
        <option value="a.hotmail.com">Adam</option>
        <option value="d.homtail.com">Dan</option>
    </select>
    <input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
 </form>

    function changeHiddenInput (objDropDown)
    {
        var objHidden = document.getElementById("hiddenInput");
        objHidden.value = objDropDown.value; 
    }   

Upvotes: 1

Views: 18472

Answers (3)

KalenGi
KalenGi

Reputation: 2077

I've found that at times you need to use the parent form in order to access child inputs. No idea why. In this case, give the form an id:

<form id="hotmail"> 
    <!-- Form stuff -->
</form>

Since you have only one hidden input, you could use jQuery to access it like so:

var selectedValue = $("#dropdown option:selected").val();
$("#hotmail input[type=hidden]").val(selectedValue);

Upvotes: 0

ssilas777
ssilas777

Reputation: 9764

I think you need this:-

function changeHiddenInput (objDropDown)
{
   document.getElementById("hiddenInput").value = objDropDown.value; 
}

Check demo

Upvotes: 1

Niventh
Niventh

Reputation: 995

use jQuery its much easier:

var objHidden = $('#hiddenInput').val(objDropDown);

Upvotes: 0

Related Questions