Morning,
I'm trying to create a table with dropdown (selectpicker A) fill dynamically with data selected with result of other input (selectpicker B) not into this table.
Filling (SelectPicker A) its OK for first row of table after selected value into SelectPicker B.
But when i add new line (by clone), SelectPicker A is empty for second row.
Need your help, thks !
My view code :
<select class="form-control selectpicker" name="nc_A" id="nc_A" onchange="select_B(this)" type="string" required>
<option disabled> </option>
</select>
...
<table id="sub_table" class="table">
<thead">
<tr>
<th>{{__('test.B')}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="nc_B[]" id="nc_B" type="string" required>
<option> </option>
</select>
</td>
</tr>
</tbody>
</table>
<i class="btn" onclick="add_row()">{{" + ".__('home.ajoutligne')}}</i>
My Jquery code :
var clonednc = $("#sub_table tbody tr:first").clone()
$("select[name*=nc_B]").selectpicker()
function add_row() {
$(clonednc).find("input").val("")
$("<tr>" + $(clonednc).html() + "</tr>").appendTo($("#sub_table tbody"))
$("#sub_table tbody tr:last select").selectpicker()
}
function select_B(e)
{
var selectionA = e.value;
$.ajax({
type: "POST",
url: "/production/selectionB",
data: {_token: CSRF_TOKEN, ncA : selectionA },
dataType: "JSON",
success: function (data) {
$(e).parents('div').find('#nc_B').empty();
$.each(data, function(key,value){
$(e).parents('div').find('#nc_B').append('<option value="'+value.NumB+'">'+ value.NumB +'</option>');
});
$("select[name*=nc_B]").selectpicker('refresh');
}
});
}
Related
I have the following codes which makes an select list to auto populate from a table and another which auto populate from another table (both in the same db) without using a submit button. All works ok but there is also a button that if clicked will make another table row with the same select fields.
The questions are: - what is wrong in the code because when i click on add another row button, it displays another row but only the first select is operational. i need both select to be operational; - what to use instead of the first javascript code for the cloning of the row but keep full functionality
Here are the codes:
Javascript for new row
<script>
function addField(n) {
var tr = n.parentNode.parentNode.cloneNode(true);
document.getElementById('tbl').appendChild(tr);
}
</script>
script querying
<script>
$(document).ready(function() {
$("#id_produs").change(function() {
var id_produs = $(this).val();
$.ajax({
url: 'query.php',
type: 'post',
data: {
id_produs: id_produs
},
dataType: 'json',
success: function(response) {
var len = response.length;
$("#cod_produs").empty();
for (var i = 0; i < len; i++) {
var id_produs = response[i]['id_produs'];
var cod_produs = response[i]['cod_produs'];
$("#cod_produs").append("<option value='" + id_produs + "'>" + cod_produs + "</option>");
}
}
});
});
});
</script>
PHP & HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl">
<tr>
<td>Produse</td>
<td>Cod Produs</td>
<td>Cantitate</td>
<td></td>
</tr>
<tr>
<td>
<select id="id_produs">
<option value="0">- Select -</option>
<?php
if ($rezultatproduse->num_rows > 0) {
while($rowproduse = $rezultatproduse->fetch_assoc()) {
?>
<option value="<?php echo $rowproduse[" id_denumire "]; ?>">
<?php echo $rowproduse["denumire"]; ?>
</option>
<?php
}
}
?>
</select>
</td>
<td>
<select id="cod_produs">
<option value="0">- Select -</option>
</select>
</td>
<td>
<input type="text" name="cantitate" />
</td>
<td><input type="submit" class="button" value="Add another line" onclick="addField(this);" /></td>
</tr>
</table>
and also query.php
<?php
include "conn.php";
$id_produs = $_POST['id_produs'];
$sql = "SELECT id_produs, cod_produs FROM coduri_produse WHERE id_produs = ".$id_produs;
$result = mysqli_query($conn,$sql);
$coduri_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id_produs = $row['id_produs'];
$cod_produs = $row['cod_produs'];
$coduri_arr[] = array("id_produs" => $id_produs, "cod_produs" => $cod_produs);
}
// encoding array to json format
echo json_encode($coduri_arr);
?>
Change this
$("#id_produs").change(function() {
to this
$(document).on('change', "#id_produs", function() {
If you want an event to work on dynamically added elements you need to bind it to document and not to elements. Because jQuery bunds an event only to elements which are currently in DOM.
$(document).on('change', "#id_produs", function() {
var id_produs = $(this).val();
$.ajax({
url: 'query.php',
type: 'post',
data: {
id_produs: id_produs
},
dataType: 'json',
success: function(response) {
var len = response.length;
$("#cod_produs").empty();
for (var i = 0; i < len; i++) {
var id_produs = response[i]['id_produs'];
var cod_produs = response[i]['cod_produs'];
$("#cod_produs").append("<option value='" + id_produs + "'>" + cod_produs + "</option>");
}
}
});
});
function addField(n) {
var tr = n.parentNode.parentNode.cloneNode(true);
document.getElementById('tbl').appendChild(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl">
<tr>
<td>Produse</td>
<td>Cod Produs</td>
<td>Cantitate</td>
<td></td>
</tr>
<tr>
<td>
<select id="id_produs">
<option value="0">- Select -</option>
<option value="test_value">
test value
</option>
</select>
</td>
<td>
<select id="cod_produs">
<option value="0">- Select -</option>
</select>
</td>
<td>
<input type="text" name="cantitate" />
</td>
<td><input type="submit" class="button" value="Add another line" onclick="addField(this);" /></td>
</tr>
</table>
EDIT
Also you should avoid adding elements with the same id.
That is the reason why wrong select is activated. Change id to class and of course in jQuery change id to class.
The same goes for this $("#cod_produs"). Make sure that you get the exzact element. Because right now it will work for all elements with id="cod_produs".
So change to something like this (example):
Instead of this
$("#cod_produs").empty();
do
$(this).closest(".cod_produs").empty();
I have form input dynamically row on table area. My first schema on first row is running well using automatic filling field change ajax function:
but I have problem in the second row and next row too. When I change the select option on second row, the previous field changed (not same row as what I have changed):
How to automatic filling same row with the select option..?
Here my html code:
<?php echo form_open_multipart(base_url().'back/transaksi/Order/insert_temp', array('role' => 'form', 'class' => 'form-horizontal', 'method'=>'POST','id'=>'Validation_form'));?>
<fieldset style="min-width: 0;padding:.35em .625em .75em!important;margin:0 2px;border: 2px solid black!important;margin-bottom: 10em;">
<legend style="border-bottom: none;width: inherit !important; padding:inherit; font-weight:bold; color:red;">Form Input</legend>
<button class="btn btn-success add_field_button" type="button" onClick="addRow('dataTable')">Add </button>
<input type="button" class="btn btn-danger" value="Remove" Field" onClick="deleteRow('dataTable')"/>
<div> </div>
<table id="dataTable" class="table table-striped table-responsive table-bordered dataTable" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="selectall" value="selectAll"/></th>
<th class="text-center">No</th>
<th class="text-center">Item</th>
<th class="text-center">Konversi</th>
<th class="text-center">Spesifikasi</th>
<th class="text-center">qty</th>
<th class="text-center">Satuan</th>
<th class="text-center">Note</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="check"></td>
<td id="no">
</td>
<td>
<select name="id_komoditi[]" id="id_komoditi" class="form-control chzn_select_L">
<option value="">--- Pilih Item ---</option>
<?php
foreach($id_komoditi as $a)
{
echo "<option value='".$a['id_komoditi']."'>".$a['nama_komoditi']."</option>";
}
?>
</select>
</td>
<div class="input_fields_wrap1">
<div><input type="hidden" name="id_order[]" id="id_order" value="<?php echo $_GET['id'];?>"></div>
</div>
<div class="input_fields_wrap">
<div><input type="hidden" name="item[]"></div>
</div>
<td>
<select name="id_konversi_satuan[]" id="id_konversi_satuan" class="form-control chzn_select_R">
<option value="">--- Pilih Konversi ---</option>
<?php
foreach($id_konversi_satuan as $a)
{
echo "<option value='".$a['id_konversi_satuan']."'>".$a['satuan_awal']."</option>";
}
?>
</select>
</td>
<td><input name="spesifikasi[]" id="spesifikasi" type="text" class="form-control"></td>
<td><input name="qty[]" id="qty" type="text" class="form-control"></td>
<td><input name="satuan[]" id="satuan" type="text" class="form-control"></td>
<td><textarea name="note[]" id="note" type="text" class="form-control"></textarea></td>
</tr>
</tbody>
</table>
<button style="border-radius: 3px; box-shadow: 0 3px 6px rgba(0,0,0,0.9);" type="submit" class="btn btn-success">Entry</button>
</fieldset>
</form>
Here is my jQuery/Javascript code // for first change schema
$(document).ready(function(){
dataTable();
$('#selectall').click(function(event)
{
if(this.checked)
{
$('.check').each(function()
{
this.checked = true;
});
}
else
{
$('.check').each(function() {
this.checked = false;
});
}
});
$('#id_komoditi').on('change',function(){
$.ajax({
url: '<?=base_url();?>back/transaksi/Order/Detail_Item',
method: 'POST',
data:{
id_komoditi: $('#id_komoditi').val(),
},
dataType:'json',
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
});
});
and here the dynamically add row input Javascript function:
function addRow(dataTable){
var table = document.getElementById(dataTable);
var rowCount = table.rows.length;
if(rowCount < 301)
{
$(".chzn_select_L").chosen('destroy');
$(".chzn_select_R").chosen('destroy');
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
var wrapper = $(".input_fields_wrap");
var wrapper1 = $(".input_fields_wrap1");
$(wrapper).append('<div><input type="hidden" name="item[]"/></div>');
$(wrapper1).append('<div><input type="hidden" name="id_order[]" value="<?php echo $_GET['id'];?>"/></div>');
for(var i=0; i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}
else
{
alert("Maximum is 300.");
}
$(".chzn_select_L").chosen().on('change',function(e){
event.stopImmediatePropagation();
var id_komoditi = $(this).val();
$.ajax({
url: '<?=base_url();?>back/transaksi/Order/Detail_Item',
method: 'POST',
data:{
id_komoditi: id_komoditi,
},
dataType:'json',
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
});
$(".chzn_select_R").chosen();}
The Problem is, you didn't specify any row number here
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
that's why it's only changed the first element, since it didn't know which "spesifikasi" input to be changed.
SOLUTION
you should have something like this
<select name="id_komoditi[]" id="id_komoditi" class="form-control chzn_select_L" data-spesifikasi="0">
and this on your first spesifikasi input
with the value of data-spesifikasi is the same as the row number to change.
then edit your addRow function at the iteration line, so it will give row number value for the necessary input column
for(var i=0; i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
cellToChange = $(newcell).find('.form-control');
if($(cellToChange[0]).attr("class") == "form-control chzn_select_L")
$(cellToChange[0]).data("spesifikasi", (rowCount-1))
else if($(cellToChange[0]).attr("id") == "spesifikasi0")
$(cellToChange[0]).attr("id", "spesifikasi"+(rowCount-1))
}
and your chosen() function to be like this :
$(".chzn_select_L").chosen().on('change',function(e){
event.stopImmediatePropagation();
var id_komoditi = $(this).val();
var spesifikasi_target = $(this).data("spesifikasi");
$.ajax({
url: '<?=base_url();?>back/transaksi/Order/Detail_Item',
method: 'POST',
data:{
id_komoditi: id_komoditi,
},
dataType:'json',
success:function(hasil)
{
$('#spesifikasi'+spesifikasi_target).val(hasil.spesifikasi);
}
});
});
The number/index 0 is responsible for each row number you use, hence
you should change each input you're using to have an index in their id
and name to be the same as their row number
Therefore, you will get different target spesifikasi for each select input
P.S : Just ask more if you're still unclear about them
Your first change:
$('#id_komoditi').on('change',function(){
//...
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
Your second change:
$(".chzn_select_L").chosen().on('change',function(e){
//...
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
Both times you are changing #spesifikasi, so either you have the id multiple times which you need to change, or you have a different id then you need to use that one in the second function.
I am a beginner in Jquery and Rails.
I am trying to fetch data from rails controller and set the same to text fields located in Dynamic table.
HTML
<tbody id="template">
<tr>
<td>
<select name="order[order_placed][][itemname]" id="order_place_id" class="form-control delete-comment" style="width: 300px">
<option value=""></option>
<% Item.all.each do |item| %>
<option value="<%= item.item_name %>">
<%= item.item_name %>
</option>
<% end %>
</select>
</td>
<td><input name="order[order_placed][][quantity]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][tax]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][discount]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" size='10' class="form-control" /></td>
<td>
<button type="button" class="btn btn-default btn-sm sub" onClick="$(this).closest('tr').remove();">
<span class="glyphicon glyphicon-minus"></span>
</button>
</td>
</tr>
</tbody>
JS
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
$.ajax({
url: "/items/getdata",
type: 'get',
data: {data_value: $(this).val()},
dataType: 'json',
success: function (data) { $(this).closest('tr').next('td').next('td').next('td').find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$('input[name="order[order_placed][][tax]"]').val(data.tax);
$('input[name="order[order_placed][][discount]"]').val(data.discount);
}, error: function () {
alert('error');
}
});
});
Data is fetched properly and is set to the text boxes if we assign them directly(data.tax and data.discount are set properly).
As the table is dynamic, i am trying to put data by finding the closest tr element followed by next td(Select element) again next td(Quantity) again next td(Unit Price). [This is the text field i wanted to place data.]
But this is not working properly.
Can some one please help.
Advance Thanks...!!!
this doesn't refers to current element the success callback, thus $(this) will not work.
You can cache the reference of TR in a variable which can be used is the success callback
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
//Keep a reference of current element
var tr = $(this).closest('tr');
$.ajax({
...
success: function(data) {
tr.find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
tr.find('input[name="order[order_placed][][tax]"]').val(data.tax);
tr.find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
OR, You can set context option of $.ajax()
$(document).on('change', 'select', function() {
$.ajax({
...
context: $(this).closest('tr'), // Set context to TR
success: function(data) {
$(this).find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$(this).find('input[name="order[order_placed][][tax]"]').val(data.tax);
$(this).find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
I have a form that has a list of checkboxes and selection option. It's basically an order form. When a customer clicks on a checkbox I'd like the value of the Select Option as well as the Checkbox's value to be sent with the form.
I really don't know AJAX. I'm using a script I found to get all the data to a php file. What do I need to add to the jquery to make the option and checkbox value of all the checked items combine as one variable?
<table>
<tr>
<td>
<select class="qty" name="qty" id="qty">
<option value="1">1</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="Part1_1" name="Part[]" type="checkbox" value="Part 1">
</td>
</tr>
<tr>
<td>
<select class="qty" name="qty" id="qty1">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="Part1_2" name="Part[]" type="checkbox" value="Part 2">
</td>
</tr>
</table>
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "orderform.php",
data: sendData,
success: function(data){
$(".response_msg").text(data);
$(".response_msg").slideDown();
}
});
});
});
</script>
EDIT:
I'd like to pass along to the php a variable for each part. So if Part 1 is checked then the value of the checkbox and the value of the quantity will be grouped together.
You could use a FormData object which would allow you to append the value of the ComboBox and Select list and send that in an ajax request.
Check this FormData
You need to add the select value this way. And you should also add the new parameter in your method on the server. In the example I named it as select_param.
$(document).ready(function() {
$("#contact-form").on("submit", function(e) {
e.preventDefault();
var sendData = $(this).serialize();
$.ajax({
type: "POST",
url: "orderform.php",
data: sendData + "&select_param1=" + $("#qty option:selected").text() +
"&select_param2=" + $("#qty1 option:selected").text(),
success: function(data) {
$(".response_msg").text(data);
$(".response_msg").slideDown();
}
});
});
});
I am selecting an item from a select-option tag in a table to populate records from a database to fill another input field, but unfortunately, it only works for the first table row. When I add another table row with jquery, it does not work in the new added table row.
<table class="table table-borderd table-hover">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Discount %</th>
<th>Total</th>
<th><input type="button" class="btn btn-primary addmore" value="+"></th>
</tr>
</thead>
<tbody id="itemlist2" class="detailss">
<tr>
<td>
<select class="select-product form-control" name="product_name[]">
<option value="">
</option>
<?php
foreach ($product as $key ):
?>
<option value="<?php echo $key['id'] ?>">
<?php echo $key['product_name'] ?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<input type="text" name="price[]" class="price form-control" value="">
</td>
<td><input type="text" name="quantity[]" class="form-control"></td>
<td><input type="text" name="discount[]" class="form-control"></td>
<td><input type="text" name="total[]" class="form-control"></td>
</tr>
</tbody>
</table>
The script that add new row to table
<script>
var i=$('#itemlist2 tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><select class="select-product form-control" name="product_name[]"> <option value=""> </option><?php foreach ($product as $key ): ?><option value="<?php echo $key['id'] ?>"><?php echo $key['product_name'] ?></option><?php endforeach; ?></select></td>';
html += '<td><input type="text" name="price[]" class="price form-control" value=""></td>';
html += ' <td><input type="text" name="quantity[]" class="form-control"></td>';
html += '<td><input type="text" name="discount[]" class="form-control"></td>';
html += '<td><input type="text" name="total[]" class="form-control"></td>';
html += '</tr>';
$('#itemlist2').append(html);
i++;
});
</script>
The onchange function with ajax
<script>
$(function() {
$(document).on('change', '.select-product', function(){
$(this).change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: dataString,
cache: false,
success: function(html){
$('.price').parent().parent().find('.price').val(html);
}
});
});
});
});
</script>
Thanks for your time!
Use delegate for dynamically added element. For example
$(document).delegate( ".select-product", "change", function() {
$(this).change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: dataString,
cache: false,
success: function(html){
alert(html);
// $("#price").val(html);
}
});
});
});
});
I hope it will help you.
New added elements does not have the event binding.
The quickest fix is just change your event binding code from
$('input').change(function () {
// Do some stuff.
});
to
$(document).on('change', 'input', function() {
// Do some stuff.
});
Check these following lines:
html += '<td><select class="select-product form-control" id="product" ....
and
var id=$("#product").val();
You are assigning an id to multiple rows and trying to get the values using id which is unique. That's why you are getting the data for first row only.
To solve this, refer it using class and $(this) to get the value of current instance.