Jquery TokenInput Pre-populate based on Selected option in Dropdown - javascript

I need to pre-populate textfields that's using jquery tokeninput based on what is populated from a readonly field right next to it. This readonly text field is populated based on the user's selection from a dropdown. I'm at a standstill as to best way to achieve this. Basically need to copy the value from the textfield (name=hndarea) to the dropdown (name=selarea) right next to it which is not using tokeninput. The other ones are both text fields, one readonly (hndManager1) and the other one (name=txtManager1) not read only using tokeninput. The user could change what's in the non-readonly textfield and dropdown if they wanted.
loc.js file
function setLocDropdown_other() {
var strval = $("#selPin").val();
if (strval != '') {
var $select = $('#selLocation')
$select.empty();
$select.append('<option value="" selected> --Please select--</option>');
getdropdowndata('/cfc/LocMatrix.cfc?method=getLocJson&Pin=' + strval,$select,'',strval)
}
}
function getLocInfo(obj)
{
var $Pin = $("#selPin").val();
var $Loc = $("#selLocation").val().split("~");
$.ajax({
url: "/cfc/LocMatrix.cfc?method=LocMatrixDetailsJson&Pin=" + $Pin + '&Location='+ $Loc[0],
dataType: "json",
maxrow: 1,
dataFilter: function (data) { return data; },
success: function (data) {
//map columns to names
$('#hndVP').val('')
$('#hndManager1').val('')
var columnMap = {}
for (var i = 0; i < data.COLUMNS.length; i++) {
columnMap[data.COLUMNS[i]] = i
}
for (var i = 0; i < data.DATA.length; i++) {
$('#trChangeValue').show()
$('#hndarea').val(data.DATA[i][columnMap.area])
$('#hndarea').show()
if (data.DATA[i][columnMap.VP_E] != null) {$('#hndVP').val(data.DATA[i][columnMap.VP_E])}
$('#hndVP').show()
if (data.DATA[i][columnMap.Loc_MGR_E1] != null) {$('#hndManager1').val(data.DATA[i][columnMap.Loc_MGR_E1])}
$('#hnManager1').show()
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
page.cfm
<script>
$(document).ready(function()
{
//autocomplete using tokeInput....
$("#txtVP").tokenInput("/cfc/users.cfc?method=userAutoCompleteJSON", {
theme: "vweb",
tokenLimit: 1,
queryParam: "exchUsername",
tokenFormatter: function(item){
return "<li><p>" + item.id + "</p></li>"
}
});
$("#txtManager1").tokenInput("/cfc/users.cfc?method=userAutoCompleteJSON", {
theme: "vweb",
tokenLimit: 1,
queryParam: "exchUsername",
tokenFormatter: function(item){
return "<li><p>" + item.id + "</p></li>"
}
});
})
</script>
<cfoutput>
<script>
$(document).ready(function()
{
<cfif form.txtRequestor neq "">
$("##txtRequestor").tokenInput("add", {id: "#form.txtRequestor#", name:"#form.txtRequestor#"});
</cfif>
<cfif form.txtVP neq "">
$("##txtVP").tokenInput("add", {id: "#form.txtVP#", name:"#form.txtVP#"});
</cfif>
<cfif form.txtManager1 neq "">
$("##txtManager1").tokenInput("add", {id: "#form.txtManager1#", name:"#form.txtManager1#"});
</cfif>
});
</script>
</cfoutput>
<tr>
<td class="tdheader">area <span class="required">*</span></td>
<td>
<div style="float:left;"><input type="text" id="hndarea" name="hndarea" class="hndFields" readonly="true" value="#form.hndarea#"></div>
<div style="float:left;">
<cfselect name="selarea" style="width:233px;">
<cfloop query="#getLocMatrixSelectionP['area']#">
<option value="#val#" <cfif form.selarea eq val>Selected</cfif>>#desc#</option>
</cfloop>
</cfselect>
<span id="label_selarea" class="err"></span>
</div>
</td>
</tr>
<tr>
<td class="tdheader" valign="top">VP <span class="required">*</span></td>
<td valign="top">
<div style="float:left;"><input type="text" id="hndVP" name="hndVP" class="hndFields" readonly="true" value="#form.hndVP#"></div>
<div style="float:left;"><cfinput type="text" name="txtVP" style="float:left !important;">
<span id="label_txtVP" class="err"></span></div></td>
</tr>
<tr>
<td class="tdheader" valign="top">Manager 1 <span class="required">*</span></td>
<td nowrap="nowrap">
<div style="float:left;"><input type="text" id="hndManager1" name="hndManager1" class="hndFields" readonly="true" value="#form.hndManager1#"></div>
<div style="float:left;"><cfinput type="text" name="txtManager1">
<span id="label_txtManager1" class="err"></span></div>
</td>
</tr>

Related

How can I select all checkboxes in mvc

This code below select only one by one checkbox, how can I transform this code so I can select all checkboxes by one click, but I need my variables to stay defined.
$('.checktip').click(function () {
var iduser = $('.iduser').val();
var idtip = $(this).attr('idtip');
var che = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.OrgUnits,
data: { iduser: iduser, idtip: idtip, che: che },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});
I using this variables for controller where I save this values in database when I check them or unchecked.
Here is my html code
<input type="hidden" value="#ViewBag.iduser" id="iduser" />
<hr />
<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
//Checkbox for check all *(NOT IMPLEMENTED)*
<input type="checkbox" id="box" name="checkAll" />
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
#*#Html.CheckBox(item.id.ToString(), item.iduser == ViewBag.iduser ? true : false, new { idtip = item.idtip, #class = "checktip" })*#
<div class="pure-checkbox">
<input type="checkbox" idtip="#item.idtip" class="checktip" checked="#(item.iduser == ViewBag.iduser ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
Following code should work with your code
$('#box').click(function(){ $('.checktip').prop('checked', true); }};

jquery DataTables parent and child rows posted to server as one record instead of two

I have a problem where jquery DataTables creates parent and child rows on resize (responsive DataTable) and I need to save values of inputs from child rows as well as from parent rows and post via ajax to controller action.
Responsive (resized) DataTable:
Normal (not resized) DataTable:
Currently I am using this jquery function to post data to the server:
$('#SaveItemButton').click(function (e) {
var arr = [];
var rows = $('#ItemTable').find('tbody').find('tr');
console.log(rows.length);
$.each(rows, function (index, item) {
var controls = $(this).find('input, select');
console.log(controls.length);
item = {
ItemType: controls.eq(0).val(),
Unit: controls.eq(1).val(),
Quantity: controls.eq(2).val(),
Price: controls.eq(3).val(),
InvoiceDate: $('#InvoiceDate').val(),
TransferDate: $('#TransferDate').val(),
TransferPlace: $('#TransferPlace').val(),
InvoiceDescription: $('#InvoiceDescription').val()
};
arr.push(item);
});
$.ajax({
url: '/Item/Add',
data: JSON.stringify(arr),
contentType: 'application/json',
type: "POST",
dataType: "json",
success: function (result) {
//alert(result);
},
error: function (errormessage) {
}
});
return false;
});
but when the Datatable is resized it returns two rows which in turn gets posted to the server.
I am retrieving rows from a table via:
var rows = $('#ItemTable').find('tbody').find('tr');
How can I get all the related parent rows and child rows as one row so I can post that row to the server?
Parent row example:
<tr role="row" class="odd parent">
<td tabindex="0" style=""></td>
<td class="sorting_1"><input name="ItemType" class="form-control" type="text"></td>
<td style="display: none;"><select name="Unit" class="form-control defaultpicker"><option>dan</option><option>Komad</option><option>Sat</option>m<option>m2</option><option>m3</option><option>kg</option><option>lit</option><option>pak</option><option>reč</option></select></td>
<td style="display: none;"><input name="Quantity" class="form-control" type="number"></td>
<td style="display: none;"><input name="Price" class="form-control" type="text"></td>
<td style="display: none;"><input name="Total" class="form-control" type="text" readonly=""></td>
<td style="display: none;"><button type="submit" id="DeleteButton" class="fa fa-times select-row btn btn-secondary btn-sm" data-id=""></button>
</td>
</tr>
Child row example:
<tr class="child">
<td class="child" colspan="2">
<ul data-dtr-index="0" class="dtr-details">
<li data-dtr-index="2" data-dt-row="0" data-dt-column="2">
<span class="dtr-title">Unit</span>
<span class="dtr-data">
<select name="Unit" class="form-control defaultpicker"><option>dan</option><option>Komad</option><option>Sat</option>m<option>m2</option><option>m3</option><option>kg</option><option>lit</option><option>pak</option><option>reč</option></select>
</span>
</li>
<li data-dtr-index="3" data-dt-row="0" data-dt-column="3">
<span class="dtr-title">Quantity</span>
<span class="dtr-data">
<input name="Quantity" class="form-control" type="number" value="3">
</span>
</li>
<li data-dtr-index="4" data-dt-row="0" data-dt-column="4">
<span class="dtr-title">Price</span>
<span class="dtr-data">
<input name="Price" class="form-control" type="text" value="1000">
</span>
</li>
<li data-dtr-index="5" data-dt-row="0" data-dt-column="5">
<span class="dtr-title">Total</span>
<span class="dtr-data">
<input name="Total" class="form-control" type="text" readonly="" value="">
</span>
</li>
<li data-dtr-index="6" data-dt-row="0" data-dt-column="6">
<span class="dtr-title"></span>
<span class="dtr-data">
<button type="submit" id="DeleteButton" class="fa fa-times select-row btn btn-secondary btn-sm" data-id=""></button>
</span>
</li>
</ul>
</td>
</tr>
Controller posted data, index 0 contains valid data:
Code Snippet:
var table = $('#ItemTable').DataTable({
"dom": '<"toolbar">frtip',
"paging": true,
"pagingType": "full_numbers",
"searching": false,
// Solution to responsive table losing data
'columnDefs': [{
'targets': [1, 2, 3, 4, 5, 6],
'render': function(data, type, row, meta) {
if (type === 'display') {
var api = new $.fn.dataTable.Api(meta.settings);
var $el = $('input, select, textarea', api.cell({
row: meta.row,
column: meta.col
}).node());
var $html = $(data).wrap('<div/>').parent();
if ($el.prop('tagName') === 'INPUT') {
$('input', $html).attr('value', $el.val());
if ($el.prop('checked')) {
$('input', $html).attr('checked', 'checked');
}
} else if ($el.prop('tagName') === 'TEXTAREA') {
$('textarea', $html).html($el.val());
} else if ($el.prop('tagName') === 'SELECT') {
$('option:selected', $html).removeAttr('selected');
$('option', $html).filter(function() {
return ($(this).attr('value') === $el.val());
}).attr('selected', 'selected');
}
data = $html.html();
}
return data;
}
}],
'responsive': true,
order: [1, 'asc']
});
// Solution to responsive table losing data
$('#ItemTable tbody').on('keyup change', '.child input, .child select, .child textarea', function(e) {
var $el = $(this);
var rowIdx = $el.closest('ul').data('dtr-index');
var colIdx = $el.closest('li').data('dtr-index');
var cell = table.cell({
row: rowIdx,
column: colIdx
}).node();
$('input, select, textarea', cell).val($el.val());
if ($el.is(':checked')) {
$('input', cell).prop('checked', true);
} else {
$('input', cell).removeProp('checked');
}
});
$('#SaveItemButton').click(function() {
var arr = [];
var rows = $('#ItemTable').find('tbody').find('tr');
console.log(rows.length);
$.each(rows, function(index, item) {
var controls = $(this).find('input, select');
console.log(controls.length);
item = {
ItemType: controls.eq(0).val(),
Unit: controls.eq(1).val(),
Quantity: controls.eq(2).val(),
Price: controls.eq(3).val(),
InvoiceDate: $('#InvoiceDate').val(),
TransferDate: $('#TransferDate').val(),
TransferPlace: $('#TransferPlace').val(),
InvoiceDescription: $('#InvoiceDescription').val()
};
arr.push(item);
});
$.ajax({
url: '/Item/Add',
data: JSON.stringify(arr),
contentType: 'application/json',
type: "POST",
dataType: "json",
success: function(result) {
//alert(result);
},
error: function(errormessage) {
}
});
return false;
});
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet" />
<table id="ItemTable" class="table table-hover table-secondary dataTable no-footer dtr-inline" style="width: 100%;" role="grid" aria-describedby="ItemTable_info">
<thead>
<tr role="row">
<th></th>
<th>ItemType</th>
<th>Unit</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd parent">
<td tabindex="0" style=""></td>
<td class="sorting_1"><input name="ItemType" class="form-control" type="text"></td>
<td style="">
<select name="Unit" class="form-control defaultpicker">
<option>value1</option>
<option>value2</option>
<option>value3</option>
<option>value4</option>
<option>value5</option>
<option>value6</option>
<option>value7</option>
<option>value8</option>
<option>value9</option>
</select>
</td>
<td style=""><input name="Quantity" class="form-control" type="number"></td>
<td style=""><input name="Price" class="form-control" type="text"></td>
<td style=""><input name="Total" class="form-control" type="text" readonly=""></td>
<td style=""><button type="submit" id="DeleteButton" data-id=""></button></td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.6/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
Well, you really cannot. At first DT inject and remove child rows and their content to and from the DOM, making them invisible to simple jQuery selectors. You can target open child rows, but that is all.
Secondly you cannot select multiple elements in pairs. You could have for example $('tr.parent, tr.parent ~ tr.child') or similar, but that would be equal to just $('tr'). I would go through the API:
table.rows().every(function() {
var $node = this.nodes().to$();
var item = {
ItemType: $node.find('input[name=ItemType]').val(),
Unit: $node.find('select[name=Unit]').val(),
Quantity: $node.find('input[name=Quantity]').val(),
Price: $node.find('input[name=Price]').val(),
Total: $node.find('input[name=Total]').val(),
InvoiceDate: $('#InvoiceDate').val(),
TransferDate: $('#TransferDate').val(),
TransferPlace: $('#TransferPlace').val(),
InvoiceDescription: $('#InvoiceDescription').val()
};
arr.push(item)
})
Completely untested. See JQuery Datatables search within input and select on how to update the DT internals when form controls is changing. Otherwise you will just get return default / original values.

I want to combine 2 different java scripts

I have 2 java script codes, one work as a search suggestion and second is for adding another form fields dynamically and this second script also calculate values given in input fields, but both scripts have this 'ADD MORE PRODUCT' feature. What i want is; i want to combine both 'ADD more" feature, because 1st script works on id="" tag to identify field to show search result but second script not do it.
Fetching details in first row is successful, but when i click ADD more button populated by second script, it does not work
//Script to fetch details based on search box :
$(document).ready(function() {
$(document).on('keydown', '.prname', function() {
var id = this.id;
var splitid1 = id.split('_');
var index1 = splitid1[1];
$('#' + id).autocomplete({
source: function(request, response) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 3
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$(this).val(ui.item.label); // display the selected text
var prid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {
prid: prid,
request: 4
},
dataType: 'json',
success: function(response) {
var len = response.length;
if (len > 0) {
var id = response[0]['id'];
var fprice = response[0]['fprice'];
var packing = response[0]['packing'];
var pweight = response[0]['pweight'];
document.getElementById('fprice_' + index1).value = fprice;
document.getElementById('packing_' + index1).value = packing;
document.getElementById('pweight_' + index1).value = pweight;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function() {
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='name' id='name_" + index + "' placeholder='Enter name'></td><td><input type='text' class='phone' id='phone_" + index + "' ></td><td><input type='text' class='address' id='address_" + index + "' ></td><td><input type='text' class='custid' id='custid_" + index + "' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
// Second script to do calculation :
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('keyup change', function() {
calc_total();
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.fprice').val();
var discount = $(this).find('.discount').val();
$(this).find('.total').val((qty * price) - discount);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table class="table table-bordered table-hover" style='border-collapse: collapse;' id="tab_logic">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center"> Product </th>
<th width="190px" class="text-center"> Price </th>
<th width="30px" class="text-center"> Price for </th>
<th width="100px" class="text-center"> Packing </th>
<th width="80px" class="text-center"> Qty </th>
<th width="100px" class="text-center"> Discount </th>
<th width="150px" class="text-center"> Total </th>
</tr>
</thead>
<tbody>
<tr class='tr_input' id='addr0'>
<td>1</td>
<td><input type="text" name='product[]' id="prname_1" class="prname form-control" /></td>
<td>
<input type="number" name='price[]' id='fprice_1' class="form-control fprice price" step="0.00" min="0" />
</td>
<td><input style="width:70px" type="text" class="pweight input-group-text" id="pweight_1"></td>
<td><input type="text" name='pack[]' class="form-control packing" id='packing_1' step="0" min="0" /></td>
<td><input type="text" name='qty[]' class="form-control qty" id="qty_1" step="0" min="0" /></td>
<td><input type="text" name='discount[]' class="form-control discount" id="discount_1" step="0.00" min="0" /></td>
<td><input type="number" name='total[]' class="form-control total" id="total_1" readonly/></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>

How to auto change select in accordance with same row table using jQuery ajax change function

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.

Add textbox value to multiple select box via JavaScript

I have a textbox in which the user is allowed to enter alphanumeric input. I also have a plus image which on clicking will have to add the entered text to a multiple select box called "add key num" (shown below). After adding a few inputs to the multiple select box "add key num", the user can click the left arrow to add the final list to the "list key num" select box. I am stuck on the JavaScript for adding the text input from the textbox to the first select box. Please advise.
Here is the code that I have:
<cfparam name="SESSION.stkeynum" default="">
<table border="1" align="center" STYLE="margin-left:120px;" bgcolor="##B0C4DE">
<tr>
<td align="center" >ENTER KEY NUM</td>
<td align="center" ></td>
<td align="center" >ADD KEY NUM</td>
<td align="center" ></td>
<td align="center" >LIST KEY NUM</td>
<td align="center" >AMOUNT</td>
</tr>
<tr>
<td align="center"><input type="text" maxlength ="8" name="vstkeynum" id="vstkeynum" value="" size="15"></td>
<td><img src="../images/plus.jpg" alt="Add Key number" onclick="add_cc(document.myform.vstkeynum.value);"></img></td>
<td nowrap>
<div id="Div1"></div>
<select name="keynumber" size="5" multiple style="width: 175px; display: inline;">
<option value="null"> </option>
</select>
</td>
<td><img src="../images/arrow_right.gif" alt="Add To List" onclick="copySelectedOptions_edit(document.myform.keynumber,document.myform.keynumber_selection);">
<hr>
<img onclick="removeSelectedOptions_edit(document.myform.keynumber_selection);" src="../images/arrow_left.gif" alt="Delete From List">
</td>
<td nowrap>
<select name="keynumber_selection" size="5" multiple style="width: 175px;">
</select>
</td>
<td align="center"><input type="text" maxlength ="8" name="amount" id="amount" value="" size="7"></td>
</tr>
</table>
JavaScript:
<script type="text/javascript">
function add_cc(a) {
// inital load
ajax({
url: 'add_keynum.cfm?vval=' + a,
fillDiv: 'Div1',
showBusy: true
});
document.myform.vstkeynum.value = "";
}
</script>
<script>
function copySelectedOptions_edit(from, to) {
var options = new Object();
if (hasOptions(to)) {
for (var i = 0; i < to.options.length; i++) {
options[to.options[i].value] = to.options[i].text;
}
}
if (!hasOptions(from)) {
return;
}
for (var i = 0; i < from.options.length; i++) {
var o = from.options[i];
if (o.selected) {
if (options[o.value] == null || options[o.value] == "undefined" || options[o.value] != o.text) {
if (!hasOptions(to)) {
var index = 0;
} else {
var index = to.options.length;
}
to.options[index] = new Option(o.text, o.value, false, false);
}
}
}
if ((arguments.length < 3) || (arguments[2] == true)) {
sortSelect(to);
}
from.selectedIndex = -1;
to.selectedIndex = -1;
}
function removeSelectedOptions_edit(from) {
if (!hasOptions(from)) {
return;
}
if (from.type == "select-one") {
from.options[from.selectedIndex] = null;
} else {
for (var i = (from.options.length - 1); i >= 0; i--) {
var o = from.options[i];
if (o.selected) {
from.options[i] = null;
}
}
}
from.selectedIndex = -1;
}
</script>
This is the code in add_keynum.cfm:
<cfif isDefined("vval") >
<cfif trim(vval) neq "">
<cfset SESSION.stkeynum = Listappend(SESSION.stkeynum,vval)>
<cfoutput>#SESSION.stkeynum#</cfoutput>
<cfelse>
<cfif isDefined("session.stkeynum")>
<cfoutput>#SESSION.stkeynum#</cfoutput>
</cfif>
</cfif>
</cfif>

Categories