jQuery Adding and Removing Rows Trouble - javascript

I'm trying to create a new use for an already implemented tool we use here at work, but I'm very sure I'm doing something wrong.
I can't figure out how to make it delete a row. And even more, I can figure out how to clone everything within .pt-entry, and have it replicated inside of the incremental .pt-entry...but without the user filled in info.
Hopefully this makes sense.
You can check out my Pen here, but here's the code breakdown for the rest of yous:
HTML:
<table class="manage-pt" id="0">
<tr class="pt-entry">
<td class="pt-toggle-group">
<input type="button" class="pt-button togPTbutton" value="?" />
<input type="button" class="pt-button addPTbutton" value="+" />
<input type="button" class="pt-button delPTbutton" value="-" />
</td>
<td class="pt-values">
<div>
<input type="text" class="vendor" placeholder="Vendor Name" />
</div>
<div>
<textarea class="ptCode" name="ptCode" placeholder="Pixel Tag Code" ></textarea>
</div>
<div class="page-select">
<select>
<option value="AllPages">All Pages</option>
<option value="HomePage">HomePage</option>
<option value="VehicleDetailsPage">VehicleDetailsPage</option>
<option value="VehicleSearchResults">VehicleSearchResults</option>
<option value="ContactUsForm">ContactUsForm</option>
</select>
</div>
<div class="area-checkboxes">
<p class="wheretosave">Where?</p>
<input type="checkbox" name="head" /><label for="head">Head</label>
<input type="checkbox" name="body" /><label for="body">Body</label>
</div>
<div class="save-pt">
<input value="SAVE" type="submit" />
</div>
</td>
</tr>
</table>
JavaScript:
// HIDES CURRENT PT & CHANGES TOGGLE BUTTON ICON WHEN CLICKED
$('.togPTbutton').click(function(){
$('.pt-values').slideToggle(25, function() {
if ($('.pt-values').is(':hidden')) {
$('input.togPTbutton').val('?');
}else{
$('input.togPTbutton').val('?');
}
});
});
$(document).ready(function () {
var table = $('.manage-pt'),
rows = $(table).find('tr'),
rowCount = $(rows).length,
addedRow = $(document.createElement('tr')),
addButton = $('.addPTbutton'),
removeButton = $('.delPTbutton');
function addRow(){
var thisRow = $(addedRow).clone(true);
$(thisRow).attr('class','.pt-entry-' + rowCount);
rowCount += 1;
$(thisRow).html('<td>row</td>');
$(table).append(thisRow);
}
function removeRow(){
var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
$(table).remove(items[rowCount - 1]);
rowCount -= 1;
}else{
alert('CANNOT DELETE LAST ROW');
}
}
addButton.click(function(e){
addRow();
});
removeButton.click(function(e){
removeRow();
});
});
Should look close to something like this mockup ...

Alright, I think I found your problem. You are trying to call $(table).querySelectorAll('tr'). .querySelectorAll is a javascript function that you are using with a JQuery selector. This is where your removeRow() function bombs. Try commenting that line out. Then, you will need to find a new way to select the last row, which can easily be done with this:
$(table).find('tr:last').remove();
Final form:
function removeRow(){
//var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
//$(table).remove(items[rowCount - 1]);
$(table).find('tr:last').remove();
rowCount -= 1;
}
else
{
alert('CANNOT DELETE LAST ROW');
}
}
If you want this to work in IE8 and older, you can use this JQuery since you have the number of rows:
$(table).find('tr').eq(rowCount - 1).remove();
in place of:
$(table).find('tr:last').remove();
JSFiddle: http://jsfiddle.net/Em8Q5/2/
EDIT: ------------------------------------------------------------------------------------
Alright, I found a solution being able to delete the current row.
First, allow a parameter into your removeRow function and switch the selector to use closest:
function removeRow(currRow){
//var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
//$(table).remove(items[rowCount - 1]);
currRow.closest('tr').remove();
rowCount -= 1;
}
else
{
alert('CANNOT DELETE LAST ROW');
}
}
Then you will need to modify your .click function so that it will change dynamically as you add/remove rows/buttons. Also, note the parameter so it knows which row's button is clicked.
//removeButton.click(function(e){
$('body').on("click", ".delPTbutton", function(e) {
removeRow($(this)); //Note the parameter that we added so it knows which row to remove
});
JSfiddle: http://jsfiddle.net/Em8Q5/3/

I check up your code using chrome developer tool and when i clicked the delPTbutton button to remove last row it showed an error in your removeRow Method , The Error Message Is :
(Uncaught TypeError: Object [object Object] has no method 'querySelectorAll')
The Issue Here Is That 'querySelectorAll' Is One Of javascript base api but you use it after a jquery object.
Consider Using $(table).find('tr') Instead .

Ok so thank you #Chad for your help. You were seriously a life saver.
I took what you did, one step further in this new version of the code:
New CodePen
However I now have a very js minor issue. I have it set to turn the ".vendor" input to read only when the relevant stack is closed, however I need to target something other than ".vendor", because it's effecting each clones ".vendor" as well.
Would it be something like:
$(this).parent().next().child().child();?

Related

Script not working in cell in every row in table

