How do I get the input value using a data attribute inside the body?
I have a dynamic form on my page and I have turned on automatic totals. Now my problem is that I want to get the specific value of the input using the data attribute:
I have a code like this:
$('#add-particular').on('click', function(){
var add_row = '<tbody id="row-parent-' + quot_row + '">';
add_row += ' <tr id="quot-parent-' + quot_row + '" class="uk-animation-slide-left" style="background: #C8D4DA">';
add_row += ' <td class="uk-text-center uk-text-bold">' + quot_row + '.0</td>';
add_row += ' <td class="uk-text-center"><input type="text" class="uk-form-width-medium" name="quotation[' + quot_row + '][\'particular\']" data-name="particular" /></td>';
add_row += ' <td class="uk-text-center"><input type="number" min="0" name="quotation[' + quot_row + '][\'unit\']" data-name="unit" class="uk-form-width-small uk-text-center" value="0" onClick="this.select()" onChange="computeParentTotal(' + quot_row + ', \'int\')" /></td>';
add_row += ' <td class="uk-text-center">';
add_row += ' <select name="quotation[' + quot_row + '][\'unit_label\']" class="uk-form-width-small" data-name="unit_label">';
add_row += ' <option value="">--</option>';
add_row += ' <option value="sqm">Sqm</option>';
add_row += ' <option value="lot">Lot</option>';
add_row += ' <option value="sets">Sets</option>';
add_row += ' </select>';
add_row += ' </td>';
add_row += ' <td class="uk-text-center"><input type="text" class="uk-text-right uk-form-width-small" value="0.00" onChange="computeParentTotal(' + quot_row + ', \'dec\')" name="quotation[' + quot_row + '][\'unit_price\']" data-name="unit_price" /></td>';
add_row += ' <td class="uk-text-center"><input type="text" class="uk-text-right uk-form-width-small" id="parent-subtotal-' + quot_row + '" readonly name="quotation[' + quot_row + '][\'total_price\']" data-name="total_price"/></td>';
add_row += ' <td class="uk-text-center"><button type="button" onClick="addParentParticular(' + quot_row + ')" class="uk-button uk-button-primary"><i class="fa fa-plus-circle"></i></button> <button type="button" class="uk-button uk-button-danger" onClick="removeParentParticular(' + quot_row + ')"><i class="fa fa-minus-circle"></i></button></td>';
add_row += ' </tr>';
add_row += '</tbody>';
$('#no-quot').remove();
$('#quotation-list').append(add_row);
quot_row++;
});
And I have an event trigger like this:
function computeParentTotal(id, type) {
var unit = $('#quot-parent-' + id + ' td').data('unit').val();
$('#parent-subtotal-' + id).val(unit);
}
But I got the following error:
TypeError: $ (...). data (...) - undefined
source to share
You need to use attribute equal to selector since unit
is the attribute valuedata-name
var unit = $('#quot-parent-' + id + ' td input[data-name="unit"]').val();
var unit = $('#quot-parent-' + id + ' td').data('unit')
will try to get the value unit
from the first element td
in the element '#quot-parent-' + id
, which is thus missing.
source to share