Replacing innerHtml instead of append - javascript

I have a table in which first row is a label and drodown for selecting number of spaces.
based on the number selected that much number of rows and inside each row another table with input fields will come. everithing is ok in first time.but when i reselect the number from dropdown the number of rows append to the previous one. i want to replace the previous inner tables. how to do this.
this is my html code
<table border="1" style="border-style:dotted" width="100%" id="table_booking">
<tr>
<td>
<label > Number Of Spaces</label>
</td>
<td>
<select id="dropdown" class="" name="spaces" onchange="addForm(this.value)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<table border="1" style="background-color:gray" width="100%" id="table_form">
</table>
</table>
this is the script
<script type="text/javascript">
function addForm(space)
{ var val=space;
document.getElementById('dropdown').value =val;
var doc=document.getElementById('table_booking');
for(var i=0;i<val;i++)
doc.innerHTML += '<tr><td><table width="100%" id="table_form"><tr><td><form><label>Name </label><input type="text"></form></td></tr></table></td></tr>';
}
</script>

Before appending, just flush the existing innerHTML like
doc.innerHTML = '';
Then append it,
for(var i=0;i<val;i++)
doc.innerHTML += '<tr><td><table width="100%" id="table_form"><tr><td><form><label>Name </label><input type="text"></form></td></tr></table></td></tr>';
Updates: Looking through your comments in other answers, I have devised the following approach,
function addForm(space) {
var val = space;
var doc = document.getElementById('table_booking').getElementsByTagName('tbody')[0];
// Remove nodes whenever we append new nodes to the tbody (RESET)
if (doc.getElementsByTagName('tr').length > 1) {
var len = doc.getElementsByTagName('tr').length;
for (i = (len - 1); i >= 1; i--) {
doc.getElementsByTagName('tr')[i].remove();
}
}
// Based on the value selected, new rows will be appended to the tbody
for (var i = 1; i <= val; i++) {
t = doc;
r = t.insertRow(i);
c = r.insertCell(0);
c.innerHTML = "<form><label>Name </label><input type='text'></form>";
doc.appendChild(r);
}
}
JSFiddle

Related

How to add dynamic rows and fetch values from them in order to store it in array using javascript