I have a row/column table with switches, unfortunately the script can't find
the switches in the new column, basically after the end of the cell .
I tried modifying some of the scripts that were posted in the similar posts but
none of them worked. I am pretty much stuck at this point.
Here's my HTML and the java script that does the calculation for the switches:
<div style="margin-left:-178px">
<form action="file:///Users/jason/Desktop/Temp/JACK010.txt" target="_blank">
<font color="white">JACK010</font>
<input type="submit" value="CHECK ADDRESS">
<div id="checkbox-container">
<div style="margin-left:178px">
<div style="margin-top:-18px">
<div>
<input type="checkbox" id="option170">
</div>
</form>
</td>
</tr>
I have a lot of those, within the cell, and finally the JavaScript:
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
var $checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function() {
$checkboxes.each(function() {
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
Thank you!
Using only $("#checkbox-container :checkbox"); results in only reading the first container with the ID checkbox-container.
If you want to fetch all checkboxes, you should either change the checkbox-container to a class or use the following selector within jQuery:
var $checkboxes = $("div#checkbox-container :checkbox");
It will then loop through all the checkboxes, even if an ID is used instead of a class.
Keep in mind, that the ID of your checkbox (<input type="checkbox" id="option170">) must however change in order to get valid data and all the values you want.
Side note: Please keep your HTML code clean and valid.

Trying to delete two rows using javascript

I'm trying to delete two table rows at the same time in a dynamic table, but I'm having trouble deleting multiple rows at the same time. I have a table which displays text and a delete button in one tr and other related text in the next tr immediately after it. When I press the delete button on the first row, the row gets deleted but the one after it does not get removed. I have tried to get the value/address of the next row using this link but it does not seem to be working for me.
Fiddle in the works: http://jsfiddle.net/DLqLW/3/
The button for deleting the row is coded this way:
<input type="button" id="<?php echo $str; ?>" class="button-add" name="butcli" value="-" onClick="deleteRow(this)"></input>
and the function that it calls is:
function deleteRow(el) {
while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}
if (el.parentNode && el.parentNode.rows.length > 1) {
el.parentNode.removeChild(el);
}
}
I'm struggling with how to delete the next row after it. If anyone could provide some help, that would be great!
Do you have just two rows?
You are testing:
parentNode.rows.length > 1
If you have only two rows, it will not delete the second row.
Change it to:
parentNode.rows.length > 0
Try this
http://www.w3schools.com/dom/dom_nodes_navigate.asp
function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
Alternate (simpler?) approach: Use a <div> rather than a sibling <tr>
A different approach, to keep it simple, avoid jQuery, and avoid nextSibling and related problems:
Working fiddle: http://jsfiddle.net/digitalextremist/9Zv83/3/
...using this HTML approach:
<tr>
<td>1
<div>this row should be deleted if the one above is removed.</div>
</td>
<td>
<input type="button" id="<?php echo $str; ?>" class="button-add" name="butcli" value="-" onClick="javascript:deleteRow(this)"></input>
</td>
</tr>
Also, your existing version relies on a <tr> which is short one cell. If you add colspan=2 to your sibling row, then the formatting is thrown off too... hence this approach I am proposing.
Using Jquery this is working
function deleteRow(el) {
var tr = $(el).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(400, function(){
tr.remove();
});
var tr2 = $(tr).closest('tr').next();
tr2.css("background-color","#FF3700");
tr2.fadeOut(400, function(){
tr.remove();
});
}
Looks pretty swanky too I used your jfiddle with jQuery 2.02

JQuery - Append to text area that has been modified with Jquery

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you
You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo
Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

creating an inline update field using jquery

I've gotten stuck(again)
I have a table and one of the columns is a value that I want to be able to click, turn into an input field, then click again to change it back to just text.
I've gotten the first step done. It turns into an input field with a link to click and it uses the value that was previously in the td.
However, in writing the function to update the value and remove the input, I can't get it to fire at all. I've tried copying out the input field and hard coding that first step into the page and when I do that it does actually fire the click function. (I haven't finished writing this step as I wanted to get the function to fire first. Below is my code. Any help is overwhelmingly appreciated!
HTML:
<table>
<tr id="1"><td class="qty" set="0" >2</td></tr>
<tr id="2"><td class="qty" set="0" >2</td></tr>
<tr id="3"><td class="qty" set="0" >2</td></tr>
</table>
JQUERY:
$(".qty").click(function(){
var value = $(this).text();
var set =$(this).attr('set');
if (set==0){
$(this).html('<input type="text" name="quantity" value="'+value+'">update </span>');
$(this).attr('set', '1');
}
});
$(".update_qty").click(function(){
alert("using this to check if it's firing");
});
you need to use the live() function, otherwise the event won't be added to newly created elements.
$(".update_qty").live('click',function() {
alert("check if firing");
});
demo
http://jsfiddle.net/JEBaN/1/
some value
<br><br>
<a href='javascript:' id='toEdit'>To Edit Mode</a>
<a href='javascript:' id='toView'>To View Mode</a>​
jQuery(function(){
jQuery('#toEdit').click(_toEditMode);
jQuery('#toView').click(_toViewMode);
});
function _toEditMode()
{
var _elm=jQuery('.converter');
var _val= _elm.html();
_elm.html('<input type="text" value="'+_val+'" />');
}
function _toViewMode()
{
var _elm=jQuery('.converter');
var _val= _elm.find('input').val();
_elm.html(_val);
}
​
$(".update_qty").click(function(){
$("qty").html("<p>whatever text you want</p>");
});

Categories

Resources