I have the following script by which I want to achieve to dynamically add rows in an HTML table on my website:
<script>
var globalIterationVariable = 0;
document.onload = $globalIterationVariable = 1;
$('document').ready(function() {
$('.add_another').click(function() {
var globalIterationVariable;
var newRowVariable = '<tr><td><center><input name="nazovPolozky';
newRowVariable.append(String($globalIterationVariable));
newRowVariable.append(' type="text"></center></td> <td><center><input name="pocetPolozky');
newRowVariable.append(String($globalIterationVariable));
newRowVariable.append('" type="number" step="1" min="1"></center></td> <td><center><input name="jednotkovaCenaPolozky');
newRowVariable.append(String($globalIterationVariable));
newRowVariable.append('" type="number" step="0.01" min="0.01"></center></td></tr>');
alert(String(newRowVariable));
$("#tbl").append(String(newRowVariable));
globalIterationVariable++
});
});
</script>
This script though gives me the following error:
Uncaught TypeError: newRowVariable.append is not a function
Can anybody, please, help me to get this script working?
Thank you.
PS: This script is launched once I press a specific button on my website which has a class='button add_another'
You should define newRowVariable as a DOM element ->
const newRowVariable = document.createElement('tr')
Then append the content (your string) to it ->
newRowVariable.innerHTML = `<td><center><input name="nazovPolozky ${$globalIterationVariable}" type="text"></center></td>
Notice I use `` and not '' or "", it's because you can use javascript variables inside a string like that ->
const text = "World"
const superString = `Hello ${text}`
// a console.log(superString) will return 'Hello World'
Jquery might be usefull when you are a complete begginner, but you'll figure out soon that it's way simpler to use pure javascript;)
This is a string
var newRowVariable = '<tr><td><center><input name="nazovPolozky';
This is a jQuery object
var newRowVariable = $('<tr><td><center><input name="nazovPolozky');
This is how you append a string to a string
var newRowVariable = '<tr><td><center><input name="nazovPolozky';
newRowVariable += "/></td></tr>";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.