Trying to get element and store them in array using jquery - javascript

I have an html structure like this :
<tr>
<td>NC</td>
<td><%= #subscriptions.where("users.ranking = 'NC'").count %></td>
<td><input type="checkbox" name="my-checkbox" class="checkbox-ranking" id="bite" data-size='small'></td>
</tr>
<tr>
<td>40</td>
<td><%= #subscriptions.where("users.ranking = '40'").count %></td>
<td><input type="checkbox" name="my-checkbox" class="checkbox-ranking" data-size='small' ></td>
</tr>
<tr>
<td>30/5</td>
<td><%= #subscriptions.where("users.ranking = '30/5'").count %></td>
<td><input type="checkbox" name="my-checkbox" class="checkbox-ranking" data-size='small' ></td>
</tr>
I need to write a script that each time a checkbox is checked gets the innerhtml of the first <td></td> of each <tr></tr> where the checkbox is checked and returns it as an array.
Here's what I came up with :
$(document).ready(function(){
$('.checkbox-ranking').on('change', function() {
var rankings = $('.checkbox-ranking:checked').map(function() {
return $(this).parent().parent().parent().parent().children().first().html();
}).get().join(',');
alert(rankings);
});
});
I must add that I installed the gem bootstrap-switch to have ON/OFF switch button and that is what my checkboxes are. I noticed that I switch on my button, it doesnt pass to checkedin the html code, so I guess that's why my code isnt working: the script doesnt actually detects the on change event.
Any other ideas ?

Ok, now this works
$(document).ready(function(){
$('.checkbox-ranking').on('change', function() {
var rankings = $('.checkbox-ranking:checked').map(function() {
return $(this).parent().parent().find('td:first-child').html();
}).get().join(',');
alert(rankings);
});
});
and jsfiddle: https://jsfiddle.net/btrauybx/2/

