friends.I am stuck with some javascript function to read keyup function to a text field with id as array(qty[]).Please help me
<table id="dynamic">
<tr>
<td>
<label for="textfield">product :</label>
</td><td> <select name="product" id="product[0]">
<?php
$result=mysql_query("SELECT * FROM `product`");
while($row=mysql_fetch_array($result)){
?>
<option value=" <?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php }?>
</select>
<label for="qty">Qty :</label>
<input type="text" name="qty" id="qty[0]"/>
<label for="textfield">Price :</label>
<input type="text" name="price" id="price[0]" readonly/>
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
</td> <div id="loader"></div></tr>
</table>
javascript
appending dynamic fields
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
$('#dynamic').append('<tr id="row'+i+'"><td><label for="textfield">product :</label></td><td><select name="product" id="product['+i+']"><?php $result=mysql_query("SELECT * FROM `product`");while($row=mysql_fetch_array($result)){?><option value=" <?php echo $row['id']; ?>"><?php echo $row['name']; ?></option><?php }?></select><label for="qty">Qty :</label><input type="text" name="qty" id="qty['+i+']"/><label for="textfield">Price :</label><input type="text" name="price" id="price['+i+']" readonly/></td><td><button type="button" name="remove" class="btn btn-danger btn_remove" id="'+i+'">X</button></td></td><div id="loader"></div></tr>');
i++;
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
here i tried to access the qty[0] variable.but its not working.When its not array working fine.
<script type="text/javascript">
$(document).ready(function()
{
var i=1;
$("#qty[0]").keyup(function()
{
var qty=$("#qty[0]").val();
var pdt=$("#product[0]").val();
i++;
$.ajax({
type:"POST",
url:"price_ajax.php",
data : { qty : qty, pdt : pdt },
beforeSend: function () {
$('#loader').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success:function(data)
{
$("#price[0]").val(data);
$("#loader").html("");
}
});
});
});
Change
$('#add').click(function() {
$('#dynamic').append('... id="product['+i+']">...');
i++;
});
To
$('#add').click(function() {
$('#dynamic').append('... id="product_'+i+'">...');
i++;
});
id="product[0]" will become id="product_0"
Apply same method to other dynamic elements and make relevant modifications in your jQuery selector.
Everything will work fine.
Also, I would like to add here that, please break up your append call. Javascript, HTML and PHP, everything is happening in one single line. Which is very confusing. Prepare an HTML in javascript variable. Once done, append it.
Update your code as mentioned below:
HTML Changes:
Add class class='qty' in input box in id="qty[0]" field
$('#add').click(function(){
$('#dynamic').append('<tr id="row'+i+'"><td><label for="textfield">product :</label></td><td><select name="product" id="product['+i+']"><?php $result=mysql_query("SELECT * FROM `product`");while($row=mysql_fetch_array($result)){?><option value=" <?php echo $row['id']; ?>"><?php echo $row['name']; ?></option><?php }?></select><label for="qty">Qty :</label><input type="text" name="qty" class="qty" id="qty['+i+']"/><label for="textfield">Price :</label><input type="text" name="price" id="price['+i+']" readonly/></td><td><button type="button" name="remove" class="btn btn-danger btn_remove" id="'+i+'">X</button></td></td><div id="loader"></div></tr>');
i++;
$( ".qty" ).each(function( index ) {
$(this).keyup(function() {
// your code here
});
});
});
Jquery Changes:
$( ".qty" ).each(function( index ) {
$(this).keyup(function() {
// your code here
});
});
Related
Inside a table, I've created multiple forms using a loop based on data inside database.
Now I am not getting a way to implement a logic by which I wanted to identify of which form submit button is pressed so that I can update data accordingly in database.
What I did is putted an ID of that particular row as submit button id, but I am not getting how to put the same ID in javascript file (separate file) to fetch the field details, can someone help?
<?php
foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<form id="<?php echo $filtered_items->id; ?>" method="POST">
<td><input type="text" class="form-group" id="user_account_name" value="<?php echo $filtered_items->user_account_name; ?>"><?php echo $filtered_items->user_account_name; ?></td>
<td><input type="text" class="form-group" id="user_project_name" value="<?php echo $filtered_items->user_project_name; ?>"><?php echo $filtered_items->user_project_name; ?></td>
<td><input type="text" class="form-group" id="start_date" value="<?php echo $filtered_items->start_date; ?>"><?php echo $filtered_items->start_date; ?></td>
<td><input type="text" class="form-group" id="due_date" value="<?php echo $filtered_items->due_date; ?>"><?php echo $filtered_items->due_date; ?></td>
<td><input type="submit" id="<?php echo $filtered_items->id; ?>" class="btn-primary btn-sm">Submit</button></td>
</tr></form>
<?php } ?>
UPDATE:
jQuery code I am using:
$(document).ready(function() {
$('.row-submit').on('click', e => {
alert('test');
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
type: "POST",
url: ajaxurl,
action: "send_modification_training_data",
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
});
I'm presuming that you're using AJAX to send the form data, otherwise you wouldn't need to know which form was submit as the browser will collate the data for you.
To retrieve the data related to the clicked submit button you need to correct your HTML. Firstly, you need to remove all id attributes from the HTML you generate in the PHP loop as it will create duplicate values which is invalid, they must be unique. Change them to classes instead. Secondly, you cannot place a form element as a child of a tr.
In fact, given that you're using a table here you cannot use a form at all, as there's no way to make the HTML valid. You need to collate the input data on each row. To do this you can use closest() to find the tr related to the button and retrieve the input values using find(). Something like this:
<?php foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<td>
<input type="text" class="form-group user_account_name" value="<?php echo $filtered_items->user_account_name; ?>">
<?php echo $filtered_items->user_account_name; ?>
</td>
<td>
<input type="text" class="form-group user_project_name" value="<?php echo $filtered_items->user_project_name; ?>">
<?php echo $filtered_items->user_project_name; ?>
</td>
<td>
<input type="text" class="form-group start_date" value="<?php echo $filtered_items->start_date; ?>">
<?php echo $filtered_items->start_date; ?>
</td>
<td>
<input type="text" class="form-group due_date" value="<?php echo $filtered_items->due_date; ?>">
<?php echo $filtered_items->due_date; ?>
</td>
<td>
<button type="button" class="btn-primary btn-sm row-submit">Submit</button>
</td>
</tr>
<?php } ?>
$('.row-submit').on('click', e => {
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
url: 'your-handler.php',
type: 'POST',
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.
Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>
hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>
add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>
I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced
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
Below is my HTML code. I can only get value returned by ajax request in that id="sss" field.
My Problems are listed below with images:-
<form id="dynamic2" action="<?= site_url('product/save') ?>" method="post">
<table class="table">
<tbody id="itemlist2" class="detailss">
<tr>
<td>
<select id="select-product" class="form-control" data-cell="B1" 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" id="sss" data-cell="C1" name="price[]" class="form-control" value="">
</td>
<td>
<input type="text" data-cell="D1" name="quantity[]" class="form-control">
</td>
<td>
<input type="text" data-cell="E1" name="discount[]" class="form-control">
</td>
<td>
<input type="text" data-cell="F1" name="total[]"
disabled="true" data-formula="(D1*C1)-(D1*C1*E1/100)"
class="form-control">
</td>
</tr>
</tbody>
<input type="submit" value="Submit" class="btn btn-primary">
</table>
</form>
I am not getting value returned by ajax request in dynamically created input fields.
Here is my dynamically created input field jS code.
<script type="text/javascript">
$(function() {
$form = $('#dynamic2').calx();
$('.addrowss').click(function() {
$itemlist = $('#itemlist2');
$counter = 5;
var i = ++$counter;
var tr = '<tr>' +
'<td><select id="select-product" class="form-control" data-cell="B' + i + '" name="product_name[]"><option value=""></option><?php
foreach ($product as $key ):
?><option value="<?php echo $key['product_name'] ?>"><?php echo $key['product_name'] ?></option><?php endforeach; ?></select></td>'+
'<td><input id="sss" type="text" data-cell="C' + i + '" name="price[]" class="form-control" value=""></td>' +
'<td><input type="text" data-cell="D' + i + '" name="quantity[]" class="form-control"></td>' +
'<td><input type="text" data-cell="E' + i + '" name="discount[]" class="form-control"></td>' +
'<td><input type="text" class="form-control" data-cell="F' + i + '" name="total[]" data-formula="(D' + i + '*C' + i + ')-(D' + i + '*C' + i + '*E' + i + '/100)"></td>' +
'<td>Remove</td>' +
'</tr>';
$('.detailss').append(tr);
$form.calx('update');
$form.calx('getCell', 'G1').setFormula('SUM(F1:F' + i + ')');
});
$('body').delegate('.remove', 'click', function() {
var tr = $(this).parent().parent();
var c = confirm("Do you want to remove this ?");
if (c) {
tr.remove();
}
});
});
</script>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#select-product").change(function() {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {
"id": id
},
cache: false,
success: function(data) {
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
</script>
Product.php Controller
public function view_data()
{
if(isset($_GET['id'])){
$this->load->model('Product_model');
$id = $_GET['id'];
$param = $this->Product_model->get_ajax_value($id);
foreach($param as $a)
echo $a.",";
exit;
}
}
I am not exactly sure why it isn't returning all the correct data. But here might be a step to help you debug you problem.
Add a console.log(data); To see what is being returned from the ajax call. Use the console of your browser to see this.
Change your code to:
<script type="text/javascript">
$(document).ready(function () {
$("#select-product").change(function () {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {"id":id},
cache: false,
success: function(data){
console.log(data); //this will show what is returned.
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
I understand this isn't the complete answer to your code. But it might put you on the right track to seeing what the server is returning to your client side code.
Updating what has worked and the current issue:
I have 1 clear button beside each field. Each clear button works. The problem is after clearing both fields, when selecting another file from the dropdown, it only populates the text field with the file name and does not display the contents in the second textarea until refreshing the page.
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div><font color=#2F6054>Below is the list of your saved codes. To view or delete your codes, select it from the list.</font></font></div><p>
<select size="1" name="CodeList" id="CodeList">
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo "<option>" . $file . "</option>";
}
}
?>
</select><p>
<font color=#2F6054><font size=4>Enter Codes Here</font></font>
<form method="post" action="/evo/avsaveprocess.php">
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<table width="100%">
<tr>
<td>Description:</td>
<td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
<td><button type="reset" class="clear-tn" value="Clear"></button></td>
</tr>
<tr>
<td valign="top">Code:</td>
<td>
<textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Save" />
function code:
<script>
$(function(){
$('.clear-btn').on('click',function(e){
e.preventDefault();
$(this).closest('tr').find('input[type="text"],textarea').val('');
});
});
</script>
Edited to show current working code
Editing to show on change script at the bottom of my form for the dropdown
<script>
$(document).ready(function(){
// apply a change event
$('#CodeList').change(function() {
// update input box with the currently selected value
$('#CodeName').val($(this).val());
$.get( '<? echo $directory ?>' + '/' + $('#CodeName').val(), function( data ) {
$( "#CodeValue" ).val( data );
});
});
});
</script>
You can try the below link, it works without javascript or jquery. Just simple HTML
<form>
<input type="reset" />
<input type="submit" />
<input type="text" />
<textarea></textarea>
</form>
Here is the demo
Change type attribute "button" to "reset".
<button type="reset" class="clear-btn">Clear</button>
Try below working fiddle as per your requirement.
http://fiddle.jshell.net/t7gkr8rk/1/