jQuery: Cannot access text box value using .val() - javascript

I'm building a dynamic table that users can add to, delete from, or edit. I have the following:
$(document).on('click', '.edit_rule', function() {
// editable text boxes for name and description
$(this).closest("tr").find("td:nth-child(2), td:nth-child(3)").each(function() {
var html = $(this).html();
var input = $('<input type="text" />');
input.val(html);
$(this).html(input);
});
// replace Edit and Delete with Save and Cancel
$(".edit_rule").replaceWith("<input id='Button' type='button' value='Save' class='sav$
$(".delete_rule").replaceWith("<input id='Button' type='button' value='Cancel' class=$
});
Which all works fine. But, when I try to access the new values in the next boxes, the value comes up blank. I was trying to use .val() and now am trying .text() as follows:
$(document).on('click', '.save_edit', function() {
var $row = $(this).closest("tr");
var $name = $row.find("td:nth-child(2)").find('input');
console.log($name.text()); // prints empty string
});
I'm fairly new to Javascript, so is there some weird scope thing I'm not understanding that prevents the value from being accessed in a separate function? Is there another way to do it?
EDIT: Here is the corresponding HTML
<div id="customperms_table_container" style="height:655px;">
<table id="customperms_table_form" cellpadding="10" cellspacing="$
<caption></caption>
<thead>
<tr>
<th>#</th>
<th>Role Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

Issue is td has no value.
Solution is use .text() or .html() to get its text or html
Based on comment:
Your selector should be:
var $name = $row.find("td:nth-child(2)").find('input')// add class or id if there other inputs

Sorry about broken html, but combo of guradio and Haze fixed it.
var $name = $row.find("td:nth-child(3)");
console.log($name.val()); // <-- prints correct value

Related

Pass php variable through JavaScript to another php page

I want to pass the id to the next page on clicking the entire row.
I tried to do it myself but I wasn't able to do so .
my code is below :
$( "#tablerow" ).click(function() {
var jobvalue=$("#jobid").val();
alert(jobvalue);
window.location.href = "jobsview.php?id=" + jobvalue;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="tablerow">
<td><?=$srno?></td>
<td id="jobid"><?=$row['ID']?></td>
</tr>
</tbody>
</table>
val() method works for form elements like input, select etc.
Use text() method,
var jobvalue = $("#jobid").text();
Update
An HTML can have only one ID throughout the document. To enable click event for multiple elements and pass the one that is clicked onto another page, change ID attribute to class.
<table>
<tbody>
<tr class="tablerow" >
<td><?=$srno?></td>
<td class="jobid"><?=$row['ID']?></td>
</tr>
</tbody>
</table>
Then you can get the once clicked in JS as follows,
$( ".tablerow" ).click(function() {
/** $(this) will refer to current tablerow clicked
* .find(".jobid") will find element with class `jobid`
* inside currently clicked tablerow
*/
var jobvalue = $(this).find(".jobid").text();
alert(jobvalue);
window.location.href = "jobsview.php?id=" + jobvalue;
});

Cannot append to node

I have a the following html code in a table:
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
When I click the button, I would like to empty the td and add the text which is stored in a cookie. The td empties fine but I am unable to append the text. The text is in the variable as it is visible in the alert. I have used the code below to try and achive this, the commented out code is what I have tried and doesn't work.
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
//alert(hostname);
var trid = $(this).closest('tr').attr('id');
//alert(trid);
var olddesc = Cookies.get(hostname+','+trid+',description');
alert(olddesc);
$(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').append(olddesc);
// $(this).closest('tr').find('#description').text(olddesc);
// $(this).closest('td').text(olddesc);
// $('#'+trid+' td').each(function(){
// if($(this).attr('id') == 'description'){
// $(this).append(olddesc);
// }
// })
//$(document).find('#'+trid+' td#description').append(olddesc);
})
Can anyone please help me fix this or recommend a better way of doing it?
You can use .html() to add your dynamic data to HTML tag id
var olddesc = Cookies.get(hostname+','+trid+',description');
alert(olddesc);
// Create custom / dynamic HTML
var temp = `<p>` + olddesc + `</p>`;
$(this).closest('td').empty(); <----- THIS WORKS
// Edit: Use ID of html tag
$('#description').html(temp);
This shall work for you.
$(this).closest('td').append(olddesc); runs after you've removed this from the td, therefore the td is no longer an ancestor of this. You do not need to empty the td; simply set its text to olddesc and it will be automagically emptied as part of the process of setting its text.
// (REMOVE THIS) $(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').text(olddesc);
Just use .html
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
var olddesc = "Cokkies return"; //Cookies.get(hostname+','+trid+',description');
$(this).closest('td').html(olddesc); //<----- THIS WORKS
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
</tr>
</table>

Replace Key name array inputs jquery

I've got a strange question. We have buttons that have data attributes with an id in it. [v1, v2 and v3].
<table id="table-1" data-car-id="v1">
<tr><td>Header1</td></tr>
<tr><td>Content1 <input type="text" name="car[v1][marked][12]" /></td></tr>
<tr><td>Footer</td></tr>
</table>
<button id="copy-2" data-car-id="v2">Copy Table</button>
<table id="table-2">
</table>
<button id="copy-3" data-car-id="v3">Copy Table</button>
<table id="table-3">
</table>
A little piece of Javascript copies the body of the above table to closest next one. (That works).
$("button[id^='copy']").click(function() {
var $carId = $(this).attr('data-car-id');
alert($carId);
var $prevTable = $(this).prev("table[id^='table-']").prop('innerHTML');
var $nextTable = $(this).next("table").html($prevTable);
});
But now the tricky part, the input name of all inputs in that tbody should be replace. While the market should remain unchanged
car[v1][marked][12] => car[v2][marked][12]
How can I do that? Make it yourself easy and use the JSFiddle I created: https://jsfiddle.net/ra35z8ff/
After copying the HTML over to the next table element, select all the children input elements and iterate over them. Use the .replace() method to replace the previous table element's data-car-id attribute with the current button element's data-car-id attribute.
Updated Example
$("button[id^='copy']").on('click', function () {
var id = $(this).attr('data-car-id'),
previousId = $(this).prev('button').attr('data-car-id');
html = $(this).prev("table[id^='table-']").prop('innerHTML');
$(this).next("table").html(html).find('input').each(function () {
this.name = this.name.replace(previousId, id);
});
});

get jsonArray from table

I have a table and need to build json array. I need value from 1 and 4 column of table.
HTML
<table class="table table-striped" id="development_mapping">
<thead>
<tr>
<th>Visual Feature</th>
<th>Step</th>
<th>Output</th>
<th>Data Feature</th>
</tr>
</thead>
<tbody>
<tr><td>color</td>
<td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
<td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
<td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>
</table>
Here is my solution, a function to made an json array from table
JAVASCRIPT
var jsonArray = {};
$('#development_mapping').find('tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
I have done, but not understand, why I get " " from value of 4 column. I mean, why variable in variable is always getting " "
This is my DEMO
Your selector: $('#development_mapping').find('tr') is selecting all <tr> tags in the table. Even the one in the <thead>! The <thead> doesn't have <td> tags, so that's where the " " is coming from.
Try this:
$('#development_mapping').find('tbody tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
You are using .text() but there is no actual text in your 3rd td tag.
try this maybe?
variable : $(this).find('td:eq(3) input').val()
There are 2 problems with your code.
Remove the surrounding <tr> in your table head definition.
Use this to access input value
variable: $(this).find('td:eq(3) > input').first().val()
$.find() will return a collection and you'll need to get the first object of the collection for further use. Plus, you'll need to search for input inside the cell, not the cell itself.
Here is the working fiddle: http://jsfiddle.net/toshkaexe/7q3KP/

Is it possible to get the value of a <td> element using onclick?

I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')

Categories

Resources