Dynamically create and assign id to an input? - javascript

My code is below but I'm unable to verify if it's correct, or if it is, why I can't access the created text inputs by id
for (i=0;i<t;i++)
{
div.innerHTML=div.innerHTML+"<input id="+i+"\" type='text' value="+(i+1)+">"+"<br>";
div1.innerHTML=div1.innerHTML+"<input id=a"+i+"\" type='text' value=a"+(i+1)+">"+"<br>";
gont.innerHTML=gont.innerHTML+i;
}

var t = 2;
var div = document.getElementById('idDiv');
for (i = 0; i < t; i++) {
div.innerHTML = div.innerHTML + "<input id=" + i + "\" type='text' value=" + (i + 1) + ">" + "<br>";
div1.innerHTML = div1.innerHTML + "<input id=a" + i + "\" type='text' value=a" + (i + 1) + ">" + "<br>";
gont.innerHTML = gont.innerHTML + i;
}

Related

Why does my code return </h2> when I set it to return as </input>?

I have a todo site with edit mode and view mode. Full code is at https://repl.it/#UCYT5040/Notekeeper, but this is the JS I am having an issue with.
let editMode = true;
let items = 1
function toggleEditMode() {
console.log(editMode)
if (editMode == true) {
editMode = false;
for (i = 0; i < items; i++) {
document.getElementById('item' + (i + 1)).innerHTML = "<h1 id=\"itemTitle" + (i + 1) + "\">" + document.getElementById('itemTitle' + (i + 1)).value + "</h1>"
}
} else {
editMode = true
for (i = 0; i < items; i++) {
document.getElementById('item' + (i + 1)).innerHTML = "<input type=\"text\" id=\"itemTitle" + (i + 1) + "\" value=\"" + document.getElementById('itemTitle' + (i + 1)).innerHTML + "></input>"
}
}
}
This ends up with
`<div id="item1">
<input type="text" id="itemTitle1" value="New Note">
</h1>
</div>`,
but it should be
`<div id="item1">
<input type="text" id="itemTitle1" value="New Note"></input>.
</div>`.
These are void elements(<input>). This means they aren't designed to contain text or other elements, and as such do not need — and in fact, cannot have — a closing tag in HTML.
document.getElementById('item' + (i + 1)).innerHTML = "<input type=\"text\" id=\"itemTitle" + (i + 1) + "\" value=\"" + document.getElementById('itemTitle' + (i + 1)).innerHTML + "/>"

JS to generate HTML table, but one first row cell won't get value, comes up as 'undefined'

So I have a function that's below (I broke the lines after innerHTML so it's easier to see) and the forloop generates a table, with id's for each tags. I'm wanting to calculate the total of each item(quantity * price).
The function works fine after the first row, but first row's total returns an undefined value, which i'm assuming is because the variables are declared later on.
How could i possible solve this issue, and work out the total?
The relevant JS:
function load() {
for (var i = 0; i <= localStorage.length - 1; i++) {
var key = localStorage.key(i);
document.getElementById(key).setAttribute('checked', 'checked');
document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'></td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
var name = $('#name-' + i).val();
var id = $('#' + name);
var price = id.data('price');
var quantity = document.getElementById('input-' + i);
var quantityValue = quantity.value;
var total = price * quantityValue;
document.getElementById('price-' + i).innerHTML = '£' + price;
var getQuantity = $('#input-' + i).val();
var totalPrice = price * getQuantity;
}
}
Local storage's data:
key: photo2, value: checked
key: photo6, value: checked
key: photo7, value: checked
You are updating total after appending dom. you need to calculate everything before updating it to DOM.
function load() {
for (var i = 0; i <= localStorage.length - 1; i++) {
var key = localStorage.key(i);
var id = $('#' + key);
var price = id.data('price'); // assuming this will be there in dom
var quantityValue = 1; // adding this 1 in table
var total = price * quantityValue;
document.getElementById('price-' + i).innerHTML = '£' + price;
var getQuantity = 1;
var totalPrice = price * getQuantity;
document.getElementById(key).setAttribute('checked', 'checked');
document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'>£" + price + "</td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
}
}

How to get the label value in javascript

