JQuery Get Value from Select Option not working - javascript

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.

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 () {

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

Related

Adding an additional row of HTML form inputs using Javascript

I am attempting to dynamically add a new row of HTML form inputs (a new line which includes 6 inputs, namely, (Type(dropdown), Length, Width, Height, Weight and Quantity) into an existing "View" HTML form using Javascript.
The current HTML form inputs are then accessed in my controller file via PHP $_POST requests. This works fine by retrieving the "name" field in the HTML form.
So, a user completes the first line, which id for the shipment of one parcel, and they want to add a second parcel, so, they click on an add(or remove) to add or remove an extra line of inputs.
I have the code working without adding the second row. If you leave the form at default, all the $variables are retrieved for the controller to act on them.
I managed to get some Javascript code off the net which adds the second part of the input form correctly, but, I assumed the code would increment the "name" field so that the first shipment would be name=length and the second shipment would be name=length2. The code does need Bootstrap as well to work correctly.
I have PHP, HTML skills, but limited Javascript skills, hence my request please.
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
<!--cols += '<td><select class="form-control col-md-8" id="packaging_type" name="packaging_type' + counter + '"/></td>';-->
cols += '<td><input type="text" class="form-control" name="length' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="width' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="height' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="weight' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="quantity' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
Ultimately, once I have clicked on the Add Row and entered all of the inputs, I would want the script to numerically increment the "name" input of the HTML form and then be able access them via PHP $_POST.
If there is a better way of doing it, I am open to suggestions.
This won't work anyway, I would suggest using a guid instead of a counter since deleting a row before the last would cause the counter to set itself to the same number as the current last row.
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(3);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
I have managed to find a script that with customisation appears that it will resolve my problem. I will post the outcome once completed so that it may help any future users. The script link is found at :- https://www.jqueryscript.net/demo/Duplicate-Input-Fields-jQuery-Repeatable/
Basically what this script does it it allows you to duplicate DIVs in a table or form, and increments the indexes, "name" "id" etc.
I will be using it to dynamically add additional "inputs" on a form.

Passing values to multiple dynamically created controls base on bootstrap-3-typeahead dropdown list using JQuery

I am creating an invoice system using Laravel, JQuery and Bootstrap-3-typeahead and have created a button that dynamically adds new table row with text inputs in each table data on selection of a list item using JQuery. The first text input in each row has bootstrap-3-typeahead functionality: After selecting an item like this
creating invoice tutorial.
After selecting from the autocomplete text-input dropdown list, it automatically populates the price, quantity and assign a default value of "1" to the quantity input using the below Typeahead(afterSelect method) implementation using JQuery and Ajax GET method.
This is my
html markup screenshot.
My JQuery implementation of boostrap-3-typeahead and generation of auto price, quantity, and total values base on selected item from typeahead dropdown list.
var typeaheadSettings = {
source: function (query, process) {
return $.get(url, { query: query }, function (data) {
console.log(data)
return process(data);
});
},
afterSelect: function (data) {
console.log(data.sellPrice);
$('#itemPrice').val(data.sellPrice);
$('#itemQuantity').val('1');
var price = $('#itemPrice').val();
var quantity = $('#itemQuantity').val();
var subtotal = price * quantity;
$('#itemSubtotal').val(subtotal);
}
};
The JS code that adds new row on button click:
// Add Row
$(document).on('click', '#btnAddRow', function(event) {
var i=$('#invoiceTable tbody tr').size();
html = '<tr>';
html += '<td><p class="text-center pt-xs"><input type="radio" name="sn" id="sn" value=""></p></td>';
html += '<td><input type="text" name="productName[]" id="itemName'+ i +'" class="form-control typeahead twitter-typeahead" placeholder="Item name" autocomplete="off" data-fit-to-element="true" data-provide="typeahead"></td>';
html += '<td><input type="text" name="price[]" id="itemPrice'+i+'" class="form-control text-right" placeholder="Item price" autocomplete="off" readonly></td>';
html += '<td><input type="number" name="quantity[]" id="itemQuantity'+ i +'" class="form-control text-right" placeholder="Quantity"></td>';
html += '<td><input type="text" name="subtotal[]" id="itemSubtotal'+ i +'" class="form-control text-right" placeholder="Subtotal" readonly></td>';
html += '<td class="actions-hover actions-fade text-center"><p><a id="btnDelRow"><i class="fa fa-minus-circle fa-lg text-warning" id="iconDelRow"></i></a></p></td>';
html += '</tr>';
$('#invoiceTable tbody').append(html);
i++;
$('.typeahead').trigger('added');
});
This is what the markup of the dynamically added row looks like, with integer "1,2" suffixed to the ID.The integer increments if another row is added dynamically, giving all duplicate controls a unique ID.
dynamically added tr screenshot
The problem is that when i add a second control dynamically by clicking the "Add New Row" button shown on the image above, the dynamically added price and quantity input controls don't get the newly generated values. Instead, the values appear on the first already defined row. The same thing happens when i add the 3rd row and more.
I'd be glad if someone can help me out with a way i can pass the values generated after dropdown list item is selected to the right or appropriate inputs.
The HTML selector you are using seems to be an ID selector which should be unique per document. This may explain why this is happening.
It seems the values appear on the first defined row because you have coded only their IDs into the typeaheadSettings.afterSelect(...) function:
$('#itemPrice').val(data.sellPrice);
$('#itemQuantity').val('1');
var price = $('#itemPrice').val();
var quantity = $('#itemQuantity').val();
var subtotal = price * quantity;
$('#itemSubtotal').val(subtotal);
You should probably refactor the function so it can use the other auto-generated IDs like #itemPrice1, #itemSubtotal2, ...

cleaner way to attach event to dynamically rendered field

I attach a change event to a dynamically rendered form field like this:
var html ='';
html += '<div class="Gallery-overlayContentWrapper">';
html += '<center>';
html += '<h3>'+self.data('uploadHeading')+'</h3>'
html += parent;
html += '<form id="Gallery-uploadForm" enctype="multipart/form-data" method="post">';
html += '<input type="hidden" name="Gallery-Parent" id="Gallery-Parent" value="'+self.data('activeFolder')+'" />';
html += '<p><input type="file" name="file1" id="file1"></p>';
html += '<p><progress id="Gallery-uploadProgress" value="0" max="100"></progress></p>';
html += '</form>';
html += '</center>';
html += '</div>';
$(self).find(".Gallery-"+self.data('overlayType')).append(html);
$(self).find(".Gallery-"+self.data('overlayType')).fadeIn(); //This only covers the thumbs area
setTimeout(function(){
$(self).find('#file1').change(function(){
self.data('uploadFile')(self);
});
},1000);
This works, but it feels hackish to rely on the element being rendered after 1 sec like this, is there a cleaner way of doing this?
There is no need to use timeout, attach it right after appending
$(self).find(".Gallery-"+self.data('overlayType')).append(html);
$(self).find('#file1').change(function(){
self.data('uploadFile')(self);
});
$(self).find(".Gallery-"+self.data('overlayType')).fadeIn();
or use delegation
$(document).on('change', '#file1', function(){
self.data('uploadFile')(self);
});

How to get the textbox value which is dynamically added to a table row inside a <td>

I am appending a <td> having an input text to a row. I want to get the value of this textbox and use it in another function.
Below is the code snippet :
row.append($('<td ><input type="text" value=' + item.Marks + ' size="10px" class="marks" id="txtmarks" maxlength="3"/></td>'));
Thanks in advance.
Split it in two statements:
var input = $("<input type="text" size="10px" class="marks" id="txtmarks" maxlength="3"/>").val(item.Marks);
var newRow = $('<td></td>').append(input);
row.append(newRow);
So, now you have a reference to your input, and the code looks much cleaner.

Select all textboxes using jQuery

I have code which displayed a person's info in a table(fields:name, surname, address, etc.) and one of the inputs is a checkbox. The code is as follows:
$("#table").append('<tr class="trow'+j+'">'+
'<td class="ids" id="z'+i+'">'+totrecs+'</td>'+
'<td>'+member[i].jdate+'</td>'+
'<td class="users"
'<td id="contact'+i+'">'+member[i].fname+' '+member[i].lname+'</td>'+
'<td id="myaddress'+i+'">'+member[i].address1+' '+member[i].town+'</td>'+
'<td><input type="checkbox" name="whome" id="showMe'+i+'"'+
'class="boxes" onclick="getMe('+i+')" /></td></tr>');
totrecs++;
j++;
}
What I am tryin to do is program a function that when clicking a certain button all of the checkboxes will be selected/checked.
I would appreciate any help. Thank You.
this may be helpful: JQquery Select All Checkboxes tutorial
To check all checkboxes in #table using jQuery:
$('#table :checkbox').attr('checked', '');
Note that this will not trigger any click events you set for the checkboxes. You should use the change event instead of click to make it happen as expected.
<input type="button" value="Check/Uncheck All" />
$('#btnId').on('click', function() {
var check = false;
if( !$(this).hasClass('checked')){
bool = true;
}
$(this).toggleClass('checked');
$('#table input[type="checkbox"]').prop('checked', check)
});

Categories