Try using closest() and first():
$(function() {
$('input.checkbox-ranking').on('change', function(e) {
var ranks = $('input.checkbox-ranking:checked').map(function() {
return $(this).closest('tr').children().first().text();
}).get();
alert(ranks.join(','));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td>NC</td>
<td>
<%=# subscriptions.where( "users.ranking = 'NC'").count %>
</td>
<td>
<input type="checkbox" name="my-checkbox" class="checkbox-ranking" id="bite" data-size='small'>
</td>
</tr>
<tr>
<td>40</td>
<td>
<%=# subscriptions.where( "users.ranking = '40'").count %>
</td>
<td>
<input type="checkbox" name="my-checkbox" class="checkbox-ranking" data-size='small'>
</td>
</tr>
<tr>
<td>30/5</td>
<td>
<%=# subscriptions.where( "users.ranking = '30/5'").count %>
</td>
<td>
<input type="checkbox" name="my-checkbox" class="checkbox-ranking" data-size='small'>
</td>
</tr>
</table>
You can also use eq(0) instead of first().

Related

Increment the id of html field [duplicate]

I have this table with some dependents information and there is a add and delete button for each row to add/delete additional dependents. When I click "add" button, a new row gets added to the table, but when I click the "delete" button, it deletes the header row first and then on subsequent clicking, it deletes the corresponding row.
Here is what I have:
Javascript code
function deleteRow(row){
var d = row.parentNode.parentNode.rowIndex;
document.getElementById('dsTable').deleteRow(d);
}
HTML code
<table id = 'dsTable' >
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
</table>
JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
jQuery has a nice function for removing elements from the DOM.
The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."
$(this).closest("tr").remove();
Each delete button could run that very succinct code with a function call.
Lots of good answers, but here is one more ;)
You can add handler for the click to the table
<table id = 'dsTable' onclick="tableclick(event)">
And then just find out what the target of the event was
function tableclick(e) {
if(!e)
e = window.event;
if(e.target.value == "Delete")
deleteRow( e.target.parentNode.parentNode.rowIndex );
}
Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:
document.getElementById('dsTable').addEventListener('click',tableclick,false);
​​
Here is working code: http://jsfiddle.net/hX4f4/2/
I would try formatting your table correctly first off like so:
I cannot help but thinking that formatting the table could at the very least not do any harm.
<table>
<thead>
<th>Header1</th>
......
</thead>
<tbody>
<tr><td>Content1</td>....</tr>
......
</tbody>
</table>
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example:
http://jsfiddle.net/p9dey/1/
Use the following code to delete the particular row of table
<td>
<asp:ImageButton ID="imgDeleteAction" runat="server" ImageUrl="~/Images/trash.png" OnClientClick="DeleteRow(this);return false;"/>
</td>
function DeleteRow(element) {
document.getElementById("tableID").deleteRow(element.parentNode.parentNode.rowIndex);
}
try this for insert
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
and this for delete
document.getElementById("myTable").deleteRow(0);
Yeah It is working great
but i have to delete from localstorage too, when user click button , here is my code
function RemoveRow(id) {
// event.target will be the input element.
// console.log(id)
let td1 = event.target.parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);// the row to be removed
// const books = JSON.parse(localStorage.getItem("books"));
// const newBooks= books.filter(book=> book.id !== books.id);
// console.log(books, newBooks)
// localStorage.setItem("books", JSON.stringify(newBooks));
}
// function RemoveRow(btn) {
// var row = btn.parentNode.parentNode;
// row.parentNode.removeChild(row);
// }
button tag
class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}
Hi I would do something like this:
var id = 4; // inital number of rows plus one
function addRow(){
// add a new tr with id
// increment id;
}
function deleteRow(id){
$("#" + id).remove();
}
and i would have a table like this:
<table id = 'dsTable' >
<tr id=1>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr id=2>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr id=3>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>
Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

How can i accomplish the following using knockout js?

I am trying to learn knockout.js and in an attempt to make my own code, this is what i came up with. It is a hotel package proposal where a user clicks on add hotel, and text boxes relating to hotels appear. I also want the initialized data to show in the text boxes.
I'm using this as reference.
http://knockoutjs.com/examples/contactsEditor.html
Right now, the text boxes are not showing the initial data, and the code breaks when i click on add hotels
my knockout code
function Proposal(details,fee, hotelproposal) {
var self = this;
self.details = details;
self.fee = fee;
self.hotelproposal= ko.observableArray(hotelproposal);
}
function hotel(hotelname,checkin,checkout,roomtype, viewtype){
self.hotelname=hotelname;
self.checkin=checkin;
self.checkout=checkout;
self.roomtype=roomtype;
self.viewtype=viewtype;
}
// Overall viewmodel for this screen, along with initial state
function ProposalViewModel() {
var self = this;
self.info=ko.observable( new Proposal("these are the details", 1200,[new hotel("Hilton","202020","202020","double", "city") , new hotel("Hilton2","2020201","2020201","triple", "sea")]));
self.addhotel = function(hotel) {
self.info.Proposal.hotelproposal.push({
hotelname:"",
checkin:"",
checkout:"",
roomtype:"",
viewtype:""
});
};
}
ko.applyBindings(new ProposalViewViewModel());
my html code:
<h2>Proposal</h2>
<div >
<table>
<tr>
<th>Details</th>
<th>fee</th>
<th>Hotels</th>
</tr>
<tbody data-bind="foreach: info">
<tr>
<td>
<input data-bind='value: Proposal.details' />
</td>
<td><input data-bind='value: fee' /></td>
<td>
<table>
<tbody data-bind="foreach: info.hotelproposal">
<tr>
<td><input data-bind='value: hotelname' /></td>
<td><input data-bind='value: checkin' /></td>
<td><input data-bind='value: checkout' /></td>
<td><input data-bind='value: roomtype' /></td>
<td><input data-bind='value: viewtype' /></td>
</tr>
</tbody>
</table>
<a href='#' data-bind='click: $root.addhotel'>Add hotel</a>
</td>
</tr>
</tbody>
</table>
</div>
This code is not working. Can someone point out whats wrong?

javascript get a total for a table column NaN error

I am getting a NaN error. the code was copied from a fiddle which works perfectly. Here is the code.
<tbody>
<tr>
<td><input type="checkbox" name="payment_id[]" id="payment_id_" value="6" class="box" checked="checked" /></td>
<td>2015-08-26 20:43:50 UTC</td>
<td>1000002043</td>
<td class = "amount">25.0</td>
<td>CHK</td>
<td></td>
<td></td>
<td>5</td>
<td>Show</td>
<td>Edit</td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/payments/6">Destroy</a></td>
</tr>
<% end %>
</tbody>
<td>Total</td><td><div id="total"></div></td>
Here is the jquery
$(function() {
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+=parseFloat($(this).parent().next('td').find('.amount').text());
});
$('#total').text(total);
});
});
I am getting a NaN in the total element.
Let's break down your jQuery chain:
$(this) // ,box
.parent() // The <td>
.next('td') // The next <td> in the sequence
.find('.amount') // Tries to find an element with class `amount` inside the <td>
.text() // Empty, because the previous element doesn't exist
What you'll need to do is append the .amount onto your selector and use nextAll instead, like so:
$(this).parent().nextAll("td.amount").text()
If you had multiple amount classes, you'd need to make sure you only picked the first one like so:
$(this).parent().nextAll("td.amount:first").text()
Example:
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+=parseFloat($(this).parent().nextAll('td.amount').text());
});
$('#total').text(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td><input type="checkbox" name="payment_id[]" id="payment_id_" value="6" class="box" checked="checked" /></td>
<td>2015-08-26 20:43:50 UTC</td>
<td>1000002043</td>
<td class = "amount">25.0</td>
<td>CHK</td>
<td></td>
<td></td>
<td>5</td>
<td>Show</td>
<td>Edit</td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/payments/6">Destroy</a></td>
</tr>
</tbody>
</table>
<div id="total"></div>
Considering the amount is entered once per row I jumped back to row and found the td.amount in the row.
(function($) {
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total += parseFloat($('td.amount', $(this).closest('tr')).text());
});
$('#total').text(total);
});
})(jQuery);
There is a referencing error. Use:
$(function() {
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+=parseFloat($(this).closest('tr').find('td.amount').text());
});
$('#total').text(total);
});
});

