Just looking for the best practise way of doing this.
I have a table listing information and in the last column is a button with "Edit/View". When the user clicks on the button a div area appears with more information which can be edited
Code below with some fragments of jstl
<script type="text/javascript">
//Click on Edit/View on table
$('.viewCustomer').click(function()
{
.......
});
</script>
<tr class="odd">
<td>${customerBean.comName}</td>
<td>${customerBean.comCode}</td>
<td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>
So my question would be:
(1) how do i pass a variable to function $('.viewCustomer').click(function()
(2) is this the best way of going about to do this. Is there a more efficient/secure/cleaner of doing this?
Cheers
Alexis
The click function will not be called by you. It is called when the button is clicked, and as such has the event object passed to it:
$('.viewCustomer').click(function(evt){
.......
});
What exactly are you wanting to pass? You can access the DOM element that you are clicking using this and $(this), so maybe it possible to reference what you want from here.
EDIT For comment
if the user clicked on the button that
was in the 4th row of the table and in
that row the another colum had
customer id 1234 i want to pass the
variable 1234.
NOTE: None of the below has been tested, but ought to suffice
Let's assume your 'customer id' column has a classname of 'customerid'. So your HTML might be:
<tr class="odd">
<td>${customerBean.comName}</td>
<td class="customerid">${customerBean.comCode}</td>
<td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>
The jQuery might look something like:
$('.viewCustomer').click(function(){
var $buttonCell = $(this).parent(); //the <td> containing the button
var $buttonRow = $buttonCell.parent(); //the <tr> containing the button and your customer id
var $customerIdCell = $buttonRow.find("td.customerid");
var customerId = $customerIdCell.text();
});
The above is proken down into lines to show you how stuff is being retrieved. Using 'chaining' we can express it more concisely:
$('.viewCustomer').click(function(){
var customerId = $(this).parent().parent().find("td.customerid").text();
}
You can also search for the customerid cell as a 'sibling' of the button cell for an even more concise approach (and one less function call).
$('.viewCustomer').click(function(){
var customerId = $(this).parent().siblings("td.customerid").text();
}
Related
I am programmatically populating options to increase and decrease the value of an element and store the same in the DB table. To get a better idea, consider the following example:
<tr>
<td id="name_1">Element 1</td>
<td>increase icon</td>
<td>decrease icon</td>
</tr>
<tr>
<td id="name_2">Element 2</td>
<td>increase icon</td>
<td>decrease icon</td>
</tr>
<tr>
<td id="name_n">Element n</td>
<td>increase icon</td>
<td>decrease icon</td>
</tr>
Whenever I click any among the n increase / decrease icon, I need to access the value of #name_n. For which, I wrote the following function:
$(".increase").click(function(){
var id = $(this).attr('id'); //get the id of the element that was clicked.
console.log(id);
var arr = id.split("_"); //split to get the number
var no = arr[1]; //get the number
var name = $("#name_"+no).text(); //get the required value in name_n
console.log(name);
});
//replica for decrease class as well.
Problem :
Every time I click any increase icon, in my console, I'm getting id as inc_1 only! So, the value of name is Element 1 always. Same happens with click function for .decrease.
I have tried with the following ways to get the id:
var id = this.id;
var id = $(this).get(0).id;
var id = $(this)[0].id;
But nothing changed. The same problem persists. What's wrong and how do I resolve this?
Your code looks correct at first glance. Maybe there is some issue with rendering, perhaps the elements really get the same ID.
However, I would recommend a different approach for this task, without using ID's. You can achieve your goal by referencing the TD element relatively to the clicked increase/decrease button. I mean something like this.
$(".increase").click(function(){
var $td = $(this).closest("tr").children(":eq(0)"); //get the TR's first TD
var name = $td.text(); //get the required value in name_n td
console.log(name);
});
You could add a more generic class on the elements you wish tou target after the click(currently #name_n) and use the .closest and .siblings methods.
html
<tr>
<td id="name_n" class="target">Element n</td>
<td>increase icon</td>
<td>decrease icon</td>
</tr>
js
$(".increase").click(function(){
var name = $(this).closest('td').siblings('.target').text();
console.log(name);
});
Here is a working demo https://jsfiddle.net/0hru2jtx/
I have a dynamically generated tables the foot of the table contain some text fields when click on save i want to add the value of text fields to the body of that table .
here is the table
<table border="1" class="entity_table">
<tfoot>
<tr>
<td>
<div class="pane1"></div>
<div class="pane2">
<input type="text" id="name"><br>
<select id="data">
<option value="1">int</option>
<option value="2">tinyint</option>
</select>
<br><span id="save">save</span>
</div>
</td>
</tr>
</tfoot>
<tbody class="table-body" id='myid'></tbody>
</table>
i did this but this is id specific ..i want to update that specific table on which it is clicked and edited .
var myName = document.getElementById("name");
var data = document.getElementById("data");
var Mtable = document.getElementById("myid");
var rowCount = Mtable.rows.length;
var mrow = Mtable.insertRow(rowCount);
var mcell = mrow.insertCell(0);
mcell.innerHTML = myName.value;
var mcell1 = mrow.insertCell(1);
mcell1.innerHTML = size.value;
i want to update each dynamically generated table with values that is entered in its table's foot section
You can use below jQuery :
$(function(){
$('#save').click(function(){
$(this).closest('table').find('tbody').append('<tr><td>'+$('#name').val()+' and '+$('#data').val()+'</td></tr>');
});
});
Demo
EDIT - to eliminate input and select box id dependency use below code :
$(function(){
$('#save').click(function(){
var name = $(this).closest('tr').find('input[type=text]').val();
var data = $(this).closest('tr').find('select').val();
$(this).closest('table').find('tbody').append('<tr><td>'+name+' and '+data+'</td></tr>');
});
});
Demo
So if I understood this right, you dont want to use element's ID to select it.
You have some else options if you dont want to work with elements IDs:
1) You can add them some data- attribute, for example: data-id. And based on this you select your element like this:
myElement.querySelector("[data-id='X']") where myElement is some parent element of your tables and X is their ID which you generated before (lets say it will start from 0 and will increment with every next table).
2) If possible, work with objects. When you create your tables, you either create them with raw text with defining html elements or you create new elements with calling createElement("table") on document keyword. If second option is your option, you can save this elements to some array (myTables in this case) and then approach this elements in a standard way - lets say:
myTables[0].getElementsByTagName("input")
Hope it helps your issue. Hope I understood issue you were asking about.
I am trying to create a prepopulated form that pulls values from any selected row in a HTML table . The HTML page is populated by a JSP .
my table looks like this
<table id="data-table" id="test">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>value4</th>
</tr>
</thead>
<tbody>
<tr>
<td id="class1"><%= value.valueOne() %></td>
<td id="class2"><%= value.valueTwo() %></td>
<td id="class3"><%= value.valueThree() %></td>
<td id="class4"><%= value.valueFour() %></td>
</tr>
<%
}
%>
</tbody>
</table>
I want to obtain a prepopulated form with the row values on click of a particular row . I have some js code that does this .
$(document).on("click", ".data-table .class1", function(e) {
var value = $(this).closest('tr').val();
console.log(value);
// Just to check if I get the correct value
});
unfortunately I cannot understand how to get the values for that particular row from the DOM and populate it in a form , That I want to overlay over the table . I would appreciate any pointers . I really would have written more code but I dnt know Jquery and am stuck
Your general strategy should be this:
Populate the table on the server side: done
Have the form pre-existing in the page, but hidden with css (display:none)
Register a click listener on all tr elements to:
find the values inside each td within the tr
select the corresponding form inputs
populate the inputs using jQuery's val(value) function.
unhide the form if it's hidden
With this in mind, I would change your click listener from document to something like this. (Note: I'm assuming value.valueOne() are just numbers or strings, and don't contain any html.
//target just TR elements
$('tr').click(function(){
values = [];
$(this).children().each(function(){
//add contents to the value array.
values.push($(this).html())
});
//fill in the form values
populateForm(values);
});
Populate form would completely depend on your form's HTML, but to get you started here's an idea of what it might look like:
function populateForm(values){
//set the value of the input with id of name to the value in the first td.
$('#name').val(values[0]);
//show the form (id inputForm) now that it's populated
$('#inputForm').show();
}
A couple things are wrong with your html markup and your JQuery selector. You'll never be able to execute the code you've provided...
You have two 'id' parameters in this element, <table id="data-table" id="test">... This will work with the JQuery I've fixed below, but it's malformed html either way.
In your selector, you are using the syntax for finding an element based on it's css class attribute, however your elements in your HTML have those values set as 'id' attributes. Thus, this, $(document).on("click", ".data-table .class1", function(e) {... should be written as follows, $(document).on("click", "#data-table #class1", function(e) {
Now, if you are attempting to get the values within all of the 'td' elements within a row, then all you really need to do is get the parent element of the 'td' that was clicked, and then get it's children. Then, for each child, get their values.
Like this...
$(document).on("click", "#data-table #class1", function(e) {
var elements = $(this).parent().children();
$.each(elements, function(index, el){
alert($(el).html());
});
});
I've saved a JSFiddle for you to see this in action... http://jsfiddle.net/2LjQM/
val() is used to return value of form inputs. You are using it to try to get the value of a row and row has no value.
Without seeing what your output into the TD as html, I assume it is a form control
Try
$(document).on("click", ".data-table .class1", function(e) {
var value = $(this).find(':input').val(); // `:input pseudo selector wull access any form control input,select,textarea
console.log(value);
// Just to check if I get the correct value
});
EDIT: if the TD contains text
var value = $(this).text();
Instead of scraping the DOM, you could invert the logic, and build the rows using javascript instead. Check out this jsBin to see the solution in action: http://jsbin.com/aligaZi/2/edit?js,output
Start with an empty table:
<table class="data-table" id="test">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>value4</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Since you need to fill a form with the data, I'll be using a simple one as an example:
<form class="data-form">
<label>Value1<input class="value1" /></label>
<label>Value2<input class="value2" /></label>
<label>Value3<input class="value3" /></label>
<label>Value4<input class="value4" /></label>
</form>
Then, on the javascript side:
$(function() {
// Interpolate the values somehow.
// I'm not familiar with JSP syntax, but it shouldn't be too hard.
// I will use dummy data instead.
var tableData = [
{
value1: "row1-v1",
value2: "row1-v2",
value3: "row1-v3",
value4: "row1-v4"
}, {
value1: "row2-v1",
value2: "row2-v2",
value3: "row2-v3",
value4: "row2-v4"
}
];
// For each object, create an HTML row
var rows = $.map(tableData, function(rowData) {
var row = $("<tr></tr>");
row.append($('<td class="class1"></td>').html(rowData.value1));
row.append($('<td class="class2"></td>').html(rowData.value2));
row.append($('<td class="class3"></td>').html(rowData.value3));
row.append($('<td class="class4"></td>').html(rowData.value4));
// When this row is clicked, the form must be filled with this object's data
row.on("click", function() {
fillForm(rowData);
});
return row;
});
$(".data-table").append(rows);
function fillForm(rowData) {
var form = $(".data-form");
form.find("input.value1").val(rowData.value1);
form.find("input.value2").val(rowData.value2);
form.find("input.value3").val(rowData.value3);
form.find("input.value4").val(rowData.value4);
}
});
AIM
I'm trying to create a form that lets users select an item, and then displays the item's details once the user has selected an item. However, before i do that, i am trying to test if it would be possible by creating a simple testpage which replaces the item details to be displayed with a simple alert
Code(JQuery):
<!--Function to display item details upon selection-->
<script type="text/javascript">
function LoadDetails(cat,subcat,item)
{
return function(){
alert("Values are passed through successfully.Category is"+cat+", subcategory is"+subcat+"and item is"+item);
}
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#itemsubcat").hide();
$("#item").hide();
$("#submititem").hide();
$("#itemcat").load("getcategory.php");
$("#itemcat").change(function(){
var cat=$("#itemcat").val();
$("#itemsubcat").show();
$("#itemsubcat").load('getsubcategory.php?cat='+cat);
});
$("#itemsubcat").change(function(){
var cat=$("#itemcat").val();
var subcat=$("#itemsubcat").val();
$("#item").show();
$("#item").load('getitem.php?cat='+cat+'&subcat='+subcat);
});
$("#item").change(function(){
$("#submititem").show();
});
var cat=$("#itemcat").val();,
var subcat=$("#itemsubcat").val();,
var item=$("#item").val();,
$("#submititem").bind('click',{param:cat,subcat,item},LoadDetails);
});
});
</script>
Code(Html):
<table>
<tr>
<td><select id="itemcat" /></td>
<td><select id="itemsubcat" /></td>
<td><select id="item" /></td>
<td><input type="button" id="submititem" name="submititem" value="Get Item" /></td>
</tr>
</table>
Problem
When i click 'submititem', the alert pops up successfully, but the values cat,subcat and item are shown as undefined instead of the values that were supposed to be passed through.How would i pass data/values through to the function LoadDetails?
Solutions tried:
I've tried using .bind(), but to no avail.
E.g
var cat=$("#itemcat").val();,
var subcat=$("#itemsubcat").val();,
var item=$("#item").val();,
$("#submititem").bind('click',{param:cat,subcat,item},LoadDetails);
Question:
Would it be possible to use the function LoadDetails to retrieve the item details form my database(through PHP) and then echo it out ?
To pass a value to a function with an event, the syntax is :
$("#submititem").bind('click', LoadDetails(cat, subcat, item));
jsFiddle for exemple.
For your question, your code seems to be only client-side but if you want to load data from your server I suggest you to read this learn jQuery ajax
To get the values selected in the drop downs, you can just do this:
function LoadDetails()
{
var cat=$("#itemcat").find(":selected").text();
var subcat=$("#itemsubcat").find(":selected").text();
var item=$("#item").find(":selected").text();
alert("Values are passed through successfully.Category is"+cat+", subcategory is"+subcat+"and item is"+item);
}
This is strictly client-side, it doesn't talk to the server.
Sorry for the vague title, couldn't think of how to title my question. So I've made a html/css table wherein I placed an edit button for each row. Pressing the button would transform a certain text field into a text-input field there by allowing the user to edit the data inside; at the same time the edit button then transforms to save button. After editing , the user then would press the save button and the text-input field would then revert back into a text field and the save button back to an edit button. But it's not entirely working
This is my problem, after editing the data inside, upon pressing the save button, the data inside is deleted and replaced with: <input type= and outside the text-input field is: " />
and the save button remains as is, a "SAVE" button and not back to an "EDIT" button
here's the script:
$(document).ready(function () {
// listen for email edit button click
$("button#edit").on('click', function () {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
alert(email);
// change button from edit to save
$(this).attr('id', 'save-email').html('SAVE');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="' + email + '" />');
});
// listen for email save button click
$("button#save-email").on('click', function () {
// get new email inline to this save button
var newEmail = $(this).parents('tr').find($('input#user-email')).val();
alert(newEmail);
// change input field back to display
$(this).parent().siblings('td.email').html(email);
// change button from save to edit
$(this).attr('id', 'edit').html('EDIT');
});
});
sorry for the wall of text.
try to put it this way :
$(document).on('click',"button#save-email", function() {...
instead of
$("button#save-email").on('click', function()
using the second one won't work, because when it is run, $("button#save-email"), doesn't exist yet.
The problem is that the first handler is the only one attached in script.
Your javascript code is executed when the page is ready.
At that moment only the first handler is attached because there is not yet an element button#save-email. When you click save, it is the first handler that is executed again, not the one think !
Why don't you create two distinct buttons and show one or the other ?
<table>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
</table>
Javascript
// listen for email edit button click
$('.btn-edit').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get email inline to this edit button
var email = $this.parent().siblings('td.email').html();
// change button from edit to save
$parentRow.find('.btn-edit').hide();
$parentRow.find('.btn-save').show();
// change email display to input field
$(this)
.parent()
.siblings('td.email')
.html('<input type="text" id="user-email" value="'+email+'" />');
});
// listen for email save button click
$('.btn-save').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get new email inline to this save button
var newEmail = $(this).parent().siblings('td.email').find('#user-email').val();
// change input field back to display
$(this).parent().siblings('td.email').html(newEmail);
// change button from save to edit
$parentRow.find('.btn-edit').show();
$parentRow.find('.btn-save').hide();
});
DEMO
Take a look at KnockoutJS, which utilizes nice Bindings helping you to do things like that much easier. Here is an example of an editable grid with KnockoutJS
KnockoutJS Editable Data example
Neat & Works
<table>
<tr>
<td>some text</td>
<td><input type='button' value='edit' id='btn'/></td>
</tr>
</table>
$(document).ready(function() {
$("#btn").click(function() {
var $btn=$(this);
var opn= $btn.val()
switch(opn){
case 'edit':
var $td=$(this).parent().parent().find('td:first');
var email=$td.html();
$td.html("").append('<input type="text" value="'+email+'">');
$btn.val("save");
break;
case 'save':
var $input=$(this).parent().parent().find('td:first input');
var email=$input.val();
$input.parent().html(email);
$btn.val("edit");
break;
}
});
});
http://jsfiddle.net/h55rc/