I have html table on my parent page that has some data:
Begin Date End Date City
03/28/2017 Toronto
03/25/2017 03/26/2017 Miami
03/22/2017 03/24/2017 Chicago
03/16/2017 03/21/2017 Dallas
03/10/2017 03/15/2017 Austin
After use update the element from specific row I would like to replace entier content of that row. Each row had unique id. I have to do this with plain JavaScript Vanilla. Here is my example what I have so far:
fnObj.DATA is numeric and I get that after my ajax call is successfully completed. I use the id from that callback function to detect the row that I want to update. I'm not sure what is the best technique to replace all the td tags. This technique works with one exception. There is no id on the row that I have replaced the data. If anyone knows better way to do this please let me know. Thank you.
window.parent.document.getElementById("New_"+fnObj.DATA).outerHTML = "<td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>document.getElementById("newCity").value</td>";
window.parent.document.getElementById(dType+"_"+fnObj.DATA).id = 'New_'+fnObj.DATA;
Try this:
var newtr = "<tr id='" + "New_"+fnObj.DATA + "'><td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>" + document.getElementById("newCity").value + "</td></tr>";
$("#New_"+fnObj.DATA ).replaceWith(newtr);
If you don't want to use jquery you can use something like:
var currentTr = document.getElementById("New_"+fnObj.DATA), parent = currentTr.parentNode,
tempDiv = document.createElement('div');
tempDiv.innerHTML = "<tr id='" + "New_"+fnObj.DATA + "'><td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>" + document.getElementById("newCity").value + "</td></tr>";
var input = tempDiv.childNodes[0];
parent.replaceChild(input, currentTr);
Related
I have a table in HTML where the ID is dynamically generated from a row counter:
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>"
+ "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>"
+ "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>"
+ "</tr>"
I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input.
Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding:
$(#maxAltitude).prop("disabled", true);
How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed.
I've tried jQuery and javascript but can't seem to find a good way to do this:
<option onclick="shapeSelect()" value="sphere">Sphere</option>
<option onclick="shapeSelect()" value="cylinder">Cylinder</option>
function shapeSelect() {
var shapeSelects = document.getElementsByName("shapeSelect");
var maxAlts = document.getElementsByName("maxAlt");
for(var i = 0; i < shapeSelects.length; i++) {
switch(shapeSelects[i].value) {
case "sphere":
maxAlts[I].disabled = True;
break;
case "cylinder":
maxAlts[i].disabled = False;
}
}
}
With the above code I get: SyntaxError: unexpected token: identifier whenever shapeSelect() is fired.
I've modified the code as follows:
<table class="myTable" id="myTable"></table>
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option value=\"sphere\">Sphere</option>"
+ "<option value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude_" + rowCount + "\"</td>"
+ "<td><input class=\"maxAltitudeInput\" type=\"text\" id=\"maxAltitude_" + rowCount + "\" disabled></td>"
+ "</tr>"
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
And still nothing happens when I change the shape selector dropdown.
EDIT:
Apologies on the naming mismatches. My dev machine is on an airgapped network and I was hand jamming the post here on Stack Overflow. The rowCount variable was being created and incremented in another function. I was trying to only put relevant code in the post for brevity.
I was missing a class from shapeSelector. That was the missing link. It works now!
jQuery actually makes this really easy by binding this to whichever element triggered an event.
For instance, instead of writing a generic function for when that value changes, you could use jQuery to bind an event listener to them:
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
You'll notice a few things in this snippet:
The element we are binding the listener to is the table, not the individual row. That's because the row is dynamic, and we don't want to have to keep adding listeners every time we add a row. Instead we add it to the parent which is stable, but then we specify that we are interested in its children that match ".shapeSelector"
The listener relies on class names, not IDs, since we want to match multiple copies of them, not just a specific one. So you'd need to add those class names or a similar way of matching more than one item
Inside the callback function that runs, you'll notice a couple uses of this. jQuery has bound that to the element that triggered the event listener, in this case, the <select> control. So when we use this, we have to think of it from that perspective. We can get its value by $(this).val(), we can find its parentt with $(this).parent(), etc. In this case, I'm travelling up to the nearest tr, then from there down to that tr's input that I want to disable. You'd need to adjust a little depending on your dom.
Also note that this is a DOM element, not a jQuery result. That's why when we want to run more jQuery commands on it, we have to put it in $() again.
That's how I'd approach it. We don't have your entire code here, so you'll have to adjust a bit, but hopefully that pushes you off in the right direction.
EDIT
To be honest, there were a lot of naming mismatches and things that didn't line up. For instance, you were attempting to append onto a tbody tag, but that tag didn't exist. You were using a rowCount variable, but didn' ever set that up or increment it. The select tag sill didn't have the class name you were trying to use.
I suggest you look at your code piece by piece, ask yourself what you're telling the browser to do, and then do that instruction in your mind to make sure the computer can do it.
HTML:
<table class="myTable" id="myTable"><tbody></tbody></table>
JavaScript:
var rowCount = 0;
function addRow(){
$('.myTable tbody').append(`<tr name="tableRow">
<td>
<select class="shapeSelector" id="shapeSelect_${rowCount}">
<option value="sphere">Sphere</option>
<option value="cylinder">Cylinder</option>
</select>
</td>
<td><input type="text" id="altitude_${rowCount}" /></td>
<td><input class="maxAltitudeInput" type="text" id="maxAltitude_${rowCount}" disabled></td>"
</tr>`);
rowCount++;
}
$('.myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
});
addRow();
addRow();
addRow();
https://jsfiddle.net/32vnjq81/
I have HTML table. I get data from Firebase and append that data to my HTML table, with classes.
I'm trying to figure out how to select that appended data on my HTML and update values, because my values changes by time (I do some math with time).
I know the way to select using on.('click'), but I would like to select it and update it without any click events.
var frequency = snapshot.val().frequency;
var recordKey = snapshot.key;
var minsAway = frequency - (firstCurrentDiff % frequency);
var nextArrival = moment().add(minsAway, "minutes").format("HH:mm")
var row = $("<tr>").attr("class", recordKey);
row.appendTo("#tableBody");
$("<td>" + frequency + "</td>").appendTo(row);
$("<td>" + nextArrival + "</td>").appendTo(row);
$('<td class="mins-away">' + minsAway + "</td>").appendTo(row);
If i get what you need, after append, you can get it with :last
row.appendTo("#tableBody");
$myrow = $("#tableBody tr:last");
And then, for ex, refer to each td or find specific one:
$td_mins_away = $myrow.find('td.mins-away');
I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);
I'm using a very simple function to present within a table the name of a person and their age given by the user through a prompt window. The only problem I'm having is that whenever the user adds a second name and age, JS replaces the previous one. It won't add a second row.
http://jsbin.com/jamobifu
JS
function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");
/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}
HTML
<h1>Making A List</h1>
<p>This program will create a list based on two question which will be asked to you. Type the name of the person and their corresponding age. Output will be presented in a customized table.</p>
<input type="button" value="Create List" onclick="table()" />
<table id="tableOfPeople" style="width: 600px; margin-left: auto; margin-right: auto; margin-top: 50px; background-color: #74a9cb; color: white; border: 1px solid #127bbb"></table>
You shouldn't use innerHTML to modify the contents of a table as it will fail in versions of IE upto and including 9 at least (where innerHTML is readonly for a number of table related elements*). So you should be using DOM insertRow and insertCell methods (or createElement and appendChild, but the insert methods do two steps in one):
var row = document.getElementById("tableOfPeople").insertRow(-1);
var cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(name));
cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(age));
* MSDN::innerHTML property
The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.
You Forgot += instead =
function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");
/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}
Your problem is right here. Every time the user adds a new name you are replacing the old information instead of adding to it. Any time the innerHTML method is called on an element it will delete the old HTML information inside of the element.
document.getElementById("tableOfPeople").innerHTML = "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
What you could do is store this information to a variable and then add that with the new information.
Something along the lines of:
var information = document.getElementById("tableOfPeople").innerHTML;
document.getElementById("tableOfPeople").innerHTML = information + "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
This is because you are replacing the innerHTML with the new table row, not adding to it. You can solve this pretty easily by replacing
document.getElementById("tableOfPeople").innerHTML = "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
With:
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
The += operator adds to the existing value. For example, the following code:
a = 4;
a += 2;
alert(a); //alerts 6
As #cookiemonster pointed out, there are numerous caveats to this approach. The cost of using .innerHTML to alter the DOM is high and destructive. It requires the DOM to be parsed into a string, the string altered, then parsed back into the DOM. This process destroys any event listeners or other information you may have had on the elements.
It will also make things more difficult as you wish to extend the functionality of the code, to add things like the ability to delete rows.
#RobG has presented a much better solution, and as he points out .innerHTML can fail in various versions of IE.
I am having some trouble using the chosen.js plugin on my dropdown.There are a few related questions on here that I have worked through but still no luck on my code.
I have 4 dynamically created and populated select elements.
var dropdownArray = [];
function initDropdown() {
var id = "list";
var classy= "chzn-select";
var html = "";
for ( var idcount = 0; idcount < 4; idcount++) {
var dropdownHTML = "<select class=\""+classy+"\" id=\"" + id
+ "\" onchange= selectfunc(this) >" +
"<option selected=\"selected\">Make Selection... </option>" +
"</select>";
dropdownArray.push(id);
html += dropdownHTML;
id += "0";
}
$("#dropdowns").html(html);
$(".chzn-select").chosen();
};
I have tried to use this line to apply Chosen.js to the elements by their class name chzn-select:
$(".chzn-select").chosen();
However I am getting the error :
Uncaught TypeError: Object #<Object> has no method 'chosen' .
Sorry about the messy code, I am new to this.
any help would be much appreciated.
From your comments, you were trying to create a single SELECT with 4 options using chosen.js. Check out JSFiddle 1 for result.
From your question, you were trying to create 4 SELECT dynamically using chosen.js. Check out JSFiddle 2. The reason for error is you missed to point the right id (dropHolder).
try this $("#list").trigger("chosen:updated");
got it from here