jquery/javascript: add to array in case tr has certain class

I have a dynamic html table:
<table>
<tbody>
<tr>
<td>Name</td>
<td>City</td>
</tr>
<tr class="new" id="item1">
<td><input class="names" value="John Smith" type="hidden">John Smith</td>
<td><input class="cities" value="London" type="hidden">London</td>
</tr>
<tr class="normal" id="item2">
<td><input class="names" value="Regina Mills" type="hidden">Regina Mills</td>
<td><input class="cities" value="Berlin" type="hidden">Berlin</td>
</tr>
<tr class="normal" id="item3">
<td><input class="names" value="Marcus Bell" type="hidden">Marcus Bell</td>
<td><input class="cities" value="Liverpool" type="hidden">Liverpool</td>
</tr>
</tr>
</tbody>
</table>
From my js file I'm storing the information in this way:
var arrayNames = [];
$(".names").each(function(){
arrayNames.push($(this).val());
})
var arrayCities = [];
$(".cities").each(function(){
arrayCities.push($(this).val());
})
params += '&names='+arrayNames;
params += '&cities='+arrayCities;
With this I am getting in my php:
$_REQUEST['names']
: string = John Smith,Regina Mills,Marcus Bell
$_REQUEST['cities']
: string = London,Berlin,Liverpool
But I only need in the $_REQUESTs the values when the class in the table tr's is "new"
How can I do that?
Thanks!
You could try
$(".names").each(function(){
if ($( this ).parent().attr( "class" ) == "new")
arrayNames.push($(this).val());
})
Just target the .names within .new. You can use map() to get the values:
var arrayNames = $('.new .names').map(function() { return this.value; }).get();
.. and do the same thing for .cities

if input field has a value found in array, do this (jQuery/Javascript)

I've got a page with a handful of input fields.
I need to find the fields with an array of values, and if so, .remove() the closest('tr')
The markup is similar to this
<table>
<tr>
<td>
<input type="text" value="this">
</td>
</tr>
<tr>
<td>
<input type="text" value="that">
</td>
</tr>
<tr>
<td>
<input type="text" value="them">
</td>
</tr>
</table>
I need to find "this" and "that", and if they are there, remove their <tr> container (and themselves) so I'd end up with:
<table>
<tr>
<td>
<input type="text" value="them">
</td>
</tr>
</table>
I've tried this:
jQuery(document).ready(function($){
var badfields = ['this', 'that'];
var fieldvalue = $('input[type="text"]').val();
if($.inArray(fieldvalue, badfields) > -1){
$(this).closest('tr').remove();
}
});
but it doesn't seem to want to work?
You need to iterate over all the fields using .each, so something like this:
$('input[type="text"]').each(function() {
var fieldvalue = $(this).val();
if ($.inArray(fieldvalue, badfields) > -1) {
$(this).closest('tr').remove();
}
});
Example: jsfiddle
You can be very concise sometimes with jQuery. jQuery has content selectors you can use for this type of purpose:
$("input[type=text][value=this], [value=that]").parents("tr").remove();
since you don't necessarily know this or that beforehand, you can do something like this:
var badfields = ['this', 'that'];
$(badfields).each(function(i) {
$("input[type=text][value=" + this + "]").parents("tr").remove();
});
You can use each to iterate through the selector. this in your inArray scope is not the element you were looking for.
DEMO: http://jsfiddle.net/
html:
<table>
<tr>
<td>
<input type="text" value="this">
</td>
</tr>
<tr>
<td>
<input type="text" value="that">
</td>
</tr>
<tr>
<td>
<input type="text" value="them">
</td>
</tr>
</table>
js:
jQuery(document).ready(function($){
var badfields = ['this', 'that'];
$('input[type="text"]').each(function(){
if( $.inArray(this.value, badfields) > -1 ){
$(this).closest('tr').remove();
}
});
});

Categories