Example:
<table id ='table'>
<tr>
<td>1</td>
<td><select id='old' name='old'></select></td>
<td><select id='old2' name='old2'></select></td>
<td><div id='old3' name='old3'></div></td>
</tr>
</table>
How to change the value of id or name from select id ='old' to select id ='new' (for example) after deleting rows in javascript?
I have been trying all the methods like trying getElementById('old') = 'new' but not work, used replaceChild also not work (or maybe I put the wrong code, no idea).
Do you have other alternatives? (No JQuery, please).
Thanks.
You can use the setAttribute method to accomplish this
document.getElementById("old").setAttribute("id","new");
document.getElementById("new").setAttribute("name","new");
var sel = document.getElementById("old"); //Reference the element
sel.id = "new"; //set the id
try this :
document.getElementById("old").name = 'NewName';
alert(document.getElementById("old").name);
document.getElementById("old").id = 'Newid';
alert(document.getElementById("Newid").id);
its work for me.
I feel there is something inelegant going on here; if you told us more we'd be able to say the "right way" to do it. If you nevertheless have a very good reason to do what you're doing, merely call this snippet of code you have made all your changes. It will update all the elements in your rows to have the correct numbering.
var formElements = document.getElementById('table').getElementsByClassName('toUpdate');
for (var i=0; i<formElements.length; i++) {
var e = formElements[i];
e.id = 'new'+i;
}
There are quite a few variations on this if you didn't want to add a class="toUpdate ..." to each one. For example you were using regular form elements, you could iterate over the <form>'s elements. Or you could iterate through all the elements and pattern-match on the names or ids. Or if you are algorithmically generating this with javascript you could add each element to an array at the same time you add it to the DOM, for later use (like this update).
Related
My professor has a unique task that prevents us from using any JQuery or basically anything that isn't Javascript or HTML/CSS.
I have to, on a mouse click, update the value within a cell with some numeric value. I am new to Javascript and basically here is what I am working with.
<table id="score">
<tr>
<td> One's </td>
<td class="scoring" id="ones" onClick="inputScore()"> </td>
</tr>
</table>
What I want to do is click the cell with id=ones and insert a value of 50 with the function inputScore(). What is the best way to approach this using only Javascript? Thanks in advance.
Edit: Code ported from comments:
<script>
function inputScore() {
var x = 50;
document.getElementById("ones") = x;
}
</script>
You have correctly targeted the element with getElementById(), but you need to set its innerHTML property to modify the cell's contents.
function inputScore() {
var x = 50;
document.getElementById("ones").innerHTML = x;
}
You were very nearly there. In this case you could also use .innerText since you are not adding any additional HTML markup, only the number 50.
If you want, you might consider modifying this function to accept the new value as a parameter:
function inputScore(value) {
// Set the contents to value
document.getElementById("ones").innerHTML = parseInt(value, 10);
}
// Called as
inputScore(50)
As you learn, it is recommended to use the MDN documentation as your point of reference. Here is the documentation on .innerHTML.
I have a problem with replacing html elements.
For example, here is a table:
<table>
<tr>
<td id="idTABLE">0</td>
<td>END</td>
</tr>
</table>
(it can be div, span, anything)
And string in JavaScript:
var str = '<td>1</td><td>2</td>';
(It can be anything, 123 text, <span>123 element</span> 456 or <tr><td>123</td> or anything)
How can I replace element idTABLE with str?
So:
<table>
<tr>
<td id="idTABLE">0</td>
<td>END</td>
</tr>
</table>
Becomes:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>END</td>
</tr>
</table>
<!-- str = '<td>1</td><td>2</td>'; -->
<table>
<tr>
123 text
<td>END</td>
</tr>
</table>
<!-- str = '123 text' -->
<table>
<tr>
<td>123</td>
<td>END</td>
</tr>
</table>
<!-- str = '<td>123</td>' -->
I tried createElement, replaceChild, cloneNode, but with no result at all =(
As the Jquery replaceWith() code was too bulky, tricky and complicated, here's my own solution. =)
The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.
Here is the code
var str = 'item to replace'; //it can be anything
var Obj = document.getElementById('TargetObject'); //any element to be fully replaced
if(Obj.outerHTML) { //if outerHTML is supported
Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var
}
else { //if outerHTML is not supported, there is a weird but crossbrowsered trick
var tmpObj=document.createElement("div");
tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->';
ObjParent=Obj.parentNode; //Okey, element should be parented
ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to
ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str);
}
That's all
Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:
function replaceTargetWith( targetID, html ){
/// find our target
var i, tmp, elm, last, target = document.getElementById(targetID);
/// create a temporary div or tr (to support tds)
tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
/// fill that div with our html, this generates our children
tmp.innerHTML = html;
/// step through the temporary div's children and insertBefore our target
i = tmp.childNodes.length;
/// the insertBefore method was more complicated than I first thought so I
/// have improved it. Have to be careful when dealing with child lists as
/// they are counted as live lists and so will update as and when you make
/// changes. This is why it is best to work backwards when moving children
/// around, and why I'm assigning the elements I'm working with to `elm`
/// and `last`
last = target;
while(i--){
target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
last = elm;
}
/// remove the target.
target.parentNode.removeChild(target);
}
example usage:
replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );
demo:
http://jsfiddle.net/97H5Y/1/
By using the .innerHTML of our temporary div this will generate the TextNodes and Elements we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.
...either that or look to using jQuery and it's replaceWith method.
jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');
update 2012/11/15
As a response to EL 2002's comment above:
It not always possible. For example, when createElement('div') and set its innerHTML as <td>123</td>, this div becomes <div>123</div> (js throws away inappropriate td tag)
The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):
<table><tr>123 text<td>END</td></tr></table>
If you then take this string an inject it into the DOM, depending on the browser you will get the following:
123 text<table><tr><td>END</td></tr></table>
<table><tr><td>END</td></tr></table>
The only question that remains is why you would want to achieve broken HTML in the first place? :)
Using jQuery you can do this:
var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);
http://jsfiddle.net/hZBeW/4/
Or in pure javascript:
var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;
http://jsfiddle.net/hZBeW/1/
You would first remove the table, then add the new replacement to the table's parent object.
Look up removeChild and appendChild
http://javascript.about.com/library/bldom09.htm
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
Edit:
jQuery .append allows sting-html without removing tags: http://api.jquery.com/append/
Your input in this case is too ambiguous. Your code will have to know if it should just insert the text as-is or parse out some HTML tags (or otherwise wind up with bad HTML). This is unneeded complexity that you can avoid by adjusting the input you provide.
If the garbled input is unavoidable, then without some sophisticated parsing (preferably in a separate function), you could end up with some bad HTML (like you do in your second example... which is Bad, right?).
I'm guessing you want a function to insert columns into a 1-row table. In this case, your contents should be passed in as an array (without table, tr, td tags). Each array element will be one column.
HTML
<table id="__TABLE__"><tr><td></td></tr></table>
JS
using jQuery for brevity...
function insert_columns (columns)
{
var $row = $('<tr></tr>');
for (var i = 0; i < columns.length; i++)
$row.append('<td>'+columns[i]+'</td>');
$('#__TABLE__').empty(); // remove everything inside
$('#__TABLE__').append($row);
}
So then...
insert_columns(['hello', 'there', 'world']);
Result
<table id="__TABLE__"><tr><td>hello</td><td>there</td><td>world</td></tr></table>
If you need to actually replace the td you are selecting from the DOM, then you need to first go to the parentNode, then replace the contents replace the innerHTML with a new html string representing what you want. The trick is converting the first-table-cell to a string so you can then use it in a string replace method.
I added a fiddle example: http://jsfiddle.net/vzUF4/
<table><tr><td id="first-table-cell">0</td><td>END</td></tr></table>
<script>
var firstTableCell = document.getElementById('first-table-cell');
var tableRow = firstTableCell.parentNode;
// Create a separate node used to convert node into string.
var renderingNode = document.createElement('tr');
renderingNode.appendChild(firstTableCell.cloneNode(true));
// Do a simple string replace on the html
var stringVersionOfFirstTableCell = renderingNode.innerHTML;
tableRow.innerHTML = tableRow.innerHTML.replace(stringVersionOfFirstTableCell,
'<td>0</td><td>1</td>');
</script>
A lot of the complexity here is that you are mixing DOM methods with string methods.
If DOM methods work for your application, it would be much bette to use those.
You can also do this with pure DOM methods (document.createElement, removeChild, appendChild), but it takes more lines of code and your question explicitly said you wanted to use a string.
use the attribute "innerHTML"
somehow select the table:
var a = document.getElementById('table, div, whatever node, id')
a.innerHTML = your_text
I have the following jquery code to loop over 525 (I know, alot!) checkboxes:
var elements = $("#profile-list table tr input[type=checkbox].email-checkout:not(:checked)");
$.each(elements, function(i) {
$(elements[i]).attr('checked', 'checked');
});
UPDATE The html looks like this:
<table>
<tr>
<th>Name</th>
<th>Title</th>
<th>E-mail</th>
<th>Telephone</th>
<th id="email_check"><img src="check_black.png"/></th>
</tr>
<?php foreach ($this->profiles as $profile): ?>
<tr>
<?php echo $this->presentProfile($profile, 'list') ?>
</tr>
<?php endforeach; ?>
This basically loops over all profiles in the database and creates a table row for each profile, where the last table data includes a checkbox, which one can select to send email to. If the user clicks the table header with the id of "email_check" then the javascript code should kick in, and that's where Chrome fails.
I attach the event with the following code:
$("#email_check img").live('click', function() {
//my code
}
When I run this code in Firefox (mac), it goes smoothly but when I run it in Chrome (mac) it takes forever and ends up giving me the window where chrome offers me the option of killing the window, so basically it never completes this loop.
I've been trying to optimize this selector as much as I can, and since jquery 1.3, I understand that they switched from left to right to right to left selector, which basically means that I should try to make my right most selector as specific as I can. Can it be any more specific than I currently have?
Or is it the loop that just takes so long? I have tried switching from $.each to just a regular for() without a positive result.
Any tips or ideas how I can fix this?
Ingiber
I really don't think this is a selector issue at all.
Your selector is a valid selector for querySelectorAll, which means it will be extremely fast.
I tested the exact selector in Chrome on Mac against a table with 250 rows, and the result was instantaneous.
I'd guess that there's something else going on.
Try removing the table tr part of the selector. It isn't adding anything.
Try this:
// console.time("test");
var elements = $("#profile-list input[type=checkbox].email-checkout").get();
var len = elements.length;
for (var i = 0; i < len; i += 1) {
elements[i].checked = true;
}
// console.timeEnd("test");
(So, first we select all check-boxes that are of the class "email-checkout" and are inside the #profile-list element. Then we just set their checked property to true. I assume, this is as fast as it can be.)
You could always give each check box a select/deselect event that will add/remove a class from the checkbox, then use the class as the selector.
You can use a .each() on the set to use the elements directly, like this:
$("#profile-list table tr input[type=checkbox].email-checkout").each(function() {
this.checked = true;
});
Also note the removal of :not(:checked) above...if you're going to check them all, that selector is more expensive that actually checking them anyway. More importantly is that this.checked = true; is tremendously cheaper than $(elements[i]).attr('checked', 'checked'); which happens every time.
Did you profile this? What is taking too long, getting the elements or looping over them? The only way to really speed up code is to profile and fix the slow parts.
FWIW, I would try
var elements = $("#profile-list").find("input[type=checkbox].email-checkout").get();
...
and see what happens.
Add an onlclick on the checkbox
$("#profile-list input[type=checkbox].email-checkout").click(function() {
var obj = $(this);
obj.hasClass("checked") ? obj.removeClass("checked") : obj.addClass("checked");
});
s = $("input[type=checkbox].email-checkout.checked");
I am very new to jquery/javscript.
I have a simple question.
Lets say i have a tag like this:
<Table id="mytable" >
<Table>
And i want to add some rows to this table.
Then we do like:
$("#mytable").append("<tr><td>value</td></tr>");
//some thing like this may not be having the right syntax
Now my question is lets the id of the table is in a variable for example:
var table="mytable"; //which is coming from the back end
Now my using the "table" variable how can I append the row..?
Is that going to be
$("#"+table).append("<tr><td>value</td></tr>");//
Can some one help me out in this simple thing?
Thanks,
Swati
that's correct!
var tableId = 'myTable';
$('#' + tableId).append('your row');
will append whatever you put in the 'your row' to the table with the id 'myTable'
That's exactly how you would do it. The selector is only expecting a string, so any form of concatenation or string logic via ternary operators will do the trick. This is a very powerful feature of jQuery selectors.
Yes, you can reference an ID like that by storing a variable in advance. This would append table rows/cells. You may need to dig deeper between the rows and cells depending on what you need to do though. :)
$(document).ready(function () {
var table = "myTable";
$("#" + table).append("<tr><td>row1</td><tr>");
});
<td> <input type="button" name="buton" id="x2" value="2" onclick="swap(id)";/> </td>
This is the button in a table when it is clicked it's id is passed as parameter to function "swap" as below:
function swap(x)
{
document.write(x);
}
It is successful in getting the id but not the value;when i am trying in this way:
function swap(x)
{
document.write(x.value);
}
The output is shown as undefined. Can you tell me how to get the cell value using the cell id?
I believe that what you are looking for is document.getElementById(x).value;
Also if you want the button just pass this to the function like this:
<button onclick="foo(this)"/>
I guess use jQuery for the purpose,it allows to traverse in DOM very easily.
<table id="mytable">
<tr><th>Customer Id</th><th>Result</th></tr>
<tr><td>123</td><td></td></tr>
<tr><td>456</td><td></td></tr>
<tr><td>789</td><td></td></tr>
</table>
If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:
$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
}
Essentially this is the same as the other solutions (possibly because I copypasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a < span >, provided you keep the class attribute with it.
By the way, I think you could do it in one selector:
$('#mytable .customerIDCell').each(function()
{
alert($(this).html());
});
If that makes things easier
Code will be more or less more reliable on cross bowser issue
z = document.getElementById(id); first, and then you should be able to use z.firstChild.textContent
You need to get the cell using var cell = document.getElementById(x). Then use cell.firstChild.nodeValue.
function swap(x)
{
var cell = document.getElementById(x);
document.write(cell.firstChild.nodeValue);
}
EDIT: Tested this on both FF3.5 and IE8 and it works.
If you are passing the id of the element you might want to use document.getElementById(x) to access it.