How can I display value in table row? - javascript

I am trying to edit a open-source project which I downloaded from internet
I want to display the value of HSN no. in table,here is the code.
var $hsn;
$("#invoice_item").delegate(".product_name","change",function(){
var pid = $(this).val();
var tr = $(this).parent().parent();
if (pid != 0) {
$.ajax({
url : domain+"/includes/update.php",
method : "POST",
data : {get_price_qty:1,pid:pid},
success : function(data){
if(data == "NO_PRODUCT"){
alert("Sorry, Selected product is not available");
}else{
var ar = data.split(",");
tr.find(".pro_name").val(ar[2]);
tr.find(".price").val(ar[0]);
tr.find(".total_qty").val(ar[1]);
tr.find(".qty").val(0);
tr.find(".hsn").val(ar[3]);
tr.find(".amt").html(tr.find(".price").val() * tr.find(".qty").val());
$hsn=ar[3];
$("#discount").val(0);
}
}
})
}else{
alert("Please Select at least one product");
} })
Here is how the table looks
Now the code for adding a new row is as below
if (isset($_POST["addNewRow"])) {
$num = $_POST["number"];
$pro = new DBOperation();
$rows = $pro->displayBrandAndCategory("products");
?>
<tr>
<td><b class="number"></b></td>
<td>
<select name="pname[]" class="form-control form-control-sm product_name">
<option value="0">Choose Product</option>
<?php
foreach ($rows as $row) {
?>
<option value="<?php echo $row['pro_id']; ?>"><?php echo $row["pro_name"]; ?></option>
<?php
}
?>
</select>
</td>
<td><input name="total_qty[]" type="text" class="form-control form-control-sm total_qty" readonly></td>
<td><input name="qty[]" type="text" class="form-control form-control-sm qty"></td>
<td><input name="hsn[]" type="text" class="form-control form-control-sm qty" readonly> </td>
<td><input name="price[]" type="text" class="form-control form-control-sm price" readonly></td>
<td>Rs.<span class="amt">0</span></td>
</tr>
<?php
exit();}
but hsn column is always showing 0,I tried doing this
document.write(ar[3]);
It correctly shows the HSN no. I don't know exactly what the statement below does,could anyone explain it to me?
tr.find(".hsn").val(ar[3]);

Related

Am trying to parse data from a dynamic html form with javascript or jquery to php and insert the data into the database

