Javascript Switch Statement to fill a table - javascript

I am trying to create a table to log in stress level through the click of a button which leads to a prompt, i got the first line to work and it fills in the table but i don't know how to take it to the next line because if the button is clicked again the input for the prompt refreshes and prints in the same cell. I hope that makes sense i'm quite new in coding so forgive me if i dont make sense.
here is my HTML code followed by the JavaScript;
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="project.html">Occupational Stress Monitor</a>
<form class="form-inline">
<button id= "record-button" class="btn btn-md btn-light" type="button" data-toggle="tooltip" data-placement="top" title="Click Here to Record Stress">Record</button>
</form>
</div>
</nav>
<h1>Stress Log</h1>
<table>
<tr>
<th class="heading">Day of the Week</th>
<th class="heading">Stress Level</th>
<th class="heading">Cause of Stress</th>
</tr>
<tr>
<td>Monday</td>
<td id="Monday"></td>
<td id="stressor1"></td>
</tr>
<tr>
<td>Tuesday</td>
<td id="Tuesday"></td>
<td id="stressor2"></td>
</tr>
<tr>
<td>Wednesday</td>
<td id="Wednesday"></td>
<td id="stressor3"></td>
</tr>
<tr>
<td>Thursday</td>
<td id="Thursday"></td>
<td id="stressor4"></td>
</tr>
<tr>
<td>Friday</td>
<td id="Friday"></td>
<td id="stressor5"></td>
</tr>
</table>
Javascript:
var record = document.getElementById("record-button");
var person = ["Good", "Ok", "Bad"];
record.onclick = function () {
var person = prompt ("How are you feeling today?-Good,Ok or Bad");
document.getElementById("Monday").innerHTML = person;
if (person !== "Good") {
var cause = prompt ("What is causing your stress?");
document.getElementById("stressor1").innerHTML = cause;
}
}

You can do it something like this
What i have done is.
Used a variable array called days which have all the days and one variable called last to keep track of which day is inserted before the current click event.Than in the onclick function every time i am selecting the current clicked day from array and updating last by 1.
var record = document.getElementById("record-button");
var person = ["Good", "Ok", "Bad"];
var days = ["Monday","Tuesday","Wednesday","Thursday","Friday",]
var last = 0;
record.onclick = function (){
if(last < 5)
{
var person = prompt ("How are you feeling today?-Good,Ok or Bad");
document.getElementById(`${days[last]}`).innerHTML = person;
if (person !== "Good"){
var cause = prompt ("What is causing your stress?");
document.getElementById(`stressor${last+1}`).innerHTML = cause;
}
last++
}
}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="project.html">Occupational Stress Monitor</a>
<form class="form-inline">
<button id= "record-button" class="btn btn-md btn-light" type="button" data-toggle="tooltip" data-placement="top" title="Click Here to Record Stress">Record</button>
</form>
</div>
</nav>
<h1>Stress Log</h1>
<table>
<tr>
<th class="heading">Day of the Week</th>
<th class="heading">Stress Level</th>
<th class="heading">Cause of Stress</th>
</tr>
<tr>
<td>Monday</td>
<td id="Monday"></td>
<td id="stressor1"></td>
</tr>
<tr>
<td>Tuesday</td>
<td id="Tuesday"></td>
<td id="stressor2"></td>
</tr>
<tr>
<td>Wednesday</td>
<td id="Wednesday"></td>
<td id="stressor3"></td>
</tr>
<tr>
<td>Thursday</td>
<td id="Thursday"></td>
<td id="stressor4"></td>
</tr>
<tr>
<td>Friday</td>
<td id="Friday"></td>
<td id="stressor5"></td>
</tr>
</table>

