Victornez Victornez - 3 months ago 7
HTML Question

How to bind the value of select to an input when it's dinamically created

I have a problem with a Js/Rails code. I have a form that is created dynamically when I click a button(It can create multiple of this forms in the same page), it contains a select that have an ID that is never the same. I need to put some value into an input according to the select value. In the first form It works perfectly but later in the other forms it doesn't work. Like I said, I don't have access to the ID's because those are created in rails.

HTML

<div class="test">
<div>
<div class="divSelect">
<select id="1470190840697_ad_type">
<option>Element1</option>
<option>Element2</option>
<option>Element3</option>
<option>Element4</option>
<option>Element5</option>
<option>Element6</option>
</select>
</div>
<div class="divInput">
<input type="text">
</div>
</div>
<div>

//This is dynamically created
<div class="divSelect">
<select id="1470190846932_ad_type">
<option>Element1</option>
<option>Element2</option>
<option>Element3</option>
<option>Element4</option>
<option>Element5</option>
<option>Element6</option>
</select>
</div>
<div>
<input type="text">
</div>
</div>






Javascript - jQuery

$('.test').on('change',$('.divSelect').children('select'),function(){
updateTime();
});

function updateTime() {
var tipoPauta = { 'Element1':1,
'Element2':2,
'Element3':3,
'Element4':4,
'Element5':5,
'Element6':6
}

var select = $('.divSelect').children('select');
$('.divInput').children('input').val(tipoPauta[select.val()]);
};


JSBIN CODE

Thanks a lot! I'm crazy with this problem.

Answer

As @adeneo mentioned, you need to specify a string as a selector as the second argument. Also to update the correct input element, your code should be something like

$('.test').on('change',  '.divSelect' ,function(){
  var $select = $(this).find('select');
  updateTime($(this), $select);
});



function updateTime($divelement, $selectelement) {
  var tipoPauta = { 'Element1':1,
                    'Element2':2,
                'Element3':3,
                'Element4':4,
                'Element5':5,
                'Element6':6
               }

  var $input = $divelement.next().children('input');

  $input.val(tipoPauta[$selectelement.val()]);
};
Comments