Alex Alex - 1 month ago 9
PHP Question

Multiple actions on a Single Change Event with JQuery/Javascript

I need to implement this js in order to fill in different fields on change event of a select field.

<select class="form-control" name='brands_list'>
<option value="0">Seleziona il produttore</option>
<?php
while ($listabrand=mysqli_fetch_array($brands)){
echo '<option value="'.$listabrand[0].','.$listabrand[1].','.$listabrand[2].'">'.$listabrand['0'].' - '.$listabrand['1'].'</option>';
}?>
</select>


This is the js to implement. I should add a second action that fill in the input field named 'brand_link' assuming the array value [2]:

<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
</script>


I made several attempts but without results such as

<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});

$('select[name="brands_list"]').change(function(){
$('input[name="brand_link"]').val($('select[name="brands_list"] option:selected').text()[2]);
});




Any help?

Answer Source

You can do it all within the one function. The reason your pastebin didn't work is because 1) you aren't operating on the .val() of the selected item (rather the element itself) and 2) you didn't split the value by comma, like you split the .text() by hyphen.

$('select[name="brands_list"]').change(function(){
  var $selectedOption = $('select[name="brands_list"] option:selected');
  $('input[name="brand_name"]').val($selectedOption.text().split(' - ')[1]);
  $('input[name="brand_link"]').val($selectedOption.val().split(',')[2]);
});