You can use querySelector to achieve that behaviour.
var record = document.getElementById("record-button");
var recordIndicator = ["Good", "Ok", "Bad"];
var cellCounter = 2
record.onclick = function (){
var person = prompt ("How are you feeling today?-Good,Ok or Bad") ;
document.querySelector(`table tr:nth-child(${cellCounter}) td:nth-child(2)`).innerHTML = "person";
var cause = prompt ("What is causing your stress?");
document.querySelector(`table tr:nth-child(${cellCounter}) td:nth-child(3)`).innerHTML = "cause";
cellCounter++;
}
I have used String literals to use the cellCounter variable inside querySelector.
To learn more about String literals and query Selector you can visit respective links.
Happy coding :)

Related

Get all values from URL with no name textarea

I want to get all fields data separately from the table. as the table is dynamically created so main problem is newly created one.
Please check out:
I tried to get all fields using Javascript, but I still can't get values of newly created rows. Please check out the screenshot of Javascript method result:
I want to get all fields of table values, including newly created values too..so that I can post the data and access data using URL and post it in database
Here is my HTML :
<table id="items">
<tr>
<th>Item</th>
<th>Description</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td class="item-name">
<div class="delete-wpr"><textarea name="invoice_item[]">Web Updates</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div>
</td>
<td class="description"><textarea name="description[]">Monthly web updates for http://widgetcorp.com (Nov. 1 - Nov. 30, 2009)</textarea></td>
<td><textarea class="cost" name="unit_cost[]">$650.00</textarea></td>
<td><textarea class="qty" name="quantity[]">1</textarea></td>
<td><span class="price">$650.00</span></td>
</tr>
<tr class="item-row">
<td class="item-name">
<div class="delete-wpr"><textarea name="invoice_item[]">SSL Renewals</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div>
</td>
<td class="description"><textarea name="description[]">Yearly renewals of SSL certificates on main domain and several subdomains</textarea></td>
<td><textarea class="cost" name="unit_cost[]">$75.00</textarea></td>
<td><textarea class="qty" name="quantity[]">3</textarea></td>
<td><span class="price">$225.00</span></td>
</tr>
<tr id="hiderow">
<td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Subtotal</td>
<td class="total-value">
<div id="subtotal">$875.00</div>
</td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value">
<div id="total">$875.00</div>
</td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Amount Paid</td>
<td class="total-value"><textarea id="paid">$0.00</textarea></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">Balance Due</td>
<td class="total-value balance">
<div class="due">$875.00</div>
</td>
</tr>
</table>
My Javascript code :
function myFunction() {
let QueryString = '';
var formFields = document.querySelectorAll('textarea');
formFields.forEach(function(textarea) {
//creates querystring for the form inputs
QueryString += textarea.name + '=' + textarea.value + '&';
//show the value of the textarea
console.log(textarea.value);
});
//remove the extra "&" from the end of the querystring
QueryString = QueryString.substr(0, QueryString.length - 1);
console.log("==FOR USING AS QUERY STRING FOR====");
// window.location.href = "index.php?name=" + QueryString;
alert(QueryString);
}
By newly created rows do you mean rows created after the page has loaded?
If so why don't you play around with
const formFields = [].slice.call(document.querySelectorAll('textarea'));
let AllValues = "";
formFields.forEach(formField => formField.addEventListener("input", yourFunction, false));
function yourFunction() {
AllValues += `${event.target.name}=${event.target.value}&`;
console.log(AllValues);
}
note: I'd target the id of the form otherwise all the textareas will be targetted...

Getting html control value using javascript function

