2

I dont know why my jquery code does not works to get value from select option.

I have created a function where when I click on "Add New Row" button then it will create a new row to my table.

Here's my JS code to add new row

$(".tambah_sofa").on('click',function(){
    html = '<tr id="row_'+i+'">';
    html += '<td><button type="button" id="delete-button" data-row-delete="row_'+i+'">X</button></td>';
    html += '<td><select name="sofa[]" id="sofa"> <option value="'+sofa_rumah+'">Sofa rumah</option><option value="'+sofa_pejabat+'">Sofa Pejabat</option><option>Sofa Kedai</option><option>Tilam Tak Bujang</option> </select> </td>';
    html += '<td>X</td>';
    html += '<td><input type="number" name="quantity[]" id="quantity_'+i+'" value="1" disabled="disabled"></td>';
    html += '</tr>';
    sidebar = '<tr id="row_'+i+'">';
    sidebar += '<td><input style="width:50%;" type="text" id="price_sofa" value="" disabled="disabled"></td>';
    sidebar += '</tr>';
    $('#table_item').append(html);
    $('#table_sidebar').append(sidebar);
    i++;
});

Below is my code to get select option values into textbox :

    $('#sofa').on('change', function () {
    $('#price_sofa').val(this.value);
    }).trigger('change');

I try to follow this JSfiddle demo : http://jsfiddle.net/JwB6z/2/

The code is working but when I try implement to my "add new row" function, it's not working.

G5W
  • 36,531
  • 10
  • 47
  • 80
Aizuddin Badry
  • 454
  • 3
  • 9
  • 22

2 Answers2

4

I believe this is because any new row is not being recognised. I think you should bind the change to body...

example:

$('body').on('change', '#sofa', function () {
cpardon
  • 487
  • 4
  • 24
1

you can always use this:

$('#sofa').on('change', function () {
$('#price_sofa').find(':selected').val();
}).trigger('change');

EDIT: The above one is used to get the value you entered if you want to add the text and not value you can always put

$('#price_sofa).find(':selected').text();

EDIT2: When you use $('#price_sofa').val(this.value); you are not taking the selected option and a you can see in the fiddle here that you added they didn't use the function that you used.

Hope this helps

eBourgess
  • 304
  • 4
  • 15
  • 1
    They are working fine when i not append the row table. The code not working when i use my JS code to append new row into table. I totally lost here... – Aizuddin Badry Feb 12 '17 at 02:06
  • always use the one I wrote for you, it's more successful than the one that you used. for more information kindly llook [Here](http://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – eBourgess Feb 12 '17 at 02:11
  • 1
    Thanks ! I learn something new today. The code you wrote for me really help me. – Aizuddin Badry Feb 12 '17 at 02:18