Ben Jarrett Ben Jarrett - 2 years ago 61
Javascript Question

Mapping multiple <select> to <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

I disagree with this approach. What you should do is actually tack these names onto the HTML element, rather than an array. What would happen if a name changes, etc? Easier to keep names and IDs, etc in HTML rather than JS - for readability and to reduce errors

You can assign the "ID" to the data-name attribute (or whatever you want really).


<div id="someID">
    <select data-name="division">
           <option value="something">Text1</option>
    <input data-name="division" value="" />

Now you use the on event - and the purpose of doing this is to assign only ONE event to the ID, and tell it to "watch" the selects for the changed event.

$('#someID').on('change','select', function() {
     var $this = $(this),
         name = $'name'),
         $input = $('#someID').find('input[data-name="' + name + '"]"');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download