I have this table in my page that I fetch by using AJAX request.
<table>
<tbody>
<tr>
<th>No</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Example Name 1</td>
<td class="text-center">
<div class="btn-group" role="group" aria-label="">
<a href="javascript:;" onclick="deleteParticipantFunction()" class="delete-participant" value="2">
Delete
</a>
</div>
</td>
</tr>
<tr>
<td>2</td>
<td>Example Name 2</td>
<td class="text-center">
<div class="btn-group" role="group" aria-label="">
<a href="javascript:;" onclick="deleteParticipantFunction()" class="delete-participant" value="1">
Delete
</a>
</div>
</td>
</tr>
</tbody>
</table>
So I'm trying to get the anchor value when the button is clicked. So I make a function like this :
function deleteParticipantFunction(){
var result = confirm('You are about to delete this participant. Continue?');
if(result){
var participant_id = $(this).val();
console.log(participant_id);
}
};
But I'm not able to get the value. What is the correct way to fetch the value in the function?
Pass id direct to method:
<a href="javascript:;" onclick="deleteParticipantFunction(1)" class="delete-participant">
Then Yours js methods will be simpler:
function deleteParticipantFunction(participant_id){
var result = confirm('You are about to delete this participant. Continue?');
if(result){
//delete smth by id
}
};
Anchor elements don't have a value attribute. That's something one finds on form inputs. Instead, you can put the value in a data-* attribute:
<a href="javascript:;" onclick="deleteParticipantFunction()" class="delete-participant" data-participant="1">
Delete
</a>
And retrive it from the data() function:
var participant_id = $(this).data('participant');
Though, thinking about it, when calling the function like that, is this even the correct context? I guess I haven't had to try that in a while so I don't know off the top of my head. But fortunately you're already using jQuery, so why not just use jQuery? Rather than put the function call on every element in an onclick attribute, use jQuery to bind a function to the click event(s):
<a href="javascript:;" class="delete-participant" data-participant="1">
Delete
</a>
and:
$(document).on('click', '.delete-participant.', function () {
var result = confirm('You are about to delete this participant. Continue?');
if(result){
var participant_id = $(this).data('participant');
console.log(participant_id);
}
});
Which has the added benefit of de-cluttering your markup.
function deleteParticipantFunction(e){
var result = confirm('You are about to delete this participant. Continue?');
if(result){
var participant_id = this;
console.log(e.value);
//e.parentNode.parentNode.parentNode.remove()
}
};
<table>
<tbody>
<tr>
<th>No</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Example Name 1</td>
<td class="text-center">
<div class="btn-group" role="group" aria-label="">
<button href="javascript:;" onclick="deleteParticipantFunction(this)" class="delete-participant" value="2">
Delete
</button>
</div>
</td>
</tr>
<tr>
<td>2</td>
<td>Example Name 2</td>
<td class="text-center">
<div class="btn-group" role="group" aria-label="">
<button href="javascript:;" onclick="deleteParticipantFunction(this)" class="delete-participant" value="1">
Delete
</button>
</div>
</td>
</tr>
</tbody>
</table>

HTML - Get row Id by pressing a Button inside same row