I am creating a dynamic tr/td based on json data using below code.
for (i = 0; i < dataPoolJSON.length; i++) {
html += "<tr id ='row" + i + "' value ='" + dataPoolJSON[i].msisdn + "'><td><div class='group'><label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" + dataPoolJSON[i].msisdn;
html += "</label></div></td><td class='hidden-xs'><a id='viewUsage" + i + "' class='viewUsage' onclick='viewDataPoolUsage(this," + dataPoolJSON[i].msisdn + ");return false;' href=''>View Usage</a>";
html += "<div class='pool-usage hidden'></div></td>";
html += "<td><span id='dataAllowed" + i + "'><select>";
if (dataPoolJSON[i].userSetting != null) {
html += "<option selected='selected' value='" + dataPoolJSON[i].userSetting.alertPercentageData1 + "'>" + dataPoolJSON[i].userSetting.alertPercentageData1 + "</option>";
}
html += "</select></span></td></tr>";
}
$('#data-pool tbody').html(html);
Now on click on radio button i need to fetch the msisdn value and current option selected value as but it is not giving me required answer. I am getting the current option selected value but not the msisdn.
function submitNewDataUsagealerts() {
var jsonSubmitData = [];
var selectedData = document.getElementsByName("msisdnSelected");
var i = selectedData.length-1;
for ( j=0; j <= i; j++ ) {
if(selectedData[j].checked) {
var valueCurrent = $('#dataAllowed'+selectedData[j].value).find('option:selected').val();
var row = $('#label'+selectedData[j].value).val();
item = {}
item [0] = valueCurrent;
item [1] = selectedData[j].value;
}
}
}
To get the "value" from a label, use .text() rather than .val().
var row = $('#label'+selectedData[j].value).text();
As your label includes an input and the required text, you can put the text inside a container so that it can be referenced without including the input:
The label code is currently (irrelevant code removed) :
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>";
html += dataPoolJSON[i].msisdn;
html += "</label>";
change this to:
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" ;
html += "<span>" + dataPoolJSON[i].msisdn + "</span>";
html += "</label>";
Then your selector can be:
var row = $('#label'+selectedData[j].value + ">span").text();
Alternatively, move the input out of the label as you're already using label for=:
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" ;
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += dataPoolJSON[i].msisdn
html += "</label>";
Then your selector can be:
var row = $('#label'+selectedData[j].value).text();
var msg = document.getElementById('lbltxt').innerHTML;
alert(msg);
<label id="lbltxt" style="display:none">Test</label>
HTML Code
<label id="mylabel" />
JS Code
var lavelValue = $("#mylabel").text();

javascript find delta of modified form data

I have an html and javascript page rendered through python django, where I have a form data of 30 entries maximum in each page, that can be edited. I included a hidden field with the same form data to extract the old, and modified values in the form. I am looking for extracting just the delta (old and new values for the field that was changed). My code is
{%extends 'base.html'%}
{%block content%}
<h4> Search results</h4>
<p id="data"></p>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
<script>
function onEdit(btn)
{
var id=btn.id;
var before = '';
var after = '';
var input = document.getElementsByName("new"+id);
if(btn.value=="Edit") {
//var input = document.getElementsByName("name"+id);
for(i = 0;i < input.length; i++) {
document.getElementById(input[i].id).removeAttribute("Readonly");
} //End of for loop
document.getElementById(id).value="Save";
return false;
}
if(btn.value=="Save") {
for(i = 0;i < input.length; i++) {
document.getElementById(input[i].id).setAttribute("Readonly", "readonly");
}
document.getElementById(id).value="Edit";
return false;
}
} // End of Function onEdit()
{% autoescape off %}
var data = {{ search|safe }}; //search is the key defined in django view and will be substituted with the json value
{% endautoescape %}
text = ''
var out = '<form name="display" id="update" method="post" action="update/">';
out += "<table style=\"width:50%\">";
out += "<tr>";
out += "<th>Domain</th>";
out += "<th>Points to</th>";
out += "<th>Type</th>";
out += "<th>TTL</th>";
out += "<th>MX priority</th>";
out += "<th>Recorded generated on</th>";
out += "<th></th>";
out += "</tr>";
var i
var id = 0;
for ( var i = 0; i < data.records.length; i++) {
id = id + 1;
out += "<tr><td>" +
"<input readonly='readonly' name='new" + id + "' id='" + data.records[i].domain + "' value='" + data.records[i].domain + "'type='text'/>" +
"<input type='hidden' name='old" + id + "' id='" + data.records[i].domain + "' value='" + data.records[i].domain + "'type='text'/>" +
"</td><td>" +
"<input readonly='readonly' name='new" + id + "' id='" + data.records[i].record_points_to + "' value='" + data.records[i].record_points_to +"'type='text'/>" +
"<input type='hidden' name='old" + id + "' id='" + data.records[i].record_points_to + "' value='" + data.records[i].record_points_to + "'type='text'/>" +
"</td><td>" +
data.records[i].record +
"</td><td>" +
"<input readonly='readonly' name='new" + id + "' id='" + data.records[i].ttl + "' value='" + data.records[i].ttl + "'type='text'/>" +
"<input type='hidden' name='old" + id + "' id='" + data.records[i].ttl + "' value='" + data.records[i].ttl + "'type='text'/>" +
"</td><td>" +
data.records[i].priority_mx +
"</td><td>" +
data.records[i].generated_on +
"</td><td>" +
"<input id='" + id + "' value='Edit' onclick='return onEdit(this)' type='button'/>" +
"</td></tr>";
}
out += "</table>"
total = data.meta.total_records
page = data.meta.page
records_returned = data.records.length
records_shown = ((data.meta.page - 1) * 30) + data.records.length
out += records_shown + " returned of " + total
page = data.meta.page + 1
link = window.location.href
out += "<input type='hidden' name='currenturl' value='" + link + "'>"
if (records_shown == total){
out += " End "
}
else{
url ="<a href='" + updateQueryStringParameter(link, "page", page) + "'> Next"
out += url
}
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
//out += '<input style="position: relative; left: 550px;" type="submit" value="Submit">';
out += '<br>'
out += '<button type="submit" class="btn btn-default">Submit</button>'
out += '</form>';
document.getElementById("data").innerHTML = out
</script>
{%endblock%}
What is the best way to do this?

