JavaScript Clears My Input Values - javascript

I am writing a simple form at work using HTML and have added JavaScript to the page to allow users to add extra rows to a table. This table has input type="Text" tags and select tags. When the user clicks the button to add a row, the JavaScript adds a row, but clears the input and select tags.
My script is
var x = x + 1;
function another()
{
x = x + 1;
y = y + 1;
var bigTable = document.getElementById("bigTable");
bigTable.innerHTML += ("<TR><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><SELECT
NAME=\"PO" + x + "\"><OPTION>Select</OPTION><OPTION>1234567890</OPTION></SELECT>
</TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"SKU" + x
+ "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\"
NAME=\"modelNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT
TYPE=\"Text\" NAME=\"itemNum" + x + "\"></TD><TD CLASS=\"bigTable2\"
ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"qty" + x + "\" ID=\"qty"+x+"\"
onBlur=\"total();\"></TD></TR>");
}
I'm not sure what the issue is here. Is the "+=" statement basically resetting my table like an = statement would?
EDIT: I don't know how to get all of the code to appear, but what is displayed is not all of my code. I have a basic Table and using JavaScript use a += statement to add HTML to it.
EDIT: My table is this:
<TABLE ID="bigTable">
<TR>
<TH>P.O. #</TH>
<TH>SKU #</TH>
<TH>Model #</TH>
<TH>Item #</TH>
<TH>Quantity</TH>
</TR>
<TR>
<TD CLASS="bigTable" ALIGN="Center">
<SELECT NAME="PO1">
<OPTION>Select</OPTION>
<OPTION>1234567890</OPTION>
</SELECT>
</TD>
<TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="SKU1"></TD>
<TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="modelNum1"></TD>
<TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="itemNum1"></TD>
<TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="qty1" ID="qty1" onBlur="total();"></TD>
</TR>
</TABLE>
My JavaScript Replicates everything between the tags. And I use the variable x to update the number in the names for the inputs and dropdowns. Variable Y is used to increment a calculation function.

When you edit the innerHTML of a HTML element, the entire DOM gets re-parsed. Since the input's values aren't actually stored in the input elements's HTML, they are cleared.
An option would be to use DOM manipulation to add the row:
function another(){
x = x + 1;
y = y + 1;
var bigTable = document.getElementById("bigTable");
vat tr = document.createElement('tr');
tr.innerHTML = ("<td class='bigTable2' align='Center'><select name='PO" + x + "'><option>select</option><option>1234567890</option></select></td>"+
"<td class='bigTable2' align='Center'><input type='Text' name='SKU" + x + "'></td>"+
"<td class='bigTable2' align='Center'><input type='Text' name='modelNum" + x + "'></td>"+
"<td class='bigTable2' align='Center'><input type='Text' name='itemNum" + x + "'></td>"+
"<td class='bigTable2' align='Center'><input type='Text' name='qty" + x + "' ID='qty" + x + "' onBlur='total();'></td>");
bigTable.appendChild(tr);
}
Notice how the string no longer contains a <tr> tag.
This codes creates a tr element, then adds the rows to it, then adds that whole, (parsed), tr to the table.
(I also changed the tags / attributes to lowercase and replaced all \" with ' to make it more readable)

To be clear, x += y is the same as writing x = x + y. What's happening here is that you are overwriting the HTML with what you had plus the new row. This clears your inputs because their values are not stored in the HTML (when you type inside one of the input, it's "value" property is not updated in the actual HTML).
So you are basically overwriting your HTML with what was there initially plus some added nodes.
EDIT: Go for Cerbrus's solution. Much cleaner.

What I ended up going with was a dynamic JavaScript code that would create a dynamic array and store values in each column of my current table. Then the code created a new row and the array was then accessed to repopulate the values.

Related

Why is the data being displayed many times over the loop?