Supposing I have an HTML Table and each row has Some data, an Update and a Delete Button. I want, by clicking on the Update Button, to retrieve every data THIS SPECIFIC ROW has. I have searched for other examples but they most of them just traversed through a column by using a column id and just printed every cell data they found. I need, upon pressing the update Button, to retrieve all the current cell data this row has. How can I do that?
JS Fiddle HERE
Could not properly indent code after trying for more than 30mins so I gave up
You can change your html button from:
<button type="button" class="btn btn-danger" onclick="getConfirmation();">Delete</button>
to:
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
^^^^
Adding the this keyword to the function you are passing the current button. Now, in order to get the corresponding row it's enough you use jQuery.closest():
var row = $(ele).closest('tr');
or with plain js .closest()
var row = ele.closest('tr');
For the update buttons you can add the click handler:
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
or with plain js .querySelectorAll():
document.querySelectorAll('#employees-table tbody button.btn.btn-warning').forEach.....
The jQuery snippet:
window.getConfirmation = function(ele){
var retVal = confirm("Are you sure you want to delete ?");
if( retVal == true ){
alert("User wants to delete!");
var row = $(ele).closest('tr');
row.remove();
return true;
}
else{
alert ("User does not want to delete!");
return false;
}
}
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
var row = $(this).closest('tr');
console.log('TR first cell: ' + row.find('td:first').text());
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Employees</h2>
<table id="employees-table" class="table table-hover table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Born</th>
<th>Country</th>
<th>Department</th>
<th class="text-center">Update Row</th>
<th class="text-center">Delete Row</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>John</td>
<td>vas#gmail.com</td>
<td>1976</td>
<td>USA</td>
<td>Michigan</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
<tr>
<td>2</td>
<td>Mark</td>
<td>Twain</td>
<td>va1122s#gmail.com</td>
<td>1965</td>
<td>England</td>
<td>London</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
</tbody>
</table>
</div>
As per Hossein Asmand comment (How can I do this using only Javascript?) a full js solution follows:
window.getConfirmation = function(ele){
var retVal = confirm("Are you sure you want to delete ?");
if( retVal == true ){
var row = ele.closest('tr');
console.log("User wants to delete: " + row.cells[0].textContent);
row.remove();
return true;
}
else{
console.log("User does not want to delete!");
return false;
}
}
document.querySelectorAll('#employees-table tbody button.btn.btn-warning').forEach(function(ele, idx) {
ele.addEventListener('click', function(e) {
var row = this.closest('tr');
console.log('TR first cell: ' + row.cells[0].textContent);
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<div class="container">
<h2>Employees</h2>
<table id="employees-table" class="table table-hover table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Born</th>
<th>Country</th>
<th>Department</th>
<th class="text-center">Update Row</th>
<th class="text-center">Delete Row</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>John</td>
<td>vas#gmail.com</td>
<td>1976</td>
<td>USA</td>
<td>Michigan</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
<tr>
<td>2</td>
<td>Mark</td>
<td>Twain</td>
<td>va1122s#gmail.com</td>
<td>1965</td>
<td>England</td>
<td>London</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
</tbody>
</table>
</div>
To to retrieve data in row after pressing button Update
<button type="button" class="btn btn-warning" onclick="getData(this)">
window.getData = function(val) {
let arr= [];
val.parentNode.parentNode.querySelectorAll('td').forEach(item=>{
if (item.getAttribute('class') != "text-center") {
arr.push(item.innerHTML)
}
},this)
console.log(arr); //["1", "John", "John", "vas#gmail.com", "1976", "USA", "Michigan"]
}
The answer from #gaetanoM will be the accepted one. If anyone wants a way not only to get only the id, but full row data, you may try this:
HTML CODE:
Change this:
<td>1</td>
<td>John</td>
<td>John</td>
<td>vas#gmail.com</td>
<td>1976</td>
<td>USA</td>
<td>Michigan</td>
to this:
<td class="table_id">23</td>
<td class="table_firstName">John</td>
<td class="table_lastName">John</td>
<td class="table_email">vas#gmail.com</td>
<td class="table_born">1976</td>
<td class="table_country">USA</td>
<td class="table_departmentId">Michigan</td>
JAVASCRIPT CODE:
Change this:
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
var row = $(this).closest('tr');
console.log('TR first cell: ' + row.find('td:first').text());
})
to this:
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
var id = $(this).closest('tr').find('.table_id').text();
console.log("Id = " + id);
var firstname = $(this).closest('tr').find('.table_firstName').text();
console.log("First Name = " + firstname);
var lastname = $(this).closest('tr').find('.table_lastName').text();
console.log("Last Name = " + lastname);
var email = $(this).closest('tr').find('.table_email').text();
console.log("Email = " + email);
var born = $(this).closest('tr').find('.table_born').text();
console.log("Born = " + born);
var country = $(this).closest('tr').find('.table_country').text();
console.log("Country = " + country);
var department = $(this).closest('tr').find('.table_departmentId').text();
console.log("Department = " + department);
})
See the results in THIS fiddle.
Thanks again to everyone who contributed in finding an answer!!!

use button to pass td data