Edit HTML table and capture changes as POST using Javascript

I just started off with javascript and html, so please correct me if I am doing it the wrong way. I was trying to edit an html form table.
{%extends 'base.html'%}
{%block content%}
<html>
<body>
<h4> Search results</h4>
<p id="data"></p>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
<form id="update" action="/update/" method="POST">
<script>
function onEdit(btn)
{
var id=btn.id;
if(btn.value=="Edit") {
var input = document.getElementsByName("name"+id);
for(i = 0;i < input.length; i++) {
document.getElementById(input[i].id).removeAttribute("Readonly");
} //End of for loop
document.getElementById(id).value="Save";
return false;
}
if(btn.value=="Save") {
for(i = 0;i < input.length; i++) {
document.getElementById(input[i].id).setAttribute("Readonly", "readonly");
}
document.getElementById(id).value="Edit";
return false;
}
} // End of Function onEdit()
{% autoescape off %}
var data = {{ search|safe }}; //This will be the json value returned by django view
{% endautoescape %}
text = ''
var out = "<table style=\"width:50%\">";
out += "<tr>";
out += "<th>Domain</th>";
out += "<th>Points to</th>";
out += "<th>Type</th>";
out += "<th>TTL</th>";
out += "</tr>";
var i
var id = 0;
for ( var i = 0; i < data.records.length; i++) {
id = id + 1;
out += "<tr><td>" +
"<input readonly='readonly' name='name" + id + "' id='" + data.records[i].domain + "' value='" + data.records[i].domain + "'type='text'/>" +
"</td><td>" +
"<input readonly='readonly' name='name" + id + "' id='" + data.records[i].record_points_to + "' value='" + data.records[i].record_points_to +"'type='text'/>" +
"</td><td>" +
data.records[i].record +
"</td><td>" +
"<input readonly='readonly' name='name" + id + "' id='" + data.records[i].ttl + "' value='" + data.records[i].ttl + "'type='text'/>" +
"</td><td>" +
"<input id='" + id + "' value='Edit' onclick='return onEdit(this)' type='button'/>" +
"</td></tr>";
}
out += "</table>"
total = data.meta.total_records
page = data.meta.page
records_returned = data.records.length
records_shown = ((data.meta.page - 1) * 30) + data.records.length
out += records_shown + " returned of " + total
page = data.meta.page + 1
link = window.location.href
if (records_shown == total){
out += " End "
}
else{
url ="<a href='" + updateQueryStringParameter(link, "page", page) + "'> Next"
out += url
}
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
document.getElementById("data").innerHTML = out
</script>
<input type="submit" value="Submit">
</form>
I have the page displayed as expected.
What I am trying to achieve is to make these html tables editable, which is also working half way. When I click the Edit button, the table link turns editable, and I can change the value, and the Edit button changes to Save.
But when I click on "Save" button, firebug error shows
TypeError: input is undefined
for(i = 0;i < input.length; i++) {
----------↑
(Yes, arrow points to var i)
I want to capture the changes when I click on Save, and whatever changes in that page should be captured via POST method once clicked on the submit button below. Submit is redirected to action="/update/". Please let me know what should I do.
to avoid such problems please define all variables at the beginning of their scope (the scope is a function in case of Javascript)

Categories