Cannot append to node - javascript

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>

Related

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

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

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);
});
});

Jquery next() is not working

I have
<table class="prodtable">
<tr>
<td></td>
<td>
<input class="editok" value="2" />
</td>
<td>
<input name="prodnumber" value="1" />
<i></i>
</td>
</tr>
</table>
and this js
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = $(this).val();
$(this).parent('td').text(neuanzahl);//<-- till here works fine
$(this).parent('td').next().find('input').val(neuanzahl);//<-- from here, failure
$(this).parent('td').next().find('i').addClass('icon-pencil');
});
the editok input was inserted dynamically, thats why i am setting the handler from parent table.
my problem is, on blur event, the value of the given input should be put in the next input which is inside the next td with name prodnumger and the <i> should get the class icon-pencil.
I am trying for 1 hour now, what a shame.. not a single success. what am I doing wrong here?
This line
$(this).parent('td').text(neuanzahl);
replaces everything in the TD, as that's what text() does, it overwrites everything, so on the next line when you do
$(this).parent('td').next().find('input') ...
there is no this, you just removed it with text()
Just chaining instead of using multiple lines will keep the reference
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = this.value;
$(this).parent('td')
.text(neuanzahl)
.next('td')
.find('input')
.val(neuanzahl)
.next('i')
.addClass('icon-pencil');
});
FIDDLE
The minute you call $(this).parent('td').text(...), you've removed the input from its parent. So $(this).parent('td') in the following calls won't match anything.
Save that td at the start, and use it throughout:
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = $(this).val();
var td = $(this).parent('td');
td.text(neuanzahl);
td.next().find('input').val(neuanzahl);
td.next().find('i').addClass('icon-pencil');
});
Example: http://codepen.io/paulroub/pen/xHwdi
Solution is to store reference of next div in a variable.
$('.prodtable').on('blur', '.editok', function () {
var td = $(this).parent('td');
var next = $(this).parent('td').next(); //Store reference of next div in a variable
var neuanzahl = $(this).val();
td.text(neuanzahl);
next.find('input').val(neuanzahl);
next.find('i').addClass('icon-pencil');
});
Problem with your code is that when $(this).parent('td').text(neuanzahl) reference to this is lost as you have replaced the content to td.
Your table opening tag is not spelled correctly that is likely why you are having difficulties.

jquery adding table row with commented out html

I have a table and I want to add a new row to this table. I load html of the row from the server. Returned html has some other commented out html on the top. Because of that comment adding row doesn't work properly. jQuery removes <tr> and <td> tags and adds plain text from <td> elements. Is it a bug or expected behaviour?
<table id="tbl">
<tr><td>old1</td></tr>
<!-- <abc -->
<tr><td>old2</td></tr>
</table>
<input id="add" type="button" value="add"/>
JavaScript:
$("#add").click(function() {
$("#tbl tr:last").after("<!-- <abc --><tr><td>New</td></tr>");
});
fiddle
P.S. The issue is because of '<' in the comment. It works ok with normal comments. And it would also work with '<' if the comment was inserted into/from div elements rather than table/tr. What would be your suggestion to fix this issue without removing comment from the html on server-side.
You can simply remove comments by using regular expressions. Code(Demo on JSFiddle):
$("#add").click(function() {
var rawHTML = "<!-- <abc --><tr><td>New</td></tr>";
var HTMLToAdd = rawHTML.replace(/<!--[\s\S]*?-->/g, '');
$("#tbl tr:last").after(HTMLToAdd);
});
Shorter version:
$("#add").click(function() {
$("#tbl tr:last").after("<!-- <abc --><tr><td>New</td></tr>".replace(/<!--[\s\S]*?-->/g, ''));
});
Referring to my comment above - e.g. the below JS works...
$("#add").click(function() {
newRow = '<!-- <abc --><tr><td>New</td></tr>';
var newRow = newRow.replace('<!-- <', '<!-- ');
$("#tbl tr:last").after(newRow);
});
where the newRow is actually the data returned by your server call.
if you get always string like that and you don't want to have comment at all, you can strip it off
$("#add").click(function() {
var responseString = "<!-- <abc --><tr><td>New</td></tr>";
var index = responseString.indexOf("-->")+3;
var formatedString = responseString.slice(index);
$("#tbl tr:last").after(formatedString);
});

How to update label tag using jquery

I have the following HTML:
<div id="myDiv">
<table id="tbl0">
<tr id="tr0" style="display: none;">
<td>
<label id="lbl0"></label>
</td>
</tr>
<tr id="tr1" style="display: none;">
<td>
<label id="lbl1"></label>
</td>
</tr>
<tr id="tr2" style="display: none;">
<td>
<label id="lbl2"></label>
</td>
</tr>
</table>
</div>
And the following jquery that sets a row to visible and updates (but fails) the label tag with some text.
var myStr = $(this).text();
var myArr = myStr.split(',');
$.each(myArr, function (i) {
// This part works just fine
var tr = $('#myDiv').find("#tr" + i);
tr.css('display', 'inline');
// The label is found, but I can't get jquery to update the text of
// ...it no matter what I try
var lbl = tr.find("lbl" + i);
lbl.val('hello world'); // doesn't work
lbl.text('hello world'); // doesn't work
lbl.html('hello world'); // doesn't work
});
So what am I doing wrong here?
try this...
var lbl = tr.find("#lbl" + i);
You are trying to select a <lbl1/> tag, which obviously doesn't exist
use # to specify an id to search for.
You're wrong about the label being found, you need to use a # to specify that it is an id:
var lbl = tr.find("#lbl" + i);
Both:
lbl.text('hello world');
lbl.html('hello world');
are correct ways to set the text of the label, I prefer .html() since it doesn't parse the string from htmlspecialchars it might be slightly faster.
The error is in this line:
var lbl = tr.find("#lbl" + i);
You forgot # sign, since you are looking up by ID.
I stumbled upon this thread and while it helped lead me in the right direction I was able to solve a little different way once I found my label by setting the innerHTML property on the label element. I was using jQuery.
var labels = document.getElementsByClassName('someclassname');
$(labels).each(function (index, element) {
element.innerHTML = 'hello world';
});

Categories

Resources