I have a table that I want to give the user the ability to select. I added an button, value="Update", to the beginning of the row, and assigned an onclick value. My problem is that I want to send other items(in td>s on the same row) from the row to the function called by the button.
How do I get the information from the row the button is on? I would like to pass the "Name" and "Last Update Time" to the function the button calls. I tried using the following:
$("#Report input[name=btn_id]").closest('td').attr('text')
but it returns "undefined," which I am not surprised by, as I think this is due to it not knowing what row of the table to pull from.
Here is a view of the table:
Here is the code behind the table:
<table align="center" border="1" class="report" id="report">
<thead>
<tr>
<th width="75">Update</th>
<th width="500">Name</th>
<th width="50">Info</th>
<th width="100">location</th>
<th width="100">Last Update Time</th>
</tr>
</thead>
<tbody>
<tr class="parent" id="other_app">
<td align="center">
<input type="button" name="btn_id" value="Update" onclick="UpdateRec(d1)">
</td>
<td name="App_Name">Test1</td>
<td align="center">None</td>
<td align="center">Desktop</td>
<td align="center">2014-06-30 18:22:39</td>
</tr>
<tr class="parent" id="other_app">
<td align="center">
<input type="button" name="btn_id" value="Update" onclick="UpdateAppRec(d1)">
</td>
<td name="App_Name">Test1</td>
<td align="center">None</td>
<td align="center">Server</td>
<td align="center">2014-03-30 16:20:15</td>
</tr>
</tbody>
Any help would be appreciated.
Embrace the power of this.
Using:
onclick="UpdateRec(this)"
..in your function:
function UpdateRec(el) {
var targetRow = $(el).parents('tr')
...
}
Using this passes a reference to the clicked element. You can then use jQuery to select the parent table row. From there you can use .find() to select anything in that row.
Another way to do this would be to use HTML5 data- attributes on this button itself:
<input type="button" name="btn_id" value="Update" onclick="UpdateRec(d1)" data-appName="something" />
In the same function you can then use $(el).data('appName') to get the value directly without looking up values in other DOM elements.
//Add a click listener on all your buttons using event delegation
$('#Report').click(onUpdateButtonClicked, 'input[name=btn_id]');
function onUpdateButtonClicked() {
var rowValues = $(this)
.parent() //select parent td
.nextAll() //select all next siblings of that parent td
.map(function () { //loop through the tds, collecting their text value
return $(this).text();
}).get(); //return the result as an array
//do what you want with rowValues
}
I would suggest you to use common class for all update buttons with common click event handler.
Here is the fiddle: http://jsfiddle.net/jwet6z6x/
HTML:
<table align="center" border="1" class="report" id="report">
<thead>
<tr>
<th width="75">Update</th>
<th width="500">Name</th>
<th width="50">Info</th>
<th width="100">location</th>
<th width="100">Last Update Time</th>
</tr>
</thead>
<tbody>
<tr class="parent" id="other_app">
<td align="center">
<input class="updateBtn" type="button" name="btn_id" value="Update">
</td>
<td name="App_Name">Test1</td>
<td align="center">None</td>
<td align="center">Desktop</td>
<td align="center">2014-06-30 18:22:39</td>
</tr>
<tr class="parent" id="other_app">
<td align="center">
<input class="updateBtn" type="button" name="btn_id" value="Update">
</td>
<td name="App_Name">Test1</td>
<td align="center">None</td>
<td align="center">Server</td>
<td align="center">2014-03-30 16:20:15</td>
</tr>
</tbody>
Javascript:
$(".updateBtn").click(function(){
var name = $(this).parent().parent().find('td').eq(1).html()
var time = $(this).parent().parent().find('td').eq(4).html()
alert (name);
alert (time);
})
I would do as follow : http://jsfiddle.net/Lk91cpup/2/
<table>
<tr id="row_1">
<td>
<input type="button" id="btn_row_1" class="btn" value="Update">
</td>
<td id="text_row_1">Test1</td>
<td>None</td>
<td>Desktop</td>
<td >2014-06-30 18:22:39</td>
</tr>
<tr id="row_2">
<td>
<input type="button" id="btn_row_2" class="btn" value="Update">
</td>
<td id="text_row_2">Test2</td>
<td>None</td>
<td>Server</td>
<td>2014-03-30 16:20:15</td>
</tr>
</table>
And Javascript
$(document).ready(function(){
$(".btn").click(function(){
var id = this.id.substring(this.id.lastIndexOf("_") + 1);
alert($("#text_row_" + id).text());
});
});
<tr class="parent" id="other_app">
<td align="center">
<input type="button" name="btn_id" value="Update" onclick="UpdateRec(d1, 'Test1', 'None', 'Desktop', '2014-06-30')">
</td>
<td name="App_Name">Test1</td>
<td align="center">None</td>
<td align="center">Desktop</td>
<td align="center">2014-06-30 18:22:39</td>
</tr>
Since you have already written a javascript function call why not just include the things you need right?
This is simplier but not the best practise.

