JQuery with .live & .remove I can't figure this out - javascript

Here is a jsfiddle that is working except for the function I'm trying to figure out.
I have this code that .appends a .table to a form on a value change in the .qty field. I'm trying to figure out 2 things.
The first is that only ONE extra line may be available at any time.
The second would be to remove that one extra line when the #extraDiscount has .focusin.
Here's the JQuery.
var TheOrderLine = ('<table class="orderLine formFont" width="400" hspace="0" vspace="0"><tr><td width="75" valign="top">Name:<input class="ProductName" type="text" size="6"></td><td width="75" valign="top">WholeSale:<input class="WholeSalePrice" type="text" size="6"></td><td width="75" valign="top">QTY:<input class="qty addLine" type="text" size="6"></td><td width="75" valign="top">L/Total:<input class="lineTotal" type="text" size="6"><br></td><td width="100" valign="top"><div id="delButton">DEL</div></td></table>');
$(document).ready(function(e) {
//This adds the Line Totals
});function updateTotal() {
var totalA = 0;
$('.lineTotal').each(function() { totalA += parseFloat($(this).val()) || 0; });
$('#productTotals').val(totalA.toFixed(2));
}
//This is the autocomplete and is working fine
$(function() {
$('.ProductName').val("");
$('.WholeSalePrice').val("");
$(document).ready(function(e) {
$('.ProductName').live({
focusin: function() {
$(this).autocomplete({
source: "PRODUCT.SEARCH.QUERY.php",
minLength: 2,
autoFocus: true,
select: function(event, ui) {
var $tr = $(this).closest('tr');
$tr.find('.ProductName').val(ui.item.ProductName);
$tr.find('.WholeSalePrice').val(ui.item.WholeSalePrice);
}
})
}
});
});
});
// Used a CSS button for the Delete line
$("#orderFormDiv_Lines").delegate("#delButton", "click", function () {
$(this).closest('.orderLine').remove();
updateTotal(); /* this recalculates the total after an item is deleted */
});
// Removes all lines
$("#removeAll").click(function () {
$('.orderLine').remove();
$('#productTotals input[type="text"]').val('');
updateTotal();
});
$(document).ready(function(e) {
$('.qty').live({
change: function() {
/* This add the numbers for lineTotal field */
var qty = $(this).val();
var $tr = $(this).closest('tr');
var WholeSalePrice = $('.WholeSalePrice:eq(0)', $tr).val();
var lineTotal = parseFloat(qty * WholeSalePrice) || 0;
$('.lineTotal:eq(0)', $tr).val(lineTotal.toFixed(2));;
updateTotal();
// this is the line that I need to add the if function on but I can't figure out how to find the extra empty table rows that may exist and also not let
$('#orderFormDiv_Lines').append(TheOrderLine);
// I'm thinking something along this line here but I can't grasp the .live concept for grabbing the empty .orderlines.
/*
if ('.orderLine':empty) && > 1; {
$('.orderLine').remove();
} else {
$('#orderFormDiv_Lines').append(TheOrderLine);
}
*/ }
})
// Added this in case the Delete All button is used.
$('#addLine').click(function(){
$('#orderFormDiv_Lines').append(TheOrderLine);
});
});
Here's HTML form....
<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<hr>
<form action="<?php echo $PHP_SELF;?>" method="post">
<div id="orderFormContent">
<div id="orderFormDiv_Lines">
<table class="orderLine formFont" width="400" hspace="0" vspace="0">
<tr>
<td width="75" valign="top">
Name:<input class="ProductName" type="text" size="6"></td>
<td width="75" valign="top">
WholeSale:<input class="WholeSalePrice" type="text" size="6"></td>
<td width="75" valign="top">
QTY:<input class="qty addLine" type="text" size="6"></td>
<td width="75" valign="top">
L/Total:<input class="lineTotal" type="text" size="6"><br></td>
<td width="100" valign="top">
<div id="delButton">DEL</div>
</td>
</table>
</div>
<div id="orderFormDiv_BottomRight"><br>
<table width="100%" border="1">
<tr>
<td>#extraDiscount</td>
<td><input id="extraDiscount" type="text" size="10"></td>
</tr>
<tr>
<td>#totalDiscounts</td>
<td><input id="totalDiscounts" type="text" size="10" disabled></td>
</tr>
<tr>
<td>#productTotals</td>
<td><input id="productTotals" type="text" size="10" disabled></td>
</tr>
</table></div>
<br>
<p class="clear"/>
</div>
<div id="removeAll">Delete All</div><br><br>
<div id="addLine">Add Line</div>
<hr>
<br></div>
</form><hr>
</body>
</html>
Any help would be AWESOME!!! Thanks!