I have an html form with three input fields which I increment dynamically with javascript. I have to parse the data to PHP which I have done but I can't access the data and insert it into the database as this is an array data. I have tried but it's not working.
Here is my code:
html and Javascript
<body>
<div class="container">
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="othername[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="lastName[]" placeholder="Enter your Name" class="form-control name_last" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="otherName[]" placeholder="Enter your Name" class="form-control name_last" /></td><td><input type="text" name="lastName[]" placeholder="Enter your Name" class="form-control name_last" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
PHP
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
$numberx = count($_POST["othername"]);
$numbers = count($_POST["lastname"]);
if($number > 1 && $numbers > 1){
for(($i=0; $i<$number; $i++) && ($x=0; $x<$numberx; $x++) && ($w=0; $w<$numbers; $w++)){
if(trim($_POST["name"][$i] != '') && trim($_POST["othername"][$x] != '') &&
trim($_POST["lastname"][$w] != '')){
$namex = mysqli_real_escape_string($connect, $_POST["name"][$i]);
$othernamex = mysqli_real_escape_string($connect, $_POST["othername"][$x]);
$lastnamex = mysqli_real_escape_string($connect, $_POST["lastname"][$w]);
$check = "INSERT INTO bl_name (name, othername, lastname) VALUES ('$namex', '$othernamex', '$lastnamex')";
mysqli_query($connect, $check);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
I need help as I have been on this for two days now. Is there any way I can do this?
Simplify your input names, change them to:
user[][name]
user[][othername]
user[][lastname]
Run a simple foreach() loop on $_POST['user']:
foreach($_POST['user'] as $user){
$namex = mysqli_real_escape_string($connect, $user["name"]);
$othernamex = mysqli_real_escape_string($connect, $user["othername"]);
$lastnamex = mysqli_real_escape_string($connect, $user["lastname"]);
$check = "INSERT INTO bl_name (name, othername, lastname) VALUES ('{$namex}', '{$othernamex}', '{$lastnamex}')";
mysqli_query($connect, $check);
}
Keep in mind that form field names are case sensitive. You're also not testing if the mysqli_query() function returns successfully. You should probably do that. And yes, prepared statements are safer.

multiple dynamic class ids with select-option using change function in jquery

I'm trying to get class id for a dynamic table rows, the first row is working perfectly when it's selected, but the other rows are being fetched from java-scripts and are not working.
i.e. I can't get the class ids from the rows that is fetching from the java-script table row.
//this is jquery function am using....
$('#course_code').click(function(){
var course_id = $('#course_code').val();
if(course_id != '')
{
$.ajax({
url:"<?php echo base_url('Undergraduate_pg/fetch_course_code'); ?>",
method:"POST",
data:{course_id:course_id},
success:function(data){
$('#course_cod').val(data);
}
})
}
})
//this is the javascript table rows that is loading dynamically using click button..
function addrows(){
var row = ($('.detail tr').length-0)+1;
var tr = '<tr>' +
'<th>'+row+'</th>' +
'<td><select class="form-control course_code" id="course_code" name="course_code[]" required><option value="" selected="selected">Select Course Code</option><?php if (isset($pos)) { ?><?php foreach ($pos as $row) { ?>
echo "<option> <?php echo $row->course_code; ?></option>";<?php } } ?></select></td>' +
'<td><select class="form-control course_title" id="Title" name="course_title[]" required><option value="" selected="selected">Select Course Title</option><?php if (isset($pos)) { ?><?php foreach ($pos as $row) { ?>
echo "<option> <?php echo $row->course_title; ?></option>";<?php } } ?></select></td>' +
'<td><input type="number" class="form-control unit_elect" id="course_units" name="course_unit[]" value="" required></td>' +
'<td><select class="form-control course_status" id="course_status" name="course_status[]" required><option value="" selected="selected">Select Course Status</option><?php if (isset($pos)) { ?><?php foreach ($pos as $row) { ?>
echo "<option> <?php echo $row->course_status; ?></option>";<?php } } ?></select></td>' +
'<td colspan="3"><a class="btn btn-danger remove" >X</a></td>'+
'</tr>';
$('.detail').append(tr);
}
</script>
//i expect both static row and the dynamic row should be working once selected..
<!--this is the html code.. note, only this is working....-->
<tbody class="detail">
<td>1</td>
<td><select class="form-control course_code" id="course_code" name="course_code" required>
<option value="">--Select Course Code--</option>
<?php if (isset($pos)) { ?>
<?php foreach ($pos as $row) { ?>
echo "<option value="<?php echo $row->course_id; ?>"> <?php echo $row->course_code; ?></option>";
<?php } } ?>
</select>
<input type="text" class="form-control course_cod" id="course_cod" name="course_code[]" required>
</td>
I expect both static row and the dynamic row should be working once selected.

could not get input field value in jquery

