-1

I would like to find a solution in jQuery that helps me find the selected option of a specific select name and have it transfered to a hidden text field.

My current select box and hidden field are as follow:

    <select name="pa_weight">
        <option value="">No default Weight…</option>
        <option value="50g">50g</option>
        <option value="100g">100g</option>
        <option value="150g">150g</option>
    </select>   


    <input type="text" class="hiddenField" id="hiddenField" />

Some expert help would be greatly appreciated, thank you

David
  • 43
  • 8
  • 2
    Possible duplicate of [jQuery Get Selected Option From Dropdown](https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – Luca Kiebel Sep 19 '18 at 11:34

3 Answers3

1

You can set value in the hidden field that shown below:

Index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.3.1.js"
            integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
            crossorigin="anonymous"></script>
    <script>
        $(document).on('change', 'select[name="pa_weight"]', function (e) {
            $('#hiddenField').val($(this).val());
        });
    </script>
</head>

<body>
    <select name="pa_weight">
        <option value="">No default Weight…</option>
        <option value="50g">50g</option>
        <option value="100g">100g</option>
        <option value="150g">150g</option>
    </select>
    <input type="hidden"
           class="hiddenField"
           id="hiddenField" />

</body>

</html>
baj9032
  • 2,414
  • 3
  • 22
  • 40
1

You can define a function that you call onchange on your <select> that fetches the value of the selected option and puts it into the hidden input field.

Example:

<script>
function transferValue() {
    var value = $('select[name="pa_weight"] option:selected').val();

    $('#hiddenField').val(value);
}
</script>

And your HTML:

<select name="pa_weight" onchange="transferValue();">
    <option value="">No default Weight…</option>
    <option value="50g">50g</option>
    <option value="100g">100g</option>
    <option value="150g">150g</option>
</select>   


<input type="text" class="hiddenField" id="hiddenField" />
Martin
  • 2,326
  • 1
  • 12
  • 22
0

Just place the select's .val() into the hidden field's val:

$("#hiddenField").val($('select').val());
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51