to limit appending only 1 line for .orderLine change your click function to
$('#addLine').bind('click', function(){
if($('.orderLine').length == 0)
$('#orderFormDiv_Lines').append(TheOrderLine);
});
and to remove the line when discount is focused :
$('#extraDiscount').bind('focus', function(){
$('#orderFormDiv_Lines table').each(function(){
var hasInput = false;
$(this).find('input').each(function(){
if($(this).val() != '')
hasInput = true;
});
if(!hasInput) $(this).remove();
});
});

Related

JQuery can't get input value from dynamically created field

Receiving value from static field when keyup based on input field class(.inputclass) method, but once add field dynamically its not get the value.
Below the sample code, Please help.
$(function(){
$(document).ready(function(){
$(".inputclass").keyup(function() {
alert($(this).val());
});
});
});
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
<tr>
<td>Field 1</td>
<td><input type="text" class="inputclass" /></td>
</tr>
<script>
var counter =1;
$(function(){
$('#addNew').click(function(){
counter += 1;
$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
});
});
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form>
This is because when you assigned the event handler, it only assigned to the existing elements at the time.
Delegate to the document:
$(document).on('keyup', '.inputclass', function(){
alert($(this).val())
});
When you delegate to a parent or the document, you are using the event that bubbles up and so it doesn't matter if there are dynamic elements.
$(function(){
$(document).ready(function(){
$(document).on('keyup', '.inputclass', function(){
alert($(this).val());
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
<tr>
<td>Field 1</td>
<td><input type="text" class="inputclass" /></td>
</tr>
<script>
var counter =1;
$(function(){
$('#addNew').click(function(){
counter += 1;
$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
});
});
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form>

On textbox change change label value to HTML (array)

I have a array of textbox and labels which are toggled in a html table, say the label vl be visible on first and then on the row click the text box are visible , but the problem is on that row if i change the text box value the label value should also change but hear in my case am not able to do it.
JS Fiddle demo
HTML:
<table border="1" cellspacing="1" width="100%" id="table1">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
</tr>
<tr>
<td>
<label>data1</label>
<input type="text" value="data1" />
</td>
<td>
<label>data2</label>
<input type="text" value="data2" />
</td>
<td>
<label>data3</label>
<input type="text" value="data3"/>
</td>
<td>
<label>data4</label>
<input type="text" value="data4"/>
</td>
<td>
<label>data5</label>
<input type="text" value="data5"/>
</td>
</tr>
<tr>
<td>
<label>data6</label>
<input type="text" value="data6" />
</td>
<td>
<label>data7</label>
<input type="text" value="data7"/>
</td>
<td>
<label>data8</label>
<input type="text" value="data8" />
</td>
<td>
<label>data9</label>
<input type="text" value="data9" />
</td>
<td>
<label>data10</label>
<input type="text" value="data10" />
</td>
</tr>
</table>
<input id="printdata" type="button" value="printdata" />
<div class="showresult">1: <span></span></div>
<div class="showresult">2: <span></span></div>
<div class="showresult">3: <span></span></div>
<div class="showresult">4: <span></span></div>
<div class="showresult">5: <span></span></div>
JS:
$('#table1 input').hide();
$('#printdata').fadeTo(0, 0);
// This shows or hides the button deppending on the inputs
$('#table1 tr').on('change keyup click', function() {
var text = '';
$('input', this).each(function(){
text += $(this).val();
});
if (text !='')
{
$('#printdata').fadeTo(0, 100);
}
else
{
$('#printdata').fadeTo(0, 0);
}
});
$('#table1 tr').on('click', function (e) {
if ($( e.target ).is("input") || $( e.target ).is("th") ) {
return;
} else if ($(this).hasClass('selected')) {
$(this).toggleClass('selected');
$('input', this).toggle();
$('label', this).toggle();
} else {
$('tr.selected input').hide();
$('tr.selected label').toggle();
$('tr.selected').toggleClass('selected');
$(this).toggleClass('selected');
$('label', this).toggle();
$('input', this).toggle();
}
});
$('#printdata').click(function () {
$('.showresult').each(function (index) {
$('span', this).html('');
$('span', this).html($('#table1 .selected input').eq(index).val());
});
});
try to add this code:-
$('#table1 tr').on('change','[type="text"]', function(e) {
$(this).prev('label').text($(this).val());
});
Demo
Well, that's what you need to add to make your code working:
$('#table1 input').each(function(idx, input) {
var jqInput = $(input);
var label = jqInput.parent().find("label")
jqInput.change(function() {
label.text(jqInput.val())
})
})
However, this is a slippery road.
You're trying to maintain some state, display it in different views...
You will always have some sort of data synchronization bug with this approach.
You need to use some sort of MVC to make your life easier and code more stable.

jQuery math function not working for dynamically added new table row

I need to use jQuery to perform basic math function as well as adding additional rows to a table dynamically. So far I have this piece of code:
<script type="text/javascript">
$(document).ready(function() {
$(".sub").focusout(
function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
});
$("#add").click(function() {
$('#lineItemTable tbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
return false;
});
});
</script>
And my html looks like this:
<body>
<a id="add">add Line</a>
<table id="lineItemTable">
<tr>
<th>Gross</th>
<th>Tare</th>
<th style="padding-right: 10px">Net Weight</th>
</tr>
<tr class="row_to_clone">
<td>
<input type='number' step="any" name='gross' id='gross' class='sub' />
</td>
<td>
<input type='number' step="any" name='tare' id='tare' class='sub' />
</td>
<td id="calculated">
<p id='net' class='sub1'></p>
</td>
</tr>
</table>
</body>
Now, before adding another row to the table, the basic math function works, but the math function does not works for the new added row after I click the add Line button. What am I missing here?
You are violating html rules basically by cloning elements with id. According to html rules the ids in the DOM should be unique. So what I suggest is, change id to class and make use of $(this) to fetch correct elements as below:
DEMO
Your updated html would be as follows:
<a id="add">add Line</a>
<table id="lineItemTable">
<tr>
<th>Gross</th>
<th>Tare</th>
<th style="padding-right: 10px">Net Weight</th>
</tr>
<tr class="row_to_clone">
<td>
<input type='number' step="any" name='gross' class='gross sub' />
<!-- Remove id and add it as class-->
</td>
<td>
<input type='number' step="any" name='tare' class='net sub' />
<!-- Remove id and add it as class-->
</td>
<td>
<p class='net'></p>
<!-- Remove id and add it as class-->
</td>
</tr>
</table>
and JS would be:
$(document).ready(function() {
$(".sub").focusout( //get it using class
function() {
var parent=$(this).closest('.row_to_clone'); //find its parent first
parent.find(".net").html(''); //then get all those elements with necessary class belonging to its parent
var gross = parent.find('.gross').val();
var tare = parent.find('.net').val();
var net = (gross - tare);
parent.find(".net").html(Math.round(net * 1000) / 1000);
});
$("#add").click(function() {
var newRow=$('#lineItemTable tbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
newRow.find('input').val(''); //Comment this if you you want to persist the value
newRow.find('p').text('');//Comment this if you you want to persist the value
return false;
});
});
You have to write a function and have to call it again after inserting the html. The new html is not in the DOM when you call the site:
<script type="text/javascript">
function do_math() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
});
$(document).ready(function() {
$(".sub").focusout(
do_math();
);
$("#add").click(function() {
$('#lineItemTabletbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
do_math();
return false;
});
});
</script>

How to hide a table row which have TD containing certain values

I am working on a SharePoint web site , and I need using CSS (Preferred) or JavaScript, to hide a table row that have two main TDs:-
TD with a text named Item Number.
TD with an input titled Item number.
Here is how the mark-up is constructed:-
Can anyone advice on this please?
i tried the following script , but did not hide the Item Number or the customer initial , baring in mind that all the TR are inside a table which have .ms-formtable class:-
<script>
$(function() {
$('.ms-formtable tr').each(function() {
var frstVal = $(this).find('td').eq(0).text();
if (frstVal.match(/Item Number|customer Initials/i)) {
$(frstVal).remove()
}
});
});
</script>
here is the related markup :-
<table width="100%" class="ms-formtable" style="margin-top: 8px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="113" class="ms-formlabel" nowrap="true" valign="top">
<h3 class="ms-standardheader">
<nobr>Item Number</nobr>
</h3></td>
<td width="350" class="ms-formbody" valign="top">
<span dir="none"><input title="Item Number" class="ms-long ms-spellcheck-true" id="_x0049_D1_806a702b-1716-47f5-a93c-16067f502daf_$TextField" type="text" maxlength="255" value=""><br></span>
<span class="ms-metadata">Do not customize at the list level</span>
</td></tr>
EDIT
now i tried this script :-
<script>
$(function () {
$('.ms-formtable table').each(function () {
$(this).find('tr').each(function () {
$(this).find('td').text() = 'Item Number';
$(this).remove();
}
});
});
</script>
but did not hide the Item Number field...
Hope this is what you are looking for .
$('tr').each(function(){
var count=0;
$(this).find('td').each(function(){
if($(this).text()=='Item Number'){count=count+1;}
if($(this).find('input[title="Item Number"]')){count=count+1;}
});
if(count==2){$(this).hide();}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
</head>
<body>
<table width="100%" class="ms-formtable" style="margin-top: 8px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="113" class="ms-formlabel" nowrap="true" valign="top">
<h3 class="ms-standardheader">
<nobr>Item Number</nobr>
</h3></td>
<td width="350" class="ms-formbody" valign="top">
<span dir="none"><input title="Item Number" class="ms-long ms-spellcheck-true" id="_x0049_D1_806a702b-1716-47f5-a93c-16067f502daf_$TextField" type="text" maxlength="255" value=""><br></span>
<span class="ms-metadata">Do not customize at the list level</span>
</td>
</tr>
</table>
</body>
</html>
Code snippet output will be an empty page,as in example table is having only one row which has 2 td's as mentioned,so am hiding the row,based on the creteria.
Your script and HTML has a few issues.
In your html there is no text inside any of the td's and you have the following query :
var frstVal = $(this).find('td').eq(0).text(); // how is this query going to retrive anything at all ?
The issue with your script is you're iterating over all the tr's but you're caching only the text() of the first td inside every tr, so change the script to the following :
$(function() {
$('.ms-formtable tr').each(function() {
$(this).find('td').each(function(){
var str_text = $(this).text();
if (str_text.match(/Item Number|customer Initials/i)) {
$(this).text(' ');
}
});
});
});
Fiddle here
Edit
You're selecting the wrong element, the below query is wrong :
var str_text = $(this).text();
$(this) is pointing to tr , you need to go inside tr and find nobr and then perform your action.
$('.ms-formtable table').each(function () {
$(this).find('tr').each(function () {
var str_text = $(this).find('td nobr').text();
// console.log(str_text);
if (str_text.match(/Item Number/i)) {
$(this).find('input').remove(); // add this to remove input
$(this).text(' ');
}
}
});
});

Validation on dynamically added rows

I'm cloning a row and I want to check in the database if the code exists. This all works fine on the first row but not on the cloned rows. I have an idea that I have to make the id of the field unique, I have tried to add the the code that checks if the code exist to the add button event but it doesn't work. Can someone please tell me how to merge the two script so it works on the cloned rows.
Code:
HTML
<table>
<tr id="show_codes">
<td colspan="2" class="text-fields" align="center" valign="middle">
<div class="codeForm">
<table class="codeForm" align="left" width="500px" cellpadding="0" style="padding-left: 20px;" cellspacing="0">
<tr>
<td height="15px">Codes that exist is 0011, 1234</td>
</tr>
<tr class="code_row">
<td class="details-border1" height="40px" valign="middle" bgcolor="#f3f3f3" align="center">
<input id="code" value="" class="text ui-widget-content ui-corner-all" type="text" name="code[]" />
<div id="status"></div>
</td>
<td class="details-border2" bgcolor="#f3f3f3" align="center">
<input value="" class="text ui-widget-content ui-corner-all" type="text" name="value[]" />
</td>
<td class="borders-right-bottom" bgcolor="#f3f3f3" align="center">
<input type="button" class="btnDeleteCode" value="Delete" />
</td>
</tr>
</table>
</div>
<table width="500px" align="left">
<tr>
<td align="right"><span style="cursor: pointer; color: #007FC6; font-weight: bold;" id="btnAddCode" value="add more">Add another code</span>
</td>
</tr>
</table>
</td>
</tr>
JQUERY
var dom = {};
dom.query = jQuery.noConflict(true);
dom.query(document).ready(function () {
var clonedRow = dom.query('.code_row').clone().html();
var appendRow = '<tr class = "code_row">' + clonedRow + '</tr>';
var counter = 0;
dom.query('#btnAddCode').click(function () {
dom.query('.codeForm tr:last').after(appendRow);
counter++;
$('.codeForm tr:last input[type="text"]').attr('id', 'code[' + counter + ']');
$('.codeForm tr:last').find('input').val('');
});
dom.query('.btnDeleteCode').live('click', function () {
var rowLength = dom.query('.code_row').length;
if (rowLength > 1) {
deleteRow(this);
} else {
dom.query('.codeForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode) {
dom.query(currentNode).parent().parent().remove();
}
});
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
pic2 = new Image(16, 16);
pic2.src = "tick.gif";
dom.query(document).ready(function () {
dom.query("#code").change(function () {
var usr = dom.query("#code").val();
if (usr.length >= 4) {
dom.query("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
alert(usr);
dom.query.ajax({
type: "POST",
url: "setup_practice_preference_check_code.php",
data: "username=" + usr,
success: function (msg) {
dom.query("#status").ajaxComplete(function (event, request, settings) {
if (msg == 'OK') {
dom.query("#code").removeClass('object_error'); // if necessary
dom.query("#code").addClass("object_ok");
dom.query(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
alert('msg');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
dom.query(this).html(msg);
}
});
}
});
} else {
dom.query("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
}
});
});
Fiddle
Thanks

Categories

Resources