I like to dynamically add table elements with respect to input 'table_nos' and fetch the data from the table cells and store them in array. I tried creating one table element with a row first and tried cloning the initial one according to the 'table_nos' on document ready function. In order to fetch values, I replaced the ids of cloned rows with dynamic value of "row" + Index. I tried printing the array value in the console using the following code, but it didn't work.
I see that the row elements are assigned as row1, row2, row3.... But I think there is a problem in fetching the values.
Correct me if I am wrong. Thanks in advance.
HTML
<div id= "repeat">
<table id = "repeat_table" style = "width: 70%" >
<tr id = "row0">
<td style = "width: 30%">
<label lang= "nl" for="Client Name" style="color:Grey;font-size: 0.92rem;font-family:Helvetica Neue, Arial, sans-serif">Client Name</label>
<br><br>
<select id="Client Name" style="width:66.5%" name="Client_Name[]">
<option></option>
<option value="Client1">Client1</option>
<option value="Client2" >Client2</option>
<option value="Client3" >Client3</option>
<option value="Client4" >Client4</option>
</select>
</td>
<br><br>
<td style= "width:40%">
<label for="policy" style="color:Grey;font-size: 0.92rem;font-family:Helvetica Neue, Arial, sans-serif" class="required">Policy</label><br><br>
<select id="policy" style="width:50%" name="policy[]">
<option></option>
<option value="Gold">Gold</option>
<option value="Platinum" >Platinum</option>
<option value="Diamond" >Diamond</option>
</select>
</td>
</tr>
</table>
</div>
JavaScript to add rows
<script language="javascript" type="text/javascript">
$(document).ready(function(){
var linebreak = document.createElement("br");
var Index = 1;
$('#repeat').append(linebreak);
for(var i=1 ;i< table_nos; i++)
{
var $temp = $('#row0').clone().attr("id","row"+Index);
$('#repeat_table').append($temp);
$('#repeat_table').append(linebreak);
Index++;
}
});
</script>
Javascript to fetch values
function myJavascriptFunction()
{
var request=new XMLHttpRequest();
var result1 = [];
var result2 = [];
var nodelist = document.getElementById("repeat_table").querySelectorAll("tr");
for(var j = 0 ; j < nodelist.length ; j++)
{
var repeat_policy = nodelist[j].querySelector("#policy").find(':selected').value;
var repeat_clientname = nodelist[j].querySelector("#Client Name).find(':selected').value;
result1.push(repeat_clientname);
result2.push(repeat_policy);
}
console.log(result1);
console.log(result2);
}

How can I get selected row using jQuery?

This is my table row within the tbody of my table. I get dropdown value, text value but I can't get selected row value. My row value returns "undefined".
$(document).on("click", "#skorKartDegerle", function() {
$("#modal_evaluation").modal("show");
});
$(document).on("click", "#btnKaydet", function() {
var arrList = [];
var isEmptyAnswer = false;
$("#evaluationTable > tbody > tr").each(function() {
var line = $(this).find(".answerLine").val();
var ddlVal = $(this).find(".answerddl").val();
var txtVal = $(this).find(".answertxt").val();
var obj = '{"line":"' + line + '","ddlVal":"' + ddlVal + '","txtVal":"' + txtVal + '"}';
arrList.push(obj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="answerLine" value="2">
<td>FR002</td>
<td>Koton Mağazacılık</td>
<td>1800</td>
<td>A</td>
<td>Kabul</td>
<td class="select" value="0">
<select class="answerddl">
<option value="1">Kabul</option>
<option value="2">Ret</option>
</select>
</td>
<td><input type="text" class="answertxt"></td>
</tr>
</tbody>
</table>
Part of the issue is because tr elements do not have a value attribute. To do what you require you could use a data attribute instead, to store custom metadata on the element. The other part is that this is a reference to the tr element. You're then calling find() on the element you're looking to target, so it will not be found as that method looks for descendants only.
In addition it's worth noting that you can make the logic more succinct by using map() to build the array instead of explicitly looping with each() and also that it would be better practice to store objects in the array and only JSON encode it before transferring via AJAX.
$(document).on("click", "#btnKaydet", function() {
var isEmptyAnswer = false;
let arrList = $("#evaluationTable > tbody > tr").map((i, tr) => {
let $tr = $(tr);
return {
line: $tr.data('value'),
ddlVal: $tr.find(".answerddl").val(),
txtVal: $tr.find(".answertxt").val()
}
}).get();
console.log(arrList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="evaluationTable">
<tbody>
<tr class="answerLine" data-value="2">
<td>FR002</td>
<td>Koton Mağazacılık</td>
<td>1800</td>
<td>A</td>
<td>Kabul</td>
<td class="select" value="0">
<select class="answerddl">
<option value="1">Kabul</option>
<option value="2">Ret</option>
</select>
</td>
<td><input type="text" class="answertxt"></td>
</tr>
</tbody>
</table>
<button id="btnKaydet">Click me</button>

After swap rows form doesnt send data, javascript

I have a problem, I coded table with some rows, and after that I need to swap some rows after click:
function move_up(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.previousSibling.previousSibling;
var temp = cur.innerHTML;
cur.innerHTML = cur_upd.innerHTML;
cur_upd.innerHTML = temp;
}
function move_down(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.nextSibling.nextSibling;
var temp = cur.innerHTML;
cur.innerHTML = cur_upd.innerHTML;
cur_upd.innerHTML = temp ;
}
I have table with rows like this:
<tr>
<TD >
Typ projektu 1
</TD>
<TD align="center">
<input type="text" class="order_num" name="x_order_num_PROJECT_TYPE" value="1">
<input type="checkbox" name="x_PROJECT_TYPE_on" checked>
</TD>
<td>
Hore
Dole
</td>
<TD align="LEFT">
<select class="selectbox" name="x_PROJECT_TYPE" style="width: 250px">
<OPTION VALUE="-1" SELECTED>Všetky</option>
<OPTION VALUE="1" SELECTED>Fixed price</option>
<OPTION VALUE="2">Time and materials</option>
</select>
</TD>
<TD>▲
<INPUT TYPE="radio" NAME="x_sort" VALUE="PROJECT_TYPE;asc">
<INPUT TYPE="radio" NAME="x_sort" VALUE="PROJECT_TYPE;desc">
▼
</TD>
</TR>
After I click on href 'Hore' or 'Dole' it look good, but problem is, that after swap column when I call form submit, it submit all imputs from all rows except swapped rows. Input from that rows is not submitted. What can be problem?
Don't use innerHTML to move the elements, just move the DOM elements themselves.
function move_up(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.previousSibling.previousSibling;
var parent = cur.parentNode;
parent.insertBefore(cur, cur_upd);
}
function move_down(x) {
var cur = x.parentNode.parentNode;
var cur_upd = cur.nextSibling.nextSibling;
var parent = cur.parentNode;
parent.insertBefore(cur_upd, cur);
}
If there are any event listeners bound to elements, or the application has variables referencing them, converting them back and forth to HTML will lose that.

when option selected do stuff ( btw, all the elments have dynamic id)

I searched for similar questions, I found some but their solution did't help me.
For example:
First question
Second question
My problem is:
I have a table that the user can add rows dynamically, so I am creating a unique id for each row and all elements inside as well.
each row have two text fields and select with two options, and when you select one of the option the text feild should be dislpay:block and the second will be display: "none", depending on your choice.
I built here some example that will shows the general structure (JSFiddle)
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>
<input id="description-first-1" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-1" name="description-second-2" type="text" placeholder = "second">
<select id="select-1">
<option>
<option id="first-opt-1">1</option>
<option id="second-opt-1">2</option>
</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="description-first-2" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-2" name="description-second-2" type="text" placeholder = "second">
<select id="select-2">
<option>
<option id="first-opt-2">1</option>
<option id="second-opt-2">2</option>
</option>
</select>
</td>
</tr>
$(function() {
$("#select-1").change(function() {
if ($("#first-opt-1").is(":selected")) {
$("#description-first-1").show();
$("#description-second-1").hide();
} else {
$("#description-first-1").hide();
$("#description-second-2").show();
}
}).trigger('change');
});
http://jsfiddle.net/8vz121rq/9/
In my example for that matter you can seen that there are only 2 rows but it can also be 10 rows with different id's.
How to get jquery identify which row and all the elements inside of it i'm changing if the id's of all elements is dynamic ?
First of all, you need event delegation as the rows are dynamically generated, such as:
$("table").on("change", "[id^='select']", function() {
// do your stuf
});
Or in your case:
$("table").on("change", "#select-1", function() {
// do your stuf
});
So, is this what you needed?
$(function() {
$("table").on("change", "[id^='select']", function() {
var $this = $(this);
var $row = $this.closest("tr");
var ID = this.id.replace(/^[^\-]+\-(\d+)$/gi, '$1');
var sIndex = $this.prop('selectedIndex');
var part = sIndex === 2 ? "second" : "first";
if (!sIndex) {
$row.find("input").show();
return;
}
$row.find("input").hide();
$row.find("#description-" + part + "-" + ID).show();
});
});
Demo#Fiddle
P.S. The above is purely based on your markup and ID structure!

Trying to output from Javascript file to HTML page?

I am trying to output from a Javascript file to the HTML page, and I am coming across some difficulty. Basically the user would select the options from the drop down menus and input from the text boxes, hit calculate and the program would calculate the necessary values.
After the calculation is complete there are three variables that I would like to output back to the page. Disregard the actual calculations, they are irrelevant. I am using jQuery and Javascript, I guess I can return a single variable but how do I return all of the variables I need.
Here is the HTML page I have and the javascript file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="framework.js"></script>
<script type="text/javascript">
function ShowCalculation() {
Main($("#orangeSel").val(), $("#appleSel").val(), $("#soccerTxt").val(), $("#basketballTxt").val(), $("#banSel").val());
}
</script>
</head>
<body>
<div>
<div>
<br />
<table border="0">
<tr>
<td>
Number of Bananas
</td>
<td>
<select id="banSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
Number of Oranges:
</td>
<td><select id="orangeSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
Apples
</td>
<td>
<select id="appleSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
Soccer Score:
</td>
<td>
<input type="text" id="soccerTxt" value="2" size="3" />
</td>
<td>
Basketball Score:
</td>
<td>
<input type="text" id="basketballTxt" value="30" size="3" />
</td>
</tr>
</table>
<br />
<br />
<center><input type="submit" value="Calculate" onclick="ShowCalculation(); return false;" /></center>
</div>
</div>
<div>
<b><h1>Output</h1></b>
<table border="0">
<tr>
<td>
Manipulated Oranges:
</td>
</tr>
<tr>
<td>
Manipulated Apples:
</td>
</tr>
<tr>
<td>Manipulated Soccer:</td>
</tr>
</table>
</div>
</body>
</html>
And here is the Javascript file
function Main(orange, apple, soccer, basketball, banana) {
var a = parseInt(orange);
var b = parseInt(apple);
var c = parseInt(soccer);
var d = 0;
var e = parseInt(basketball);
var f = parseInt(banana);
for (var i = 0; i < a; i++) {
d += c;
}
for (var j = 0; j < 10; i++) {
c += 30;
}
var outputOne = c;
var outputTwo = d;
var outputThree = 5;
}
To return several values from a JavaScript function you can create a new "anonymous" object, something like this in the Main() function:
function Main(orange, apple, soccer, basketball, banana) {
var a = parseInt(orange);
var b = parseInt(apple);
var c = parseInt(soccer);
var d = 0;
var e = parseInt(basketball);
var f = parseInt(banana);
for (var i = 0; i < a; i++) {
d += c;
}
for (var j = 0; j < 10; i++) {
c += 30;
}
var outputOne = c;
var outputTwo = d;
var outputThree = 5;
return {output1:outputOne, output2:outputTwo, output3:outputThree};
}
Then you have to modify the markup to add ids to the fields where you want to output the variables:
<td>
Manipulated Oranges: <span id="manOranges"></span>
</td>
Then you will have to change the JavaScript function ShowCalculation to look like this:
function ShowCalculation() {
var results = Main($("#orangeSel").val(), $("#appleSel").val(), $("#soccerTxt").val(), $("#basketballTxt").val(), $("#banSel").val());
$("#manOranges").html(results.output1);
}
...
Hope this helps
Edit: Added the complete Main function to show how the entire function has to look.
You could return the results as an object. Something along these lines:
return {
outputOne: c,
outputTwo: d,
outputThree: 5
};
This is know as JavaScript Object Literal Notation. You can read more about it in this article.
EDIT:
Using jQuery there are several ways you can then add the results to your page using. jQuery.append or jQuery.html are two such ways.
I posted an example using your code on jsFiddle. Also, there is a bug in this line:
for (var j = 0; j < 10; i++)
i++ should be j++.
In your code you are using the id selector to get the value of some elements
$("#orangeSel").val()
In the same way, you need to set the value once you do the computation
$("#answer-area").html('the answer)
I believe if your answer-area is an input, you can use val('the answer') in place of html.
f you want to return the value to another javascript function you could use an map object:
var output=[ val1, val2, val3];
and then loop trough em with a foreach
for (i in output){
do something
}
if you want to display these values in your html i would advice you to set the values from your javascript directly by giving the cell you want the values at an ID and putting a value like this
document.getElementById('answer1').innerHTML = val1;

Categories

Resources