I have been trying to set up a kind of search engine connected to an API. It takes the user input and gives back the information from the API. In the future there should be a "dynamic" amount of input fields but for the moment I am working with a fixed amount of five. The loop takes the amount of fields and calls the API that amount of times with that input.
I tried placing a constant (i.e. 5) in the loop but still, the funny part is that with 3 it of course calls the app three times but outputs 6 fields, and with 2 it calls the API 2 times but outputs three rows so it seems that it does not obey the loop but something else. Meanwhile in the console (with log) I can see that the API is properly called only the times defined by the loop so I believe something goes wrong at the $.getJSON level
The problem is at the end a table is created with 15 rows instead of the expected 5 (one row for every input). Why do you think this is happening?
Thanks in advance
<form name="inputform" method="get" width="50">
<input type="text" name="field0" id="field0" size="50">
<input type="text" name="field1" id="field1" size="50">
<input type="text" name="field2" id="field2" size="50">
<input type="text" name="field3" id="field3" size="50">
<input type="text" name="field4" id="field4" size="50">
</form>
<table id="table">
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Preference</th>
</tr>
</table>
<input id="getInfo" type="button" value="Submit" /><br/>
var customURL = "http://apitest.com/test/";
var customURL1 = '';
$('#getInfo').click(function() {
$('#table tr').not(':first').remove();
var fields = document.getElementsByTagName('input');
var table = document.getElementById('table');
if (localStorage.myJSON !== undefined) {
var myJSON = JSON.parse(localStorage.myJSON);
}
var html = '';
for (var i = 0; i < elements.length - 1; i++) {
customURL1 = customURL + document.getElementById('field' + i + '').value;
console.log(customURL1);
$.getJSON(customURL1, function(data) {
console.log(data);
html += '<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>';
$('#table tr').first().after(html);
Each time you get an AJAX response, you're appending the response to the html variable, and then adding that after the first row of the table. Since the html variable already contains the results from the previous responses, and they were insert into the table already, you get duplicates.
Instead of concatenating the new row to html, just insert the new row directly into the table.
$.getJSON(customURL1, function(data) {
console.log(data);
$('#table tr').first().after('<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>');

Different behavior of HTML <input> checked Attribute

Different behavior is occurring in different browser for HTML <input> attribute. I have generated input attribute from Javascript by clicking a button. Checkbox is visible in Firefox browser but not showing in Chrome browser. The generated HTML code is
<input id="0" class="col-sm-1" onclick="checkImage(this)" name="images[0].isActiveDefault" type="checkbox">
FireFox Browser
Chrome Browser
Any help or suggestion to resolve this problem will be appreciate.
EDIT added JavaScript Code
function addImagerow(tableId) {
var rowValue = parseInt(document.getElementById('image-add').value);
var tableData = "<tr><td><input id = '"
+ rowValue
+ "' class='col-sm-1' onclick='checkImage(this)' name='images["
+ rowValue
+ "].isActiveDefault' type='checkbox'></td><td>Default</td>"
+ "<tr>";
document.getElementById('image-add').value = rowValue + 1;
$(tableData).appendTo(tableId);
}
After having waste a lot of time I found the issue. Though the issue is silly, I have learned a lesson from it. Ok, the issue was on the design. From the input field I remove the class='col-sm-1'. And its working fine.
I added the bootstrap css for input field but not for table data field.
var tableData = "<tr><td><input id = '"
+ rowValue
+ "' class='col-sm-1' onclick='checkImage(this)' name='images["
+ rowValue
+ "].isActiveDefault' type='checkbox'></td><td>Default</td>"
+ "<tr>";
TO
var tableData = "<tr><td><input id = '"
+ rowValue
+ "onclick='checkImage(this)' name='images["
+ rowValue
+ "].isActiveDefault' type='checkbox'></td><td>Default</td>"
+ "<tr>";
And my analysis says that I when I added the col-sm-1 into the input field the <td> is not expanding that's why the input field is hide.

Javascript function for form created using Javascript

I have a script which adds a new form when a button is clicked to a HTML page with the code as following:
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("Max number of forms, " + counter );
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<form name='frmMain' action='prelucrare.php' method='POST'><div class='slot' id='dynamicInput' align='center'> Masina " + (counter +1 ) + "<table border='1'><tr><td align='right'><label for='marca'>Marca:</label></td><td colspan='2' align='left'>"
+ "<select id='marc' name='marc'><option selected value=''></option>"
+ "<tr><td align='right'><label for='motorizare1'> Motorizare:</label></td> <td><input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id=motor1 oninput='outputUpdate1(value)'></td><td><output for=motorizare1 id=moto1>2</output></td></tr>"
+ "</div></form>"
;
}
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
<input type="button" value="Adauga" onClick="addInput('dynamicInput');">
And I have the script bellow which changes the value from the slider.
<script>
function outputUpdate1(mot1) {
document.querySelector('#moto1').innerHTML = mot1;
}
</script>
My problem is that the JS code only changes the input for the first form, even if the slider is activated from another form. In short, the slider should return the value in the form from which it is activate; not only in the first form added.
Thank you!
Going along with my comment, the problem is stemming from the id value being the same across all of your output elements (moto1). You've actually got all the variables you need to make them unique since you're tracking a count of the number of forms on the page (your counter variable). You can use this in place of your current output HTML:
"<input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id='motor_" + counter + "' oninput='outputUpdate1(value)'/>"
"<output for=motorizare1 id='moto_" + counter + "'>"
You can update your function to parse out the correct index for the output you want to update since they should be in sync if you use the HTML above:
function outputUpdate1(mot) {
// Get the counter part of the range element's id
var index = mot.id.split('_')[1];
document.querySelector('#moto_' + index).innerHTML = mot;
}
You may need to make some tweaks to code you haven't provided in the question, but that's one way of making the id values unique and how to access them without knowing the exact id ahead of time.

How to get the textbox value which is dynamically added to a table row inside a <td>

I am appending a <td> having an input text to a row. I want to get the value of this textbox and use it in another function.
Below is the code snippet :
row.append($('<td ><input type="text" value=' + item.Marks + ' size="10px" class="marks" id="txtmarks" maxlength="3"/></td>'));
Thanks in advance.
Split it in two statements:
var input = $("<input type="text" size="10px" class="marks" id="txtmarks" maxlength="3"/>").val(item.Marks);
var newRow = $('<td></td>').append(input);
row.append(newRow);
So, now you have a reference to your input, and the code looks much cleaner.

Javascript why isnt this simple counter working in my loop

I have a function that is called button and it appends m table using a loop. I have modified the loop so that it assigns an ID to each <td> it makes. However, it does not seem to be working right.
Here it is in action, follow the use case below to test it: http://jsfiddle.net/JEAkX/19/
Here is a simple use case I use to test it:
Change the letter in a cell
Press "More"
Change the letter in one of the new cells
It should function the same as the original cells if the ID was getting assigned properly.
The counter is: var n = 13;
and it is inserted into the appended cell as such:
cell.innerHTML = "<input type='text' id='r"+ (n) +"' size='1' onChange='getPos('r"+ (n++) +"'), modifyCells('alphabetTable')' value='" + subset[i++] + "' />"`
This is the DOM source I am getting:
<td><input id="r13" size="1" onchange="getPos(" r14="" ),="" modifycells(="" alphabettable="" )="" value="q" type="text"></td>
<td><input id="r14" size="1" onchange="getPos(" r15="" ),="" modifycells(="" alphabettable="" )="" value="r" type="text"></td>
I suspect it has to do with cramming everything into 1 line like #zzzzBov said but I dont know how else to do it.
Besides the n++, there's a quoting issue in your HTML. There are nested single quotes in the onchange attribute, like so:
<input type='text' id='r19' size='1' onChange='getPos('r20'), modifyCells('alphabetTable')' value='p' />
Quick fix for the syntax is to use escaped double quotes, so you can get going:
cell.innerHTML = "<input type='text' id='r"+ n +"' size='1' onChange='getPos(\"r"+ (n++) +"\"), modifyCells(\"alphabetTable\")' value='" + subset[i++] + "' />"
Separation of HTML/CSS/JS notwithstanding.... You need 3 levels of quotes. Also, the comma in the onclick event needs to be a semicolon.
Perhaps:
cell.innerHTML = "<input type='text' id='r" + n + "' size='1'
onChange='getPos(\"r" + (n++) + "\"); modifyCells(\"alphabetTable\")'
value='" + subset[i++] + "' />"

Categories