Dynamically creating an object using eval() JS

I am trying to dynamically create an object in javascript. Here is the JS code that I have written:
var table = $("#eidtPersonalInfoTbl");
var trs = table.find('tr');
var obj = { };
$(trs).each(function(index, row){
var field = $(row).find('td').eq(0).html();
var value = $(row).find('td').eq(1).html();
eval('obj.' + field + ' = ' + value );
});
And here is the HTML markup for the table:
<table class="table" border="1" id="eidtPersonalInfoTbl">
<tr>
<td class="span3 hidden-phone" > Name </td>
<td class="span5"> Name </td>
</tr>
<tr>
<td class="span3 hidden-phone"> Address</td>
<td class="span5"> Address </td>
</tr>
<tr>
<td class="span3 hidden-phone">Area</td>
<td class="span5"> Area</td>
<tr>
<tr>
<td class="span3 hidden-phone">Gender</td>
<td>Male</td> </tr>
<tr>
<td class="span3 hidden-phone" > Salutation </td>
<td class="span5"> Dr</td>
</tr>
<tr>
<td class="span3 hidden-phone">State</td>
<td class="span5"> State </td>
<tr>
<tr>
<td class="span3 hidden-phone">City</td>
<td class="span5"> City </td>
</tr>
<tr>
<td class="span3 hidden-phone" > Postel Code </td>
<td class="span5"> Postel Code </td>
</tr>
<tr>
<td class="span3 hidden-phone" > Phone# </td>
<td class="span5"> 04128741 </td>
</tr>
<tr>
<td class="span3 hidden-phone" > Mobile# </td>
<td class="span5"> 03218741525</td>
</tr>
<tr>
<td class="span3 hidden-phone" > Cover Letter </td>
<td>Cover letter goes here</td>
</tr>
<tr>
<td> <input type="submit" name="per-det" class="btn btn-success span5" value="Update and Cont."></td>
</tr>
Whenever I try to execute this, it gives me this error
Undefined variable Name
It's far easier, safer and faster to use this:
obj[field] = value;
... instead of eval('obj.' + field + ' = "' + value + '"'), which obviously has the same purpose.
You see what you see now because value should be wrapped in the quotation marks. For example, if both field and value are equal to 'Name' (string), the evalled expression as it stands now will look like...
obj.Name = Name
... obviously causing the 'Undefined variable Name' error.
Two sidenotes here. First, there's no sense wrapping trs in jQuery object again in this line...
$(trs).each(function(index, row)
... as it already IS a jQuery object (result of table.find('tr')). This redundancy is easier to see if you follow a simple convention: preceding names of all the variables that are used to store jQuery objects with $:
var $table = $("#eidtPersonalInfoTbl");
var $trs = $table.find('tr');
// ...
// $($trs) - obviously redundant
Second, it's a bit wasting to go through DOM twice in these lines:
var field = $(row).find('td').eq(0).html();
var value = $(row).find('td').eq(1).html();
I'd rather have it rewritten it like this:
var $tds = $(row).find('td');
var field = $tds.eq(0).html(); // or just $tds[0].innerHTML;
var value = $tds.eq(1).html(); // or just $tds[1].innerHTML;

Categories

Resources