I am creating an input field using foreach loop like this
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
$data is Array
(
[0] => Array
(
[asset_id] => abc-02
[asset_name] => Freezer
)
[1] => Array
(
[asset_id] => xyz-01
[asset_name] => Refrigerator
)
[2] => Array
(
[asset_id] => 300001
[asset_name] => Generator
)
)
and in javascript, I am trying to get the value using this code but it always alerts first value of the input.
<script type="text/javascript">
$(document).ready(function () {
var typename = $('#typename').val();
alert(typename);
});
</script>
i have to disable this input field when value is 'Generator'
Try:
$('[readonly].form-control').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>
.val() called once will always produce only one value; .val() docs:
Get the current value of the first element in the set of matched elements .
HTML id attribute is supposed to be unique, try this instead.
<?php
$count = 0;
foreach($data as $key=>$val) {
?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:
$('[id^="typename_"]').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
</td>
Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.
You should never use same id for several elements.
Update you code for debug, and you'll see that you have an array:
<script type="text/javascript">
$(document).ready(function () {
var typename = $('[name="model[]"]')
.toArray().map(e => e.value);
alert(JSON.stringify(typename));
});
</script>
You should update your php, to set different id for each element drawn in a cycle, i.e:
<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
So you'll be able to address eash input separately:
var typename = $('#typename_1').val();
Use class instead of duplicate id like this.
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery loop your class and get value using this instant..
$(document).ready(function () {
$( ".clsValue" ).each(function( index ) {
var typename = $(this).val();
alert(typename);
});
});
try this ,
this will call alert function for each input with form-control class
$(document).ready(function () {
$(".form-control").each(function(){
alert($(this).val());
})
});
Set class="typename" instead of id="typename":
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
You can get values like this:
<script type="text/javascript">
$(document).ready(function () {
var typename1 = $('.typename')[0].val();
var typename2 = $('.typename')[1].val();
alert(typename1);
});
</script>
there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.
Please let me know if you need sample code.
pure js approach;
replace id with class;
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
js
window.onload = alertTypeNames();
function alertTypeNames() {
document.getElementsByClassName('typename').map((inputTag) => {
alert(inputTag.value);
return true;
});
}
you fired with your id that's why it's fired only first element value.
this is how you can do that with your current code
$(document).ready(function () {
$('input[name="model[]"]').each(function(){
alert($(this).val());
});
});
However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.
<script type="text/javascript">
$(document).ready(function () {
$('.common-class').each(function() {
alert($(this).val());
});
});
</script>
<?php $incr_var = 1; ?>
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.
http://api.jquery.com/live/
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1 status">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery
$(document).on('change','.status',function(){
var $status = $(this).val();
if($status == 'not_working'){
$(this).closest('tr').find('.reason').removeAttr('disabled');
}
});
reason is class you have to give which input field you want to disable

How To Explain All data with parameter in javascript

Hi guys i have an issue for displaying all data where a column with name header_id having same data. but when it displayed, his result
just one row. actually of data with header_id='100002' having 4 rows.Thanks.
Model:
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->row_array();
}
Controller:
function getdtHeaderid() {
$header_id = $this->input->post('header_id');
$data=$this->M_selltransaction->getdtHeaderid($header_id);
echo json_encode($data);
}
View:
<div class="col-md-6">
<label for="header_id" class="col-md-4 control-label" style="text-align:left">Transaction No</label>
<label class="col-md-1 control-label">:</label>
<div class="col-md-6">
<div class="input-group input-group-unstyled">
<input type="text" class="header_id form-control" placeholder="Search" id="header_id" name="header_id"/>
<span class="input-group-addon"><i class="fa fa-search "></i></span>
</div>
</div>
</div>
<table>
<td><input type="text" width="10" class="detail_id form-control"
id="detail_id" name="detail_id[]" value="<?php $a =
set_value('detail_id[0]'); echo $a;?>" required ></td>
<td><input
type="text" width="10" class="item_code form-control" id="item_code"
name="item_code[]" value="<?php $a = set_value('item_code[0]'); echo
$a;?>" required ></td>
<td><input type="text" class="item_name
form-control" id="item_name" name="item_name[]" value=""
readonly></td>
</table>
<script type="text/javascript">
function getdHeaderid(header_id){
var header_id = header_id.val();
$.ajax({
type : "post",
data : {header_id:header_id},
url : "<?php echo base_url();?>index.php/transaction/selltransaction/getdtHeaderid",
dataType:"json",
cache :false,
success: function(data){
console.log(data);
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
}
});
}
$(document).ready(function() {
$('.header_id').on('keyup change', function() {
getdHeaderid($(this));
});
});
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->result_array();
}
Here is Your Correct model function you were using row_array() instead of result_array() thats why getting only one result
update
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
to
$(".detail_id").val(data[0].detail_id);
$(".item_code").val(data[0].item_code);
$(".item_name").val(data[0].item_name);

ajax code not taking the data from table to second row

