I'm trying to alert fields. Here is my html
<table width="100%" id="example1" class="table table-bordered table-striped">
<tr>
<td> Nip </td>
<td> Nama Lengkap </td>
</tr>
<tr id='ke0'>
<td> <input class="form-control nipnya" type="text" name="nip[]" /> </td>
<td> <input class="form-control namanya" type="text" name="namalengkap[]" /> </td>
</tr>
<tr id='ke1'>
</tr>
</table>
<div>
<a id="add_row" class="btn btn-success pull-left">Tambah Baris Baru</a>
<a id="delete_row" class="pull-left btn btn-danger">Hapus Baris</a>
</div>
and i have this jquery
$(document).ready(function() {
$("#rmnya").change(function() {
$('#td11').html($("#rmnya").val());
});
var i = 1;
$("#add_row").click(function() {
$('#ke' + i).html('<td><input class="form-control nipnya" type="text" name="nip[]" /> </td>' +
'<td> <input class="form-control namanya" type="text" name="namalengkap[]" />' +
'</td>');
$('#example1').append('<tr id="ke' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#ke" + (i - 1)).html('');
i--;
}
});
});
As you can see from my script. There is only one Row <tr></tr>. I can alert it if it only one row. But when click Tambah Baris Baru there is another row showing up. I can't alert it. Here is my other javascript
$(".nipnya").change(function(){
$('.nipnya').each(function(i, obj) {
alert($('.nipnya').val());
});
});
So, can you tell me how to alert after onchange in every field that showing up dynamically.
Here is my fiddle https://jsfiddle.net/spc5884w/
Sorry for my bad english.
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.
General Syntax
$(staticParentElement).on('event','selector',callback_function)
Example
$('table').on('click', ".nipnya", function(){
alert($(this).val());
});
DEMO
Related
User can create tables and add records to it. When records added another values must be calculated. I tried to do that with jQuery but something is wrong and do not work. Maybe someone can help me and say how to do that.
Part from blade template (full template: https://pastebin.com/Mdq8fCnJ):
#foreach($tables as $table)
#foreach($table->fuelAccountingRecords as $record)
<tr>
<td id="name">{{ $record->name }}</td>
<td id="liters">{{ number_format($record->liters, 2, '.', '') }}</td>
<td id="show_kilograms"></td>
<td id="show_price"></td>
<td>
<input type="hidden" name="record_id"
value="{{ $record->id }}">
<button type="submit" class="btn btn-danger btn-sm"
name="deleteRecord">Trinti
</button>
</td>
</tr>
#endforeach
#endforeach
And jQuery code:
$(document).ready(function () {
var total_kilograms = $('#total_kilograms').val();
$('#show_kilograms').text(total_kilograms);
$('[data-table-id]').on('click', function () {
$('#table-' + $(this).data('table-id')).append(
'<tr class="child">' +
'<td><input type="text" class="form-control" name="name" autocomplete="off" required autofocus></td>' +
'<td><input type="text" class="form-control" name="liters" autocomplete="off" required></td>' +
'<td>-</td>' +
'<td>-</td>' +
'<td><button type="submit" class="btn btn-primary btn-sm" name="saveRecord">Išsaugoti</button></td>' +
'</tr>'
);
});
});
Another jQuery lines I am using to add rows to table where user can add records. I can not get a value from table and then ouput it or calculate. Help me to fix it.
Empty fields must be filled with values
For the jquery Guru's out there, I am trying. I am trying to add a jquery toggle between smarty template { foreach item list } my code works great just that it works on the first list item, it does not toggle when I click on the 2nd, 3rd etc items in the list. any suggestions?
jquery code
<script>
$(function(){
$("#itm_add").each(function(){
$(this).click(function(e){
e.preventDefault();
$("#itm_add_box").parent("tr").empty();
href=$(this).attr("href");
$(this).closest("tr").next("tr").empty().append('<td colspan="6"><div
id="itm_add_box" data-href="'+href+'">
<input type="text" id="itm_serial" class="input" placeholder="Serial
Number..." />
<input type="text" id="itm_qty" class="input"
placeholder="Quantity..." />
<button class="green" id="itm_submit">Submit</button></div><td>');
$("#itm_add_box button").click(function(e){
e.preventDefault();
href2=$(this).parent("#itm_add_box").attr("data-href");
serial=$(this).parent().find("#itm_serial").val();
qty=$(this).parent().find("#itm_qty").val();
href2=href2+"&item_serial="+serial+"&item_quantity="+qty;
window.location=href2;
});
});
});
});
</script>
Smarty template:
<table>
<tr>
<td class="olohead" align="center" width="80">ID</td>
<td class="olohead" align="center">Type</td>
<td class="olohead" align="center">Name</td>
<td class="olohead" align="center">No</td>
<td class="olohead" align="center">Features</td>
</tr>
{foreach from=$customer item=customer}
<td class="olotd4" nowrap align="center">{$customer.ID}</td>
<td class="olotd4" nowrap align="center">{$customer.TYPE}</td>
<td class="olotd4" nowrap > {$customer.NAME} </td>
<td class="olotd4" nowrap > {$customer.NO} </td>
<td class="olotd4" nowrap align="center">
<a id="itm_add">Add</a>
</td>
</tr>
{/foreach}
</table>
Again: This works, just that the toggle only works on the first listed item. Any suggestions?
The suggestion to remove the id from the loop and make it into a class was already made in the comments. With that in mind, I tried to clean up your js a bit:
$(function() {
$(".itm_add").click(function(e) {
e.preventDefault();
$(this).parent("tr").empty();
$(this).closest("tr").next("tr").empty().append(getTemplate($(this).attr("href")));
$(this).find("button").click(function(e) {
e.preventDefault();
var href = $(this).parent("#itm_add_box").attr("data-href");
var serial = $(this).parent().find("#itm_serial").val();
var qty = $(this).parent().find("#itm_qty").val();
href += "&item_serial=" + serial + "&item_quantity=" + qty;
window.location = href;
});
});
});
function getTemplate(href) {
return '<td colspan="6">'
+ '<div id="itm_add_box" data-href="' + href + '" >'
+ '<input type="text" id="itm_serial" class="input" placeholder="Serial Number..." /> '
+ '<input type="text" id="itm_qty" class="input" placeholder="Quantity..." /> '
+ '<button class="green" id="itm_submit">Submit</button>'+
+'</div>'
+ '<td>';
}
Note that this code is not tested, so there could be bugs in there...
What I changed:
Removed the .eachas it is not required. jQuery will automatically
add the event handler on all elements that the selector applies to.
Used $(this) inside the handler, to make the code only apply to the item that has triggered the event, in stead of all the matched items.
Moved the html to a separate function, just to keep things a bit more readable.
Made all the variables function scope in stead of global, by adding the varkeyword in front of their declaration.
Let me know if there are any bugs that I missed, or if this is anything that needs further explanation.
I am trying to add row with button click in table(Add Row). I am trying to add 2 fields dynamically.
1) slno
2) Date/ Time.
My problems :
1) Row is not getting added.
2) How to assign datepicker to "Date /Time" field, added dynamically.
Jsfiddle is http://jsfiddle.net/RXzs7/12/
Pl help.
html code :
<script>
$(document).ready(function() {
$('.date').each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0" });
});
});
</script>
<body>
<div id="lpage_container">
<div class="lform_container">
<h3>DETAILS OF LOCAL CONVEYANCE EXPENSES :</h3>
<form id="localexpenses" action="">
<table summary="local expense" id="localexpense_table" width="500" border="1">
<thead>
<tr>
<th width="1%" align="center"><strong>Sl.
No.</strong></th>
<th width="7%" align="center">
<strong>Date/Time</strong></th>
<th width="8%" align="center">
<strong>Remove</strong></th>
</tr>
</thead>
<tbody bgcolor="#CCCCCC">
<tr>
<td width="1%" align="center"><input type="text"
name="lsrno_00" id="srno_00" size="1" value="0"></td>
<td width="7%" align="center"><input type="text" class="date"
name="ldate_00" id="ldate_00" value="" size="8"></td>
<td> </td>
</tr>
</tbody>
</table>
<table summary="local buttons" width="500" border="1">
<tr>
<td align="right"><input type="button" value="Add Row"
id="add_ExpenseRowlocal">
</tr>
</table>
</form>
</div><!-- END subject_marks -->
<div class="clearfix"></div>
</div>
JS code :
$(function(){
// GET ID OF last row and increment it by one
var $lastChar =1, $newRow;
$get_lastID = function(){
var $id = $('#localexpense_table tr:last-child td:first-child input').attr("name");
$lastChar = parseInt($id.substr($id.length - 2), 10);
console.log('GET id: ' + $lastChar + ' | $id :'+$id);
$lastChar = $lastChar + 1;
$newRow = "<tr> \
<td><input type='text' name='lsrno_0"+$lastChar+"' value='0"+$lastChar+"' size='1'readonly /></td> \
<td><input type='text' class='date' name='ldate_0"+$lastChar+"' id='date_0"+$lastChar+"' size='8'/></td> \
<td><input type='button' value='Remove' class='del_ExpenseRowlocal' /></td> \
</tr>";
return $newRow;
};
// ***** -- START ADDING NEW ROWS
$('#add_ExpenseRowlocal').on("click", function(){
if($lastChar <= 9){
$get_lastID();
$('#localexpense_table tbody').append($newRow);
} else {
alert("Reached Maximum Rows!");
}
});
$(document).on("click", ".del_ExpenseRowlocal", function(){
$(this).closest('tr').remove();
$lastChar = $lastChar-2;
});
});
What jQuery version are you using? In your fiddle you have not added jQuery via the framework tab but under extenral resources you have two versions: 1.6.2 and 1.11.0. When I try and run it I get an error in the console that $().onis not a function. .on() came in jQuery 1.7 so if you are using 1.6.2 then you cannot use .on().
As for the date picker, when you run
$('.date').each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0"
});
in your document ready you add a date picker to all field with class date which currently exist. You must add the date picker to the new date fields after you have added the row to the DOM. Something like
$('.date', $('#localexpense_table tbody tr').filter(':last')).each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0" });
});
after your .append() call should work.
Working fiddle (needs some styles fixing for the added rows)
I have a table which rows are generated with a click event of an element. Now, this works perfectly, the problem is with the delete part. For example I have already added 5 rows, when I click the delete button (the delete button is created through jQuery too on the addRow() click event), all rows added through the jQuery function are being deleted and the form is submitting event though I have an e.preventDefault() method called.
JavaScript/jQuery code:
var counter = 2;
window.addRow = function addRow() {
var newRow = $('<tr><td><label>'+ counter +'</label></td><td><textarea name="txtActionStep' + counter + '" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td><td valign="top"><input type="text" name="txtOwner' + counter + '"/></td><td><button class="delete">delete</button></td></tr>');
counter++;
$('table.actionsteps-list').append( newRow );
}
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
function postForm() {
var form = document.getElementById('actionStepsForm');
document.getElementById('rowCount').value = counter-1;
form.submit();
}
HTML Code (the form itself):
<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="post">
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td>
<label>1</label>
</td>
<td>
<textarea name="txtActionStep1" style="width:300px; height: 50px; word-wrap:break-word;"></textarea>
</td>
<td valign="top">
<input type="text" name="txtOwner1" />
</td>
</tr>
</table>
<table width="510">
<tr>
<td align="right">Add Action</td>
</tr>
</table>
<input type="button" value="Create" onclick="postForm(); return false;" />
<input type="hidden" value="" id="rowCount" name="rowCount" />
</form>
Believe it or not, I've been stuck here for almost 3 days now. I can't find any fix online. I don't what's wrong.
put
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
into
$(function(){$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
)};
I have a table with different places, and implemented some simple buttons that allow you to filter the list. First filter is location (north, east, central, south, west) which is based on postcode. Another filter is on "impress". This shows you only the places that have have 4 or higher value in the column. Filters work great separately, but not together. The result that I am after is when I press "West" is shows me the places in "West, when I then click impress, I expect to see the places in west with a 4 or 5 score for impress.
JSFiddle here
$('.table td.postcode').each(function() {
var cellText = $(this).html();
var locationString = cellText.substring(0,2);
if (locationString.indexOf('W') > -1){
$(this).parent().addClass('west');
}
if (locationString.indexOf('C') > -1){
$(this).parent().addClass('central');
}
if (locationString.indexOf('E') > -1){
$(this).parent().addClass('east');
}
if (locationString.indexOf('S') > -1){
$(this).parent().addClass('south');
}
if (locationString.indexOf('N') > -1){
$(this).parent().addClass('north');
}
});
$("input[name='filterStatus'], select.filter").change(function () {
var classes = [];
$("input[name='filterStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.'+$(this).val());
}
});
if (classes == "") {
// if no filters selected, show all items
$("#StatusTable tbody tr").show();
} else {
// otherwise, hide everything...
$("#StatusTable tbody tr").hide();
// then show only the matching items
rows = $("#StatusTable tr").filter(classes.length ? classes.join(',') : '*');
if (rows.size() > 0) {
rows.show();
}
}
});
$("input[name='impressStatus']").change(function(){
var classes = [];
$("input[name='impressStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.'+$(this).val());
}
});
if(classes == ""){
$("#StatusTable tbody tr").show();
}
else{
$(".table td.impress").each(function(){
if($(this).data("impress") >= 4){
$(this).parent().show();
}
else{
$(this).parent().hide();
}
});
}
});
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--BUTTON FILTERS -->
<div class="btn-toolbar" role="toolbar" aria-label="...">
<div class="btn-group" style="" data-toggle="buttons">
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="north" autocomplete="off">North
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="east" autocomplete="off" class="radio">East
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="central" autocomplete="off" class="radio">Central
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="south"autocomplete="off" class="radio">South </label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="west" autocomplete="off" class="radio">West
</label>
</div><!-- button group -->
<label class="btn btn-primary outline">
<input type="checkbox" name="impressStatus" class="radio" aria-pressed="true" autocomplete="off">Impress her
</label>
</div><!-- btn toolbar-->
<!--TABLE -->
<table class="table" id="StatusTable">
<thead>
<tr>
<th data-sort="string" style="cursor:pointer">name</th>
<!-- <th>Description</th> -->
<th data-sort="string" style="cursor:pointer;">postcode</th>
<th data-sort="int" style="cursor:pointer;">price</th>
<th data-sort="int" style="cursor:pointer;">total</th>
<th data-sort="int" style="cursor:pointer;">impress</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<tr data-link="/places/1">
<td>Name of place 1</td>
<td class="postcode">NW1</td>
<td class="price" data-price='3'>3</td>
<td class="rating" data-rating='69'>69</td>
<td class="impress" data-impress='4'>4</td>
</tr>
<tr data-link="/places/2">
<td>Name of place 2</td>
<td class="postcode">E3</td>
<td class="price" data-price='4'>4</span></td>
<td class="rating" data-rating='89'>89</td>
<td class="impress" data-impress='5'>5</td>
</tr>
<tr data-link="/places/3">
<td>Name of place 3</td>
<td class="postcode">SW3</td>
<td class="price" data-price='2'>2</td>
<td class="rating" data-rating='51'>51</td>
<td class="impress" data-impress='3'>3</td>
</tr>
</tbody>
</table>
Code is probably not the most efficient, but it works :). Once I got this working, I want to add more filters.
(sorry for my bad english)
if these are the only filters you need, you can use two different type of filter:
hide via Javascript
hide via Css
if you use 2 types of filters the filters can work correctly without use a complex javascript code to manage a big number of different cases and combination:
I add a initial (on document load) control that check if a tr has the value impress cell >4, if has it add a new class: is_impress else add an other: no_impress.
$('.table td.impress').each(function(){
var _class = ($(this).data("impress") >= 4) ? "is_impress" : "no_impress";
$(this).parent().addClass(_class);
});
The code of filter by position is the same... but... I edit the filter by impress to add a class to table () when is active and take it off when isn't:
$("input[name='impressStatus']").change(function(){
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_impress")
: $("#StatusTable").addClass("active_impress");
});
if the table has the class active_impress a css rules override the inline code of dispaly to hide all the row that haven't an impress >4:
#StatusTable.active_impress tr.no_impress{
display:none !important;
}
This type of filter override any other display modification until the checkbox stay checked.
I edit your fiddle:
https://jsfiddle.net/Frogmouth/gkba343L/1/
USE CSS to more filter
First change on load check, add price:
$('.table tbody tr').each(function(){
var _class = "";
_class += ($(this).find(".price").data("price") >= 2) ? "is_price " : "no_price ";
_class += ($(this).find(".impress").data("impress") >= 4) ? "is_impress " : "no_impress ";
console.log(_class);
$(this).addClass(_class);
});
Add an other handler to new filter:
$("input[name='priceStatus']").change(function(){
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_price")
: $("#StatusTable").addClass("active_price");
});
add new selector to the css rule:
#StatusTable.active_impress tr.no_impress,
#StatusTable.active_price tr.no_price{
display:none !important;
}
This is the result:
https://jsfiddle.net/Frogmouth/gkba343L/3/
Optimize code to add more filter:
HTML filter button:
<label class="btn btn-primary outline">
<input type="checkbox" name="impress" class="cssFilter radio" aria-pressed="true" autocomplete="off">Impress her
</label>
use cssFilter to indicate that is a css filter button and use name attribute to define the name of the filter, than use this namespace into the css class:
.active_{name} .no_{name} .is_{name}
And use a generic handler:
$("input.cssFilter").change(function(){
var _name = $(this).attr("name");
console.log(_name);
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_"+_name)
: $("#StatusTable").addClass("active_"+_name);
});
With this you can manage all the filter with an unique handler, remember to add the filter to onload check and the new selector for each new filter.
Fiddle:
https://jsfiddle.net/Frogmouth/gkba343L/4/