s.no. | description
abcd1
abcd2
abcd3
i want to add more rows through input. now what i want is when i will add another row. let say {describtion="abcd4"}
then the above grid will become
s.no. | description
abcd4
abcd1
abcd2
abcd3
meaning s.no. field got updated and new row will be added at top. adding a new row on top is no issue but how could i update s.no. at same time, here i want to ask is there any specific way to do this.
Here is a solution that adds rows at the top of a table and keeps the numbers updated:
document.querySelector('#btnadd').addEventListener('click', function () {
var inp = document.querySelector('#inpadd');
var descr = inp.value;
if (descr === '') return; // do not add empty values
var grid = document.querySelector('#grid');
// first increment all row numbers
for (var i = 1, row; row = grid.rows[i]; i++) {
row.cells[0].textContent = i+1;
}
// add new row
var row = grid.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.textContent = 1;
cell2.textContent = descr;
// clear input
inp.value = "";
});
New description: <input type="text" id="inpadd"><button id="btnadd">Add</button>
<table id="grid">
<tr><th>s.no.</th><th>description</th></tr>
<table>
If you want to insert new text description in the beginning of the ordered list, you can use 'insertBefore' javascript code:
list.insertBefore(entry, list.firstChild);
It should add the new text in the beginning of the list. Refer below code if it helps your problem.
<!DOCTYPE html>
<html>
<body>
<p>Input the text description and click 'Add Description' button to insert in list:</p>
<form>
Description Text:<br>
<input type="text" name="description" id="description">
<br>
<input type="button" value="Add Description" onclick='appendDescription()'>
</form>
<ol id="desclist">
<li>abcd1</li>
<li>abcd2</li>
<li>abcd3</li>
</ol>
<script>
function appendDescription(){
var description= document.getElementById('description').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(description));
var list = document.getElementById('desclist');
list.insertBefore(entry, list.firstChild);
}
</script>
</body>
</html>
function pushAtStarting(array, element){
array.unshift(element); // new element has s.no = 0
for (index in array){
array[index].sno++
}
}
var array = [];
pushAtStarting(array, {sno: 0, description: "abc"});
it works if your grid is java script arrays and elements are json elements.
Related
I have been cobbling together script from other sources and feel like I am close but can't make that final leap on my own. Just to give you some background
I am putting together a document in Google Sheets where I can have a student input specific values from a live football game, that will be used on OBS to be displayed as real time stats for our video broadcast. I made a very simple button based sheet for basketball and it worked fantastically. Picture of Google Basketball Sheet
Football is a different beast. My concept is to have a sidebar where I have a set of names preselected in a drop down menu along with a second drop down menu with a preselected drop down of stat types (rush, passing....) these two drop downs will find the cell associated with both with Name rows) and stat type (column) and a input field which adds value to selected cell.
I have not been able to figure out how to have a drop down menu associate with a specific cell, let alone two different drop downs. If the two drop downs isn't possible, I am happy with making a button to associate with specific plays then have a drop down of names along with an input field will work.
What I have so far - I have a drop down menu that pulls the names from Column A but when I select one, nothing happens. I also have a button that I can send a value to a specific cell, but it won't add to the original cell it just changes the cell to "Input value"1
function ftball() {
try {
var output = HtmlService.createHtmlOutputFromFile('HTML_Sidebar');
SpreadsheetApp.getUi().showSidebar(output);
}
catch(err) {
Logger.log(err);
}
}
function getNames() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Football");
return sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues(); // Retrieve values and send to Javascript
}
// Sets the value of A1 cell to value entered in the input field in the side bar!
function enterValue(number){
var ss = SpreadsheetApp.getActive()
var sheet = ss.getActiveSheet()
sheet.getRange("B11").setValue(number + 1)
}
and the HTML for the Sidebar
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="mySelect" onchange="selectChange(this)">
</select>
<script>
function selectChange(select) {
google.script.run.changeSheet(select.value);
}
function playerNames(names) {
var select = document.getElementById("mySelect");
for( var i=0; i<names.length; i++ ) {
var option = document.createElement("option");
option.text = names[i];
select.add(option);
}
}
(function () { google.script.run.withSuccessHandler(playerNames).getNames(); }());
</script>
<button onclick='f1()'>Select Athlete Name</button>
</br>
<!-- Create a input field to except a value form user, in this case there name -->
Enter Value:
<input type="number" id="number"><br>
<!-- Create a button to send the value to the spreadsheet -->
<button onclick='sendValue()'>Send Value</button>
<script>
function f1() {
google.script.run.getAddress();
}
function sendValue(){
//Get the value of the input field
var number = document.getElementById("number").value
//Log the value of input field in the web browser console (usually used for debugging)
console.log(number)
//Send the value of the text field as a arugment to the server side function.
google.script.run.enterValue(number)
}
</script>
</body>
</html>
I am able to create something from yours using my own sample data and not sure if this is what you want but I tried to adjust to anything I understood in your post. See output and code below.
Code.gs:
function ftball() {
try {
var output = HtmlService.createHtmlOutputFromFile('HTML_Sidebar');
SpreadsheetApp.getUi().showSidebar(output);
}
catch(err) {
Logger.log(err);
}
}
function getData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Football");
return [sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues().filter(String), // Retrieve names and
sheet.getRange(1, 2, sheet.getLastRow(), 1).getValues().filter(String)]; // Stat types then send to Javascript (remove blank cells)
}
function enterValue(number, name, stat){
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var namesLength = sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues().filter(String).length;
var statsLength = sheet.getRange(1, 2, sheet.getLastRow(), 1).getValues().filter(String).length;
// where your name headers for the table starts (C6)
var nameStartRow = 6;
var nameStartCol = 3;
// where your stat headers for the table (D5)
var statStartRow = 5;
var statStartCol = 4;
// get list of names
var names = sheet.getRange(nameStartRow, nameStartCol, namesLength, 1).getValues().flat();
var stats = sheet.getRange(statStartRow, statStartCol, 1, statsLength).getValues().flat();
// find the position by adjusting the index of name/stat to where the list starts
var namePosition = names.indexOf(name) + nameStartRow;
var statPosition = stats.indexOf(stat) + statStartCol;
// get previous value, assign 0 if blank.
var previousValue = sheet.getRange(namePosition, statPosition).getValue() || 0;
sheet.getRange(namePosition, statPosition).setValue(parseInt(previousValue) + parseInt(number));
}
HTML_Sidebar.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="mySelectNames"></select>
<select id="mySelectStats"></select><br>
Enter Value:
<input type="number" id="number"><br>
<button onclick='sendValue()'>Send Value</button>
<script>
function setOptions([names, stats]) {
// set both names and stats drop down
var select = document.getElementById("mySelectNames");
for( var i=0; i<names.length; i++ ) {
var option = document.createElement("option");
option.text = names[i];
select.add(option);
}
// set default value to first option
select.selectedIndex = 0;
var select2 = document.getElementById("mySelectStats");
for( var i=0; i<stats.length; i++ ) {
var option2 = document.createElement("option");
option2.text = stats[i];
select2.add(option2);
}
select2.selectedIndex = 0;
}
function sendValue(){
// send the values of name, stat and number then set as value
var number = document.getElementById("number").value;
var name = document.getElementById("mySelectNames").value;
var stat = document.getElementById("mySelectStats").value;
//Send the value of the text field as a arugment to the server side function.
google.script.run.enterValue(number, name, stat);
}
(function () { google.script.run.withSuccessHandler(setOptions).getData(); }());
</script>
</body>
</html>
Output:
Note:
I modified both your html and apps script. But I hope it is near what you are wanting to achieve.
The important bit here is how to find where to put the value given the name and stat. That's what I think is you can use and modify based on your data and wanted output.
The code needs A and B to be not populated, thus the table is a bit to the right. But it can be avoided if we exactly know the list of names and stats.
So I'm trying to make a form where the user can dynamically add and remove rows containing cascading dropdowns as a class picker.
So far I've been able to make everything work except for the remove selected classes function.
I've tried a couple different deleteRow functions but can't seem to make it work.
My most recent attempt is by using the checkbox input but I'm open to any other solutions.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Semesters Planned</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#selectCategory').change(function() {getSelectedItem(this, null); });
$('#button').click(function()
{addRow('dataTable'); });
var classes = {//can probably use external text files for these later on
"Core": ["UNI101", "ENG101"],
"Major": ["CSC101", "CSC180"],
"Elective": ["ART101", "PSY101"]
};
var keys = Object.keys(classes);
var category_dropdown = document.getElementById("selectCategory");
var getSelectedItem = function(element, row) {
var e = element;
var selectedCategory = e.options[e.selectedIndex].value;
var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("selectSubCategory"));
sub_category_dropdown.options.length = 0;
for (var i = 0; i < classes[selectedCategory].length; i++) {
sub_category_dropdown[sub_category_dropdown.length] = new Option(classes[selectedCategory][i], classes[selectedCategory][i]);
}
};
var addRow = function(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.childNodes[0].selectedIndex = 0;
}
var selects = row.getElementsByTagName("select");
selects[0].addEventListener('change', function()
{
getSelectedItem(this, row)
}, false);
};
function deleteRow(tableID)
{
for (var rowi= table.rows.length; rowi==0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('chk');
for (var inputi= inputs.length; inputi0;) {
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
row.parentNode.remove(tableID);
break;
}
}}}
for (var keys in classes) {
category_dropdown[category_dropdown.length] = new Option(keys, keys);
}
});
</script>
</head>
<body>
<INPUT type="button" value="Add Class" id="button" />
<INPUT type="button" value="Remove Selected Classes"/>
<form id="myForm">
<TABLE id="dataTable">
<TR>
<TD>
<select id="selectCategory">
<option>Choose Class Type</option>
</select>
</TD>
<TD>
<select id="selectSubCategory">
<option>Choose Class Type First</option>
</select>
</TD>
<TD><INPUT type="checkbox" name="chk" id="input"/></TD>
</TR>
</TABLE>
</form>
<input type = "Submit" value = "Submit">
</body>
</html>
My first suggestion would be to make sure that the remove button is doing something when you click it - you've attached an event listener to the Add Class button, but the Remove Selected Classes button doesn't look like it's calling that deleteRows function.
Then, make sure that you have a reference to that table in the deleteRows function. You are passing it a table id, but the table variable reference is defined outside of the scope of that function.
Then, work on the for loop and the logic therein. It looks like you are mistaking getElementsByTagName with getElementsByName. The one you are using is concerned with the tag name (input) not the name attribute (chk).
Hope this helps a little bit!
I'm currently trying to add a jQuery function to a row of radio buttons. The problem is that I need to add dynamically many rows. Now For this example I only added 2 elements into the array of newNodes, but in my application newNodes can potentially have many different sizes.
So basically I want to add the Query function something like this:
$('#rowID input').on('change', function() {
alert($('input[name=i]:checked', '#rowID').val());
});
Where it exists inside the forloop and is added for each new row. "rowID" is a variable assigned to the unique row identifier and then use the loop iterator "i" as a way to distinguish the radio buttons for each row.
Here is the HTML:
<form id="createEdges" method="POST>
<fieldset>
<legend class="title">Modify the graph!</legend>
<table id="createEdgesTable">
</table>
<input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/>
</fieldset>
And Here is the Javascript:
newNodes = [];
newNodes.push(0);
newNodes.push(1);
//get HTML Table to add rows in
var edgeTable = document.getElementById("createEdgesTable");
//Create a table row for each node
for (var i in newNodes) {
var row = edgeTable.insertRow();
row.id = "node" + i;
//Show name of the node
var td = document.createElement('td');
var text = document.createTextNode(newNodes[i]);
td.appendChild(text);
row.appendChild(td);
//Choice for showing node
var td2 = document.createElement('td');
var radioButton1 = document.createElement('input');
radioButton1.type = "radio";
radioButton1.name = i;
radioButton1.value = "showNode";
td2.appendChild(radioButton1);
row.appendChild(td2);
//Choice for creating edge
var td3 = document.createElement('td');
var radioButton2 = document.createElement('input');
radioButton2.type = "radio";
radioButton2.name = i;
radioButton2.value = "createEdge";
td3.appendChild(radioButton2);
row.appendChild(td3);
//Choice for deleting node
var td4 = document.createElement('td');
var radioButton3 = document.createElement('input');
radioButton3.type = "radio";
radioButton3.name = i;
radioButton3.value = "removeNode";
td4.appendChild(radioButton3);
row.appendChild(td4);
var rowID = row.id;
}
$('#node0 input').on('change', function() {
alert($('input[name=0]:checked', '#node0').val());
});
JSFiddle: https://jsfiddle.net/nxexrq9y/
Any example on how to make this work for each row? I'm relatively new to JQuery and have been stuck on this problem for quite some time now. Thank you for your time and help!
Just change your script with following code.
$('tr[id^=node] input').on('change', function() {
alert(this.value);
});
Explanation:
Scripts find any tr whose id starts with node. this covers all your dynamically generated TRs. Further selection narrows down to only input element in each TR, and registers change event for that element. On that change event your have already got that element so you can easily access its value there.
Here is Js Fiddle Link
Further if you want to know clicked radio falls in which node, you can check out this js fiddle.
$('tr[id^=node] input').on('change', function() {
var row = $(this).parents('tr:first').get(0);
alert('Node: '+ row.id+ ' value:' + this.value);
});
Below is my code for dynamic generation of rows:
function addRow() {
var myName = document.getElementById("name");
var type = document.getElementById("type");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML=myName.value;
row.insertCell(1).innerHTML=type.value;
row.insertCell(2).innerHTML= '<input type="button" value = "Delete" onClick="Javascript:deleteRow(this)">';
row.insertCell(3).innerHTML= ' Edit';
}
and below is my code for popup after clicking on edit link:
<div class="popup">
<p>Please edit your details here</p>
<div>
<label for="firstname" id="attr_Name">Attribute Name</label>
<input type="text" id="firstname" value="" />
</div>
<div>
<label for="lastname" id="attr_Type">Attribute Type</label>
<select id="type1" ><option >Text</option><option >Paragraph</option><option >Dropdown</option></select>
</div>
<input type="button" id="button1" value="Save" onclick="saveEditedValues()"/>
<a class="close" href="#close"></a>
</div>
Now I am using local storage to save my edited values but I am not getting how to reflect it in the dynamically generated rows. Below is code for Local storage:
function saveEditedValues(){
var myName = document.getElementById("firstname").value;
alert(myName);
var type = document.getElementById("type1").value;
alert(type);
localStorage.setItem("attributeName",myName.value);
localStorage.setItem("attributeType",type.value);
var namevar1=localStorage.getItem("attributeName");
var namevar2=localStorage.getItem("attributeType");
}
Please provide some help
In order to update the table, the save function will need to be able to locate the correct row, which means you will have to pass it something like the row number.
When adding the row, define the onclick event handler of the Edit link to pass rowCount
row.insertCell(3).innerHTML= ' Edit';
Add a hidden input to your popup div
<input type="hidden" id="editingRow" />
and have the Edit function populate that value:
function Edit(rowNum) {
...
document.getElementById("editingRow").value = rowNum;
...
}
Then the saveEditedValues function can locate the row in the table and update the values
function saveEditedValues(){
...
var rowNum = document.getElementById("editingRow").value;
var row = document.getElementById("myTableData").rows[rowNum];
row.cells[0].innerHTML = myName;
row.cells[1].innerHTML = type;
...
}
like so: jsFiddle
var myName = document.getElementById("firstname").value;
alert(myName);
var type = document.getElementById("type1").value;
alert(type);
myName and type are the correct values (strings). So
localStorage.setItem("attributeName",myName.value);
localStorage.setItem("attributeType",type.value);
is wrong, you have to use the plain variables like this:
localStorage.setItem("attributeName",myName);
localStorage.setItem("attributeType",type);
I have SQLite3 (i.e. Spatialite query) that outputs the results into HTML table. I want to get the AsText(Geometry) data to output in <textarea>
Here is the table and some assumptions.
<table>
<tr>
<th>name</th>
<th>AsText(Geometry))</th>
</tr>
<tr>
<td>Andres Street</td>
<td>LINESTRING(7.120068 43.583917,7.120154 43.583652,7.120385
43.582716,7.12039 43.582568,7.120712 43.581511,7.120873 43.580718)</td>
</tr>
</table>
$('#wktInput').click(function(){
???
???
var asTextGeometryText =
$("#wktResult").text(asTextGeometryText);
});
<textarea name='wktResult' value ='wktResult' ROWS="10" COLS="50" >'Should Display AsText(Geometry Column here!'</textarea>
This is the DOM
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var fieldNames = aResult.fieldNames;
var records = aResult.data;
var numFields = fieldNames.length;
var numRecords = records.length;
var container = document.getElementById('queryResults');
container.innerHTML = '';
var table = document.createElement('table');
container.appendChild(table);
var headerRow = document.createElement('tr');
table.appendChild(headerRow);
for(var i = 0; i < numFields; i++){
var header = document.createElement('th');
header.innerText = fieldNames[i];
headerRow.appendChild(header);
}
for(var i = 0; i < numRecords; i++){
var tableRow = document.createElement('tr');
table.appendChild(tableRow);
for(var j = 0; j < numFields; j++){
var tableData = document.createElement('td');
tableRow.appendChild(tableData);
tableData.innerText = records[i][j];
}
}
}
<input id='SQLinput' size="90" rows="3" value = 'SELECT name, AsText(Geometry) FROM Roads Where MbrContains(Geometry, MakePoint(7.120872,43.580722,4326))'></input>
<input type='button' class='button' value='Display AsText' ontouchend='wktAsTextInput'/>
Thanks in advance
It seems that texarea uses id for value.
<textarea id="field1">example text</textarea>
[This problem is related to textarea in jQuery as well][1]
This example below demonstrate that jquery is not working in textarea using id.
<script type="text/javascript">
$(function() {
$('button').click(function() {
var row = $('input:first').val();
var column = $('input:eq(1)').val();
var cell = $('table tr:eq('+row+') td:eq('+column+')');
if (cell.length == 0) {
$('#value').text('Undefined');
}
else {
$('#value').text(cell.text());
}
});
});
</script>
</head>
<body>
<h1>Table Cell Value</h1>
<table>
<tr><td>Cell 1-1</td><td>Cell 1-2</td><td>Cell 1-3</td></tr>
<tr><td>Cell 2-1</td><td>Cell 2-2</td><td>Cell 2-3</td></tr>
<tr><td>Cell 3-1</td><td>Cell 3-2</td><td>Cell 3-3</td></tr>
</table>
Row: <input type="text" value="0">
Column: <input type="text" value="0">
Value: <span id="value">?</span><br>
Textarea: <textarea id="value" >Try this! this is not working</textarea>
<button>Get Value</button>
All is working in this example. Then added a textarea to see if I can make it work. Textarea is not working in this example. Something wrong with jquery and textarea using id as well as name.
Textarea: <textarea name="value" >Try this! this is not work as well</textarea>
How this does not work.
New info about this textarea value.
$('#id_of_textarea').attr('value'); //to get and...
$('#id_of_textarea').attr('value','updated value of textarea'); //to set it...
<textarea id="editor_desc" onkeyup="update_textarea(this)"></textarea>
function update_textarea(obj)
{
$('#mydiv').text($(obj).attr('value')); //whatever you type in the textarea would be reflected in #mydiv
}
http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
It seems that my problem is not rendering a regular html tablet but a direct render to the screen.
The author of QuickConnect say told me,
If you want one of those values so that you can use it you need to pull it
out of the 2D array.
Do you mean displaying the content in AsText(Geometry) column at the textarea?
var text = []
$('table').find('tr:has(td)').each(function(){
text.push($.trim($(this).find('td:eq(1)').html()));
})
// and you set it to your textarea
$('textarea[name="wktResult"]').val(text.join('\n'));
1- assign an id attribute to your textarea to use it in jquery or if your page contain just one textarea you can use tag name insteasd.
2- to get text of textarea you need just call text function without any parameters
$('#wktInput').click(function(){
var asTextGeometryText =$('table').find('th').eq(2).text();
$('#id_of_textarea').attr('value',asTextGeometryText);
});