hi guys i have an issue on ajax. where ajax can't work to take the data of second rows.
This's code in model
function getdtbarang($barcode = FALSE) {
if ($barcode === FALSE)
{
$query = $this->db1->get('tblmstbarang');
return $query->result_array();
}
$query = $this->db1->get_where('tblmstbarang', array('barcode' => $barcode));
return $query->row_array();
}
This's code in controller:
function getdatabarang() {
$barcode = $this->input->post('barcode');
$data=$this->Mbarang->getdtbarang($barcode);
echo json_encode($data);
}
This's ajax code in view. NB:some code has updated
<script type="text/javascript">
function getdatabrg(barcode){
$('#barcode_2').each(function() {
var barcode =$('#barcode_2').val();
$.ajax({
type : "post",
data : "barcode=" +barcode,
url : "<?php echo base_url();?>index.php/master/barang/Cbarang/getdatabarang",
dataType:"json",
success: function(data){
for(var i in data)
{
var obj= data[i];
$("#barang_nama_2").val(obj.barang_nama);
$("#harga_beli_2").val(obj.harga_beli);
}}
});
});
}
$(document).ready(function() {
$('#barcode_2').keyup(function() {
getdatabrg();
});
});
</script>
<td><input type="text" class="form-control" id="barcode" name="barcode[]" value="<?php echo set_value('barcode['.$i.']') ;?>" onKeyUp="getValues()" ></td>
<td><input type="text" class="form-control" id="barang_nama" name="barang_nama[]" value="<?php echo set_value('barang_nama['.$i.']') ;?>" onKeyUp="getValues()" disabled></td>
<td><input type="text" class="form-control" id="harga_beli" name="harga_beli[]" value="<?php echo set_value('harga_beli['.$i.']');?>" onKeyUp="getValues()" disabled></td>
<td><input type="text" class="form-control" id="barcode_2" name="barcode[]" value="<?php $a=set_value('barcode[0]') ; echo $a;?>"></td>
<td><input type="text" class="form-control" id="barang_nama_2" name="barang_nama[]" value="<?php $a=set_value('barang_nama[0]') ; echo $a;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="harga_beli_2" name="harga_beli[]" value="<?php $a=set_value('harga_beli[0]'); echo $a;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="barcode_3" name="barcode[]" value="<?php echo $detail->barcode;?>"></td>
<td><input type="text" class="form-control" id="barang_nama_3" name="barang_nama[]" value="<?php echo $detail->barang_nama;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="harga_beli_3" name="harga_beli[]" value="<?php echo $detail->harga_beli;?>" onKeyUp="getValues()" readonly></td>
i hope getting solve for this problem. many thanks for all your response.
Like Zerfiryn mentioned : "You cannot use the same id for html elements. jQuery will only fetch the first element"
solutions: you can use the same class multiple times on html elements. Call not the id in your ajax but the class form-control.
So, replace $("#barcode") with $(".form-control")
writing an answer cause I can't place comments -.-
You have not constructed model correctly your model is directly outputting the data which so you will end up with the output something like
[{barang_name:"value"},{harga_beli:"value"}][{barang_name:"value"},{harga_beli:"value"}][{barang_name:"value"},{harga_beli:"value"}]...
which is not correct JSON
your should output correct JSON your output should be
[ [{barang_name:"value"},{harga_beli:"value"}], [{barang_name:"value"},{harga_beli:"value"}],.. ]
which is array of arrays
The simplest way to achieve this is
1 ) get the desired data from your model
function your_model_function()
{
$result = execute_query($sql);
$rows = array();
if($result->num_rows)
{
while($row = $result->fetch_row())
$rows[] = $row;
}
return $rows;
}
2) use json_encode to encode your whole data array in json format
$data = $this->model->your_model_func();
echo json_encode($data);
3) Use the JSON in your success callback function
//writing success function of ajax
function(data)
{
for(var i in data)
{
var row = data[i];
// to acccesss the data of row ie json object you can use . operator
console.log(row.key)
// manipulate dom content.
}
}
NOTE: i have written a pseudo code only you cannot directly copy paste it to get result it's just to clear your mind.

Categories