Ben Jarrett Ben Jarrett - 2 years ago 63
Javascript Question

Mapping multiple <select> to hidden <input>

It really seems like there should be a better way to do this without pasting scripts to my page, but I'm not very good with js and I could really use some pointing in the right direction. The 'working' code is below.

var select;
var i;
select = ['division', 'account_exec', 'badge_printing', 'attendance_tracking', 'lead_retrieval','access_control', 'general_session', 'breakout_rooms', 'exhibit_floor'];
for (i = 0; i < select.length; ++i) {
$( "<script>$(function(){$('select[name=" + select[i] + "]').change(function(){var selected=$(this).val();$('input[name=input_" + select[i] + "]').val(selected);});});<\/script>" ).appendTo("body");

Answer Source

Your code should look something like this...


    var select = [

    for (var i = 0; i < select.length; ++i) {

        $('select[name="' + select[i] + '"]').on('change', function(){

            $('input[name="input_' + select[i] + '"]').val($(this).val());



  • You should declare variables as you're assigning them.
  • I'm not sure why the ready function was inside the loop, but this normally contains all of the code.
  • I'm not sure what you're appending to the body, so I left that out.
  • I don't know if $(this).val() has the value you're expecting, but you can test it.
  • You didn't have the right quotes, so your variables were part of the string.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download