Accessing HTML this object within javascript - javascript

I have some HTML code that uses some embedded python to create a table of results that have been extracted from an SQLlite database. The HTML also uses bootstrap to create a table to highlight the rows when the mouse hovers of each row.
<div class="col-md-6">
<h3> Suggested tools </h3>
<table class="table table-hover">
<tr><th> Tool </th> <th> Function </th> </tr>
{% for post in posts %}
<tr class="table-light" onclick="changeClass()"> <td>{{post.tool}} </td> <td> {{post.summary}}</td> <td> </tr>
{% endfor %}
</table>
<p id="test"> </p>
</div>
When I select a particular row I want the row to change color. Using Bootcamp I know I can make this happen by changing the class property and the following code produces the desired result:
<tr class="table-light" onclick="this.className='success'"> <td>{{post.tool}} </td> <td> {{post.summary}}</td> <td> </tr>
This works well as each row is generated within the loop so the this object makes sure only the selected row has the class changed. The problem is I have some further javascript code I want to add to the onclick event. Is there a way of using a javascript function to access the this object so that it is used in the same way as elements in HTML?
I've tried this but as anticipated no success
HTML:
<tr class="table-light" onclick="changeClass()"> <td>{{post.tool}} </td> <td> {{post.summary}}</td> <td> </tr> code here
Javascript:
function changeClass() {
return "this.className= 'table-success';}

You need delegation and unobtrusive non-inline code
Also your HTML is not valid. You should run the rendered page through a validator
const additem = id => console.log(id);
document.querySelector(".table").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("add")) {
additem(tgt.dataset.id)
} else {
const row = tgt.closest("tr");
if (row.classList.contains("table-light")) {
row.classList.add("table-success");
}
}
})
.table-success { background-color:green}
<div class="col-md-6">
<h3> Suggested tools </h3>
<table class="table table-hover">
<tr>
<th> Tool </th>
<th> Function </th>
</tr>
<tr>
<td>tool</td>
<td>summary</td>
<td> <button type="button" class="add" data-id="{{post.id}}">ID1</button></td>
</tr>
<tr class="table-light">
<td>tool</td>
<td>summary</td>
<td>
</tr>
</table>
<p id="test"> </p>
</div>

Just pass it to the function:
function changeClass(row) {
console.log(row)}
<table>
<tr class="table-light" onclick="changeClass(this)"> <td>{{post.tool}} </td> <td> {{post.summary}}</td> <td> </tr>
<tr class="table-light" onclick="changeClass(this)"> <td>{{post.tool}} </td> <td> {{post.summary}}</td> <td> </tr>
</table>

You can do it by passing this with function call
function changeClass(row) {
row.className= 'table-success'
}
.table-success{
background-color:gray;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="col-md-6">
<h3>Suggested tools</h3>
<table class="table table-hover">
<tr>
<th>Tool</th>
<th>Function</th>
</tr>
<tr class="table-light" onclick="changeClass(this)">
<td>some data</td>
<td>some data</td>
<td></td>
</tr>
<tr class="table-light" onclick="changeClass(this)">
<td>some data</td>
<td>some data</td>
<td></td>
</tr>
<tr class="table-light" onclick="changeClass(this)">
<td>some data</td>
<td>some data</td>
<td></td>
</tr>
</table>
<p id="test"></p>
</div>
</body>
</html>

Try this:
HTML:
<tr onclick="foo(this);"></tr>
JavaScript:
let foo = elem =>{
console.log(elem.className);
}

Related

how can i add space between table border and text using html only?

HI can someone pls help me I am new to code and this is my college assignment in which we are not supposed to use CSS, only using HTML how can I add space between text and table-border.
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>TABLE</TITLE>
</HEAD>
<BODY>
<TABLE BORDER="5" CELLSPACING="4" CELLPADDING="3">
<TR BGCOLOR="BLUE">
<TH ALIGN="CENTER" HEIGHT="20">
<FONT SIZE="4" COLOR="WHITE"> <u>First Name</u>
<TH ALIGN="CENTER" HEIGHT="20">
<FONT SIZE="4" COLOR="WHITE"> <u>Last Name</u>
</TR>
<TR BGCOLOR="YELLOW">
<TD> <u>Keith</u>
<TD><u>Richards</u>
</TR>
<TR BGCOLOR="ORANGE">
<TD><u>Mick</u>
<TD><u>Jagger</u>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Bill</u>
<TD><u>Wyman</u>
</TR>
<TR BGCOLOR="ORANGE">
<TD><u>Ron</u>
<TD><u>Wood</u>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Charlie</u>
<TD><u>Watts</u>
</TR>
<TR BGCOLOR="ORANGE">
<TD><u>Mick</u>
<TD><u>Taylor</u>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Brian</u>
<TD><u>Jones</u>
</TR>
</TABLE>
</BODY>
</HTML>
my code-
<TD> <u>&nbspKeith</u> </TD>
Try using &nbsp should give you the desired result.
To add space between cell content and cell wall you can use the cellpadding attribute in table tag.
The HTML cellpadding Attribute is used to specify the space
between the cell content and cell wall. The cellpadding attribute is
set in terms of pixels.
Refer: cellpadding
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>TABLE</TITLE>
</HEAD>
<BODY>
<TABLE BORDER="5" CELLSPACING="4" CELLPADDING="10">
<TR BGCOLOR="BLUE">
<TH ALIGN="CENTER" HEIGHT="20">
<FONT SIZE="4" COLOR="WHITE"> <u>First Name</u>
<TH ALIGN="CENTER" HEIGHT="20">
<FONT SIZE="4" COLOR="WHITE"> <u>Last Name</u>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Keith</u></TD>
<TD><u>Richards</u></TD>
</TR>
<TR BGCOLOR="ORANGE">
<TD><u>Mick</u></TD>
<TD><u>Jagger</u></TD>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Bill</u></TD>
<TD><u>Wyman</u></TD>
</TR>
<TR BGCOLOR="ORANGE">
<TD><u>Ron</u></TD>
<TD><u>Wood</u></TD>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Charlie</u></TD>
<TD><u>Watts</u></TD>
</TR>
<TR BGCOLOR="ORANGE">
<TD><u>Mick</u></TD>
<TD><u>Taylor</u></TD>
</TR>
<TR BGCOLOR="YELLOW">
<TD><u>Brian</u></TD>
<TD><u>Jones</u></TD>
</TR>
</TABLE>
</BODY>
</HTML>

How to replace an entire table with pictures?

This is my table, of course with some text in it, and I want on a button click to hide it, and show some images. I also want to reverse the action on the same button click. How can I do that?
<div id="aspect" style="display:yes">
<table style="100%" id="Table">
<tr>
<th id="textul" > </th>
<th id="textul4"> </th>
</tr>
<tr>
<td id="testul2and3" style="vertical-align:top"> </td>
<td style="vertical-align:top" id="textul6">
<p> <iframe></iframe> </p>
</td>
</tr>
</table>
</div>
you can start with jQuery .toggle() method
$("button").click(function(){
$("img").toggle();
});
this will work as you need
Have a look here: http://api.jquery.com/toggle/
Please have a look at this code sample. I have used jQuery 2.1.1
$(function() {
$('#toggler').click(function() {
$('#Table').toggle();
$('#imageblock').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="aspect">
<div style="display:none;" id="imageblock">
<img src="http://lorempixel.com/400/200/" />
</div>
<table id="Table">
<tr>
<th id="textul" > </th>
<th id="textul4"> </th>
</tr>
<tr>
<td id="testul2and3" style="vertical-align:top"> </td>
<td style="vertical-align:top" id="textul6">
<p> <iframe></iframe> </p> </td>
</tr>
</table>
</div>
<button id="toggler">Toggle Image/Table</button>

Getting value from specific cell in an html table is not working using JQuery

I am trying to get row data from a table so I can use it in a modal. Below is my code for Views.
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">
<link href="#Url.Content("~/css/bootstrap.css")" rel="stylesheet">
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$("#acctInfo").DataTable();
$(".td_0").hide();
});
</script>
<!-- Page Title
============================================= -->
<section id="page-title">
<div class="container clearfix">
<h1>View Accounts</h1>
</div>
</section><!-- #page-title end -->
<section id="content">
<div class="content-wrap">
<div class="container clearfix">
<table class="table table-striped table-condensed table-hover" id="acctInfo">
<thead>
<tr>
<th class="td_0">Account Id</th>
<th>Employee Id</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Business Name</th>
<th>Account Type</th>
<th></th>
#*<th></th>*#
</tr>
</thead>
<tbody>
#foreach (var i in Model.AccountsViews)
{
<tr id="rowx">
<td > #Html.DisplayFor(m => i.AcctId)</td>
<td > #Html.DisplayFor(m => i.EmployeeId)</td>
<td > #Html.DisplayFor(m => i.FirstName)</td>
<td > #Html.DisplayFor(m => i.MiddleName)</td>
<td > #Html.DisplayFor(m => i.LastName)</td>
<td > #Html.DisplayFor(m => i.BusinessName)</td>
<td > #Html.DisplayFor(m => i.AccountType)</td>
#*<td>Edit</td>
<td>Delete</td>*#
<td>
<input type="button" value="Edit" class="btn btn-success form-control" onclick="OpenSelected()" />
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</section>
<div id="divEdit" style="display: none;">
<input type="hidden" id="hidId"/>
<table>
<tr>
<td>Employee Id</td>
<td><input type="text" id="txtEmployeeId" class="form-control"/></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" id="txtFirstName" class="form-control"/></td>
</tr>
<tr>
<td>Middle Name</td>
<td><input type="text" id="txtMiddleName" class="form-control"/></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="txtLastName" class="form-control"/></td>
</tr>
<tr>
<td>Business Name</td>
<td><input type="text" id="txtBusinessName" class="form-control"/></td>
</tr>
#*<tr>
<td>Account Type</td>
<td>
#Html.DropDownListFor(o => )
</td>
</tr>*#
</table>
</div>
<script>
function OpenSelected() {
var a = $('.trSelected td').eq(4).text();
alert(a);
}
</script>
With that code, I am able to invoke the alert method with the following code:
<script>
function OpenSelected() {
var a = $('.trSelected td').eq(4).text();
alert(a);
}
</script>
but it has no value of the cell that I need. It only has "localhost/1234 Says: " the alert has no value. I need your help. Thank you.
Give a try to following code... .closset would give you the selected row and than you find columns value on the base of indexes.
<script>
$('.btn-success').click(function () {
var a = $(this).closest("tr").find('td:eq(0)').text();
var b = $(this).closest("tr").find('td:eq(1)').text();
alert(a);
});
</script>
Try using :eq() selector at this context
You should use .text() instead to retrieve its text content,
var t = $('#table');
var val1 = $(t).find('tr:eq(2) td:eq(4)').text();
alert(val1);
Or do,
alert($('#table tr:eq(2) td:eq(4)').text());
DEMO

How can I identify a specific item in <select> and add a delete button each row in jquery

1.) I have created a nested table, then what I want to do is when I click the 'Delete' button inside the child table, its row will be deleted.
2.) I have <select> tag. The problem is how can I put a validation which checks if the item type has been already selected by one customer, but this selected item can be also selected at the next Customer.
For example, Customer1 selects Iron. Now the Customer1 cannot choose the Iron type of item on the next item. Customer1 may also select Copper or Wood but not Iron. Then if I have Customer2 the Iron type of Item can be selectable.
Here's my code:
$(".addItem").on('click', function(e) {
$(this).closest('table').find(".item:last").after('<tr class="item"><td><button>Delete</button></td><td>New item</td><td></td><td></td><td></td><td><select name="" id=""><option value="">Iron</option><option value="">Copper</option><option value="">Wood</option></select></td></tr>');
});
$(".addCustomer").on('click', function(e) {
var newCustomer = $('.customer:last').after('<tr class="customer"><td>New Customer</td><td></td><td></td><td></td></tr>');
var newCart = $('.cart:first').clone(true, true).wrap('td');
newCart.find('tbody').html("").html('<tr class="item"><td><button>Delete</button></td><td>New item</td><td></td><td></td><td></td><td><select name="" id=""><option value="">Iron</option><option value="">Copper</option><option value="">Wood</option></select></td></tr>');
$('.customer:last').append(newCart);
e.preventDefault();
});
$('.itemType').on('change', function() {
var selected = $(this)find('option:selected').val();
if ($(this).find('option:selected').val() === selected) {
alert("Item already selected.");
}
});
table,
td,
th {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>PO</title>
<header>
<form id="panel">
</form>
</header>
<section id="I">
<table id='PO1' class="purchaseOrder">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Gender</th>
<th>Cart</th>
</tr>
</thead>
<tbody>
<tr id='C1' class='customer'>
<td>Some Name</td>
<td>30</td>
<td>My Address</td>
<td>Male</td>
<td>
<table class='cart'>
<thead>
<tr>
<th>Delete</th>
<th>Brand</th>
<th>Quantity</th>
<th>Size</th>
<th>Color</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr id='item1' class='item'>
<td><button>Delete</button></td>
<td>Yamaha</td>
<td>30</td>
<td>Large</td>
<td>Black</td>
<td>
<select name="" class="itemType">
<option value="i">Iron</option>
<option value="c">Copper</option>
<option value="w">Wood</option>
</select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='5'></td>
<td>
<button class="addItem">Add Item</button>
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='3'></td>
<td>
<button class="addCustomer">Add Customer</button>
</td>
</tr>
</tfoot>
</table>
</section>
<footer> </footer>
I have fixed the Delete issue. In terms of validation, answer my below question and I will fix the same.
Okay, I handled it now properly with an empty item and disabling the selected value on other item.
$(".addItem").on('click', function(e) {
var parent = $(this).closest('table');
var lastItem = parent.find(".item:last");
var newItem = $('<tr class="item"><td><button>Delete</button></td><td>New item</td><td></td><td></td><td></td><td><select name="" id="" class="itemType"><option value="-1"></option><option value="i">Iron</option><option value="c">Copper</option><option value="w">Wood</option></select></td></tr>');
if(lastItem && lastItem.length > 0) {
parent.find(".item:last").after(newItem);
} else {
parent.append(newItem);
}
fixNewSelectOption(newItem);
handleDeleteAction();
});
$(".addCustomer").on('click', function(e) {
var newCustomer = $('.customer:last').after('<tr class="customer"><td>New Customer</td><td></td><td></td><td></td></tr>');
var newCart = $('.cart:first').clone(true, true).wrap('td');
newCart.find('tbody').html("").html('<tr class="item"><td><button>Delete</button></td><td>New item</td><td></td><td></td><td></td><td><select name="" id="" class="itemType"><option value="-1"></option><option value="i">Iron</option><option value="c">Copper</option><option value="w">Wood</option></select></td></tr>');
$('.customer:last').append(newCart);
handleDeleteAction();
e.preventDefault();
});
$(document).on('click', '.item button', function(){
if($(this).closest('table').find('.item button').length > 1) {
$(this).closest('tr').remove();
}
handleDeleteAction();
});
$(document).on('change', '.itemType', function(){
fixSelectOption($(this));
});
function handleDeleteAction() {
$('table.cart').each(function(){
var cart = $(this);
var deleteButtons = cart.find('.item button');
deleteButtons.prop('disabled', deleteButtons.length <= 1);
});
}
function fixSelectOption(elm) {
var selected = elm.val();
var options = elm.find('option[value!="' + selected + '"]');
var elms = elm.closest('table').find('.itemType').not(elm);
elms.each(function(){
var current = $(this);
if(current.val() === selected){
current.val('-1');
}
options.each(function(){
var optValue = $(this).val();
if(optValue !== '-1' && !$(this).prop('disabled')){
current.find('option[value="' + optValue + '"]').prop('disabled', false);
}
});
if(selected !== '-1'){
current.find('option[value="' + selected + '"]').prop('disabled', true);
}
});
}
function fixNewSelectOption(elm) {
var elms = elm.closest('table').find('.itemType').not(elm);
elms.each(function(){
var current = $(this);
if(current.val() !== '-1'){
elm.find('option[value="' + current.val() + '"]').prop('disabled', true);
}
});
}
table,
td,
th {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>PO</title>
<header>
<form id="panel">
</form>
</header>
<section id="I">
<table id='PO1' class="purchaseOrder">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Gender</th>
<th>Cart</th>
</tr>
</thead>
<tbody>
<tr id='C1' class='customer'>
<td>Some Name</td>
<td>30</td>
<td>My Address</td>
<td>Male</td>
<td>
<table class='cart'>
<thead>
<tr>
<th>Delete</th>
<th>Brand</th>
<th>Quantity</th>
<th>Size</th>
<th>Color</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr id='item1' class='item'>
<td><button disabled>Delete</button></td>
<td>Yamaha</td>
<td>30</td>
<td>Large</td>
<td>Black</td>
<td>
<select id="select" class="itemType">
<option value="i">Iron</option>
<option value="c">Copper</option>
<option value="w">Wood</option>
</select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='5'></td>
<td>
<button class="addItem">Add Item</button>
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='3'></td>
<td>
<button class="addCustomer">Add Customer</button>
</td>
</tr>
</tfoot>
</table>
</section>
<footer> </footer>
To delete that respective row on click of any "Delete" button, could you try using this
$(document).on('click', '.item button', function(){
$(this).parent().parent().remove();
});
Here is a Codepen
Another thing I noticed, what are you trying to do in your $('.itemType').on('change', function() ? Because as of now all you are doing is literally checking the value of the selected option to ITSELF which always obviously will be true.
you have to pass an element id which will be deleted from both customer's cart and selected row like this;
<tr class="item"><td><button data-id="1">Delete</button></td><td>New item</td><td></td><td></td><td></td><td><select name="" id=""><option value="">Iron</option><option value="">Copper</option><option value="">Wood</option></select></td>
jquery part:
$("tr.item button").click(function(){
var item_to_remove = $(this).attr("data-id");
var row = $(this).parent().parent();
$.ajax({
url: "url to cart handler for delete item",
data: "id="+item_to_remove,
type: "post",
success: function(data){
row.remove();
},
error: function(){
console.log("ajax req for delete failed");
}
});
});
For the deletion of rows I added checboxes.
PLUNKER
SNIPPET
table {
table-layout: fixed;
}
table,
td,
th {
border: 1px solid black;
}
.name,
.brand,
.color {
width: 10%;
}
.age,
.address,
.pay,
.qty,
.size {
width: 5%;
}
.cart th:first-of-type {
width: 2.5%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>PO</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<header>
</header>
<section id="I">
<table id='PO1' class="purchaseOrder">
<thead>
<tr>
<th class='name'>Name</th>
<th class='age'>Age</th>
<th class='address'>Address</th>
<th class='pay'>Pay</th>
<th>Cart</th>
</tr>
</thead>
<tbody>
<tr id='C1' class='customer'>
<td>Jon Doe</td>
<td>30</td>
<td>Earth</td>
<td>Credit</td>
<td>
<table class='cart'>
<thead>
<tr>
<th> </th>
<th class='brand'>Brand</th>
<th class='qty'>Qty</th>
<th class='size'>Size</th>
<th class='color'>Color</th>
</tr>
</thead>
<tbody>
<tr id='item1' class='item'>
<td>
<input class="chx" name="chx" type="checkbox">
</td>
<td>New Item</td>
<td></td>
<td></td>
<td>
<select name='color'>
<option value='black'>Black</option>
<option value='white'>White</option>
</select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button class="remItem" onclick='remItem(this)'>-</button>
</td>
<td colspan='3'></td>
<td>
<button class="addItem" onclick='addItem("itemTemplate", this)'>+</button>
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='3'></td>
<td>
<button class="addCustomer">Add Customer</button>
</td>
</tr>
</tfoot>
</table>
</section>
<footer>
<template id="cartTemplate">
<table class='cart'>
<thead>
<tr>
<th> </th>
<th class='brand'>Brand</th>
<th class='qty'>Qty</th>
<th class='size'>Size</th>
<th class='color'>Color</th>
</tr>
</thead>
<tbody>
<tr class='item'>
<td>
<input class="chx" name="chx" type="checkbox">
</td>
<td>New Item</td>
<td></td>
<td></td>
<td>
<select name='color'>
<option value='black'>Black</option>
<option value='white'>White</option>
</select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button class="remItem" onclick='remItem(this)'>-</button>
</td>
<td colspan='3'></td>
<td>
<button class="addItem" onclick='addItem("itemTemplate",this)'>+</button>
</td>
</tr>
</tfoot>
</table>
</template>
<template id='itemTemplate'>
<tr class="item">
<td>
<input class="chx" name="chx" type="checkbox">
</td>
<td>New Item</td>
<td></td>
<td></td>
<td>
<select name="color">
<option value="black">Black</option>
<option value="white">White</option>
</select>
</td>
</tr>
</template>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(".addCustomer").on('click', function(e) {
var newCustomer = $('.customer:last').after('<tr class="customer"><td>New Customer</td><td></td><td></td><td></td></tr>');
var newCart = newClone('cartTemplate');
$('.customer:last').append(newCart);
e.preventDefault();
});
function newClone(id) {
var template = document.getElementById(id);
var clone = document.importNode(template.content, true);
return clone;
}
function addItem(id, origin) {
var newItem = newClone(id);
$(origin).closest('table').append(newItem);
}
function toggle(origin) {
var chxList = $(origin).closest('table').find('.chx:checked');
chkList.click(function() {
chkList.prop('checked', origin.checked)
})
}
function remItem(origin) {
var chxList = $(origin).closest('table').find('.chx:checked');
chxList.each(function(idx, obj) {
obj.closest('.item').remove();
});
}
</script>
</body>
</html>
I know that you got answer on your question, but I couldn't notice some bad patterns in your code. You probably heard for best practices phrase and how things needs to be done on right way. By that I want to give one suggestions. Avoid using HTML in Javascript code whenever it is possible because it makes the application less well-structured.
By that I want to introduce you to templates.
Example how can we optimize your code (from accepted answer):
Wrap everything form newItem variable in script tag and put somewhere in your body:
<script id="newItem-template" type="text/x-custom-template">
<tr class="item"><td><button>Delete</button></td>
<td>New item</td><td></td><td></td><td></td><td>
<select name="" id="" class="itemType"><option value="-1"></option>
<option value="i">Iron</option><option value="c">Copper</option>
<option value="w">Wood</option></select></td></tr>
</script>
Browser will simply ignore this, until you call html() method to return that content.
So instead of this:
var newItem = $('<tr class="item"><td><button>Delete</button></td><td>New item</td><td></td><td></td><td></td><td><select name="" id="" class="itemType"><option value="-1"></option><option value="i">Iron</option><option value="c">Copper</option><option value="w">Wood</option></select></td></tr>');
In your javascript file you will have only this:
var newItem = $('#newItem-template').html();
Here is optimized working code: jsFiddle
This is jQuery way to manage with templates, but there is powerful template engines if your project get bigger:
JavaScript templating engines

How to pass text from view to javascript

Hi there i have problem with Rails & Javascript. Here is my table in view.
<table>
<thead>
<tr>
<th>No</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr id="adminrow">
<td>
1
</td>
<td>
John
</td>
</tr>
<tr id="adminrow">
<td>
2
</td>
<td>
Alex
</td>
</tr>
<tr id="adminrow">
<td>
3
</td>
<td>
Paul
</td>
</tr>
</tbody>
</table>
and my JS is
$('#select_name').click(function(event){
var username = $("#select_name").text();
console.log(username);
});
I have lot of names in my table, but JS printed first name in console. How can I print each name in the table to console?
You are creating in the each-loop N links (by the number of users) with the same select_name ID. Your javascript is confused, which one to choose. Try to add user id to your html select_name id and adjust your javascript accordingly. Same about your other id adminrow.
OR simply change your select_name to be a class and not id:
....
%a{:href=>"#", :class=>"select_name"}=u.firstname
....
$('.select_name').click(function(event){ ....
Ok, I am attaching the full code for you. For me it works just fine. E.g. prints just the name after clicking on the corresponding link:
<table>
<thead>
<tr>
<th>No</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="adminrow">
<td>
1
</td>
<td>
John
</td>
</tr>
<tr class="adminrow">
<td>
2
</td>
<td>
Alex
</td>
</tr>
<tr class="adminrow">
<td>
3
</td>
<td>
Paul
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$('.select_name').click(function(event){
var username = $(this).text();
console.log(username);
});
</script>

Categories

Resources