Not able to get selected word using jQuery UI selectable - javascript

I am trying to make an annotation tool, where I will select some words and get their relative start and indices in the sentence.
I am using jQuery UI's selectable tool to select word(s) and get their data attributes out of them.
In this example, I want to select the splitted word(s): (HELLO, ,, WORLD, .) and get their data attributes out of them.
My hierarchy of div(s) is as follows:
#tblText > tbody > tr > td > #0 > div#div0.uiselectee.ui-selected
$(function() {
$('#btnAddUtterance').click(function() {
populateUtterance();
});
var selected1 = new Array();
$(".tokenized").selectable({
selected: function(event, ui) {
debugger;
alert(ui.selected.innerHTML);
selected1.push(ui.selected.id);
},
unselected: function(event, ui) {
//ui.unselected.id
}
});
var uttIdx = 0;
var tokenizedUtterances = new Array();
function populateUtterance() {
let userUtterance = $('#myInput').val();
let tokenizedUtterance = tokenizeUtterance(userUtterance, uttIdx);
let markup = `<tr><td><input type='checkbox' name='record'></td><td> ${tokenizedUtterance} </td> <td>${userUtterance}</td></tr>`;
$("#tblText tbody").append(markup);
uttIdx += 1;
$('#myInput').val('');
}
$("#myInput").keyup(function(event) {
if (event.keyCode === 13) {
populateUtterance();
}
});
function findSpacesIndex(utterance) {
let index = 0;
let spacesIndex = [];
while ((index = utterance.indexOf(' ', index + 1)) > 0) {
spacesIndex.push(index);
}
return spacesIndex;
}
function createUtteranceLookup(utterance) {
let lookUpObject = new Array();
utterance.replace(/[\w'-]+|[^\w\s]+/g, (word, offset) =>
lookUpObject.push({
word: word,
start: offset,
end: offset + word.length
}));
return lookUpObject;
}
function tokenizeUtterance(utterance) {
let div = `<div id=${uttIdx} class ='tokenizedUtterance'>`;
let spacesIndex = new Array();
spacesIndex = findSpacesIndex(utterance);
let utteranceLookup = new Array();
for (let i = 0; i < spacesIndex.length; i++) {
utteranceLookup.push({
word: " ",
start: spacesIndex[i],
end: spacesIndex[i]
});
}
let wordsIndex = [];
wordsIndex = createUtteranceLookup(utterance);
Array.prototype.push.apply(utteranceLookup, wordsIndex);
utteranceLookup.sort(function(obj1, obj2) {
return obj1.start - obj2.start;
});
for (let i = 0; i < utteranceLookup.length; i++)
utteranceLookup[i]["wordIndexInSentence"] = i;
$.each(wordsIndex, function(index, item) {
let divId = "div" + index;
let divStart = item.start;
let divEnd = item.end;
let divValue = item.word;
div += `<div style="display:inline-block;margin:5px; border: 1px solid black;" id = "${divId}" data-start=${divStart} data-end= ${divEnd} data-value= "${divValue}"> ${item.word} </div >`;
});
tokenizedUtterances.push({
UtteranceNumber: uttIdx,
tokenizedUtteranceLookup: utteranceLookup
});
div += '</div>';
$('#testOutput').html('');
$('#testOutput').html(JSON.stringify(tokenizedUtterances, undefined, 2));
utteranceLookup = new Array();
return div;
}
$(document).on("click", '#tblText > tbody > tr > td:nth-child(2)', function(event) {
//if ctrl key or left click is pressed, select tokenized word
if (event.ctrlKey || event.which === 1) {
$('.tokenizedUtterance').selectable();
}
console.log("Selected");
});
// Find and remove selected table rows
$(document).on('click', '#btnDeleteRow', function(e) {
$("#tblText tbody").find('input[name="record"]').each(function() {
if ($(this).is(":checked")) {
$(this).parents("tr").remove();
$('#testOutput').html('');
}
});
});
});
.tokenizedUtterance .ui-selecting {
background: #FFFF99;
}
.tokenizedUtterance .ui-selected {
background: #FFFF00;
font-family: 'Segoe UI';
font-style: italic
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<h2>AnnotationView</h2>
<h2>Enter text to annotate</h2>
<input type="text" id="myInput" />
<button id="btnAddUtterance" class="btn btn-info">Add Utterance</button>
<table id="tblText" class="table table-hover">
<thead>
<tr>
<th>Select</th>
<th>Tokenized User Utterance</th>
<th>Original Utterance</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id='btnDeleteRow' class='btn btn-danger'>Delete Utterance</button>
<span>You've selected:</span> <span id="select-result"></span>.
<hr />
<h1>Output is: </h1> <br />
<pre id="testOutput" style="word-wrap: break-word; white-space: pre-wrap;"></pre>
Here's a Fiddle of the app
Any help will be greatly appreciated.

I believe this is what you are looking for - PEN
We can make use of the selected and unselecting events in the Selectable Widget.
The selected elements are stored in a variable elem. Hope you can use this variable to access the data variables and construct the JSON. Please let me know whether this helps.

Related

Want to remove previously appended table

When I Click on submit button after clicking on the links it appends perfectly but when I hit the button again it doesn't remove previously appended table.
I want to clear the previously created table when user clicks on the cross button and then print the table again or else overwrite the table but instead it is not removing the table and prints a new one.Image Part OneImage Part TwoImage Part ThreeImage Part Four
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(" + i + ")'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
}
//To Remove The Specific Element User Want To Delete
function remove(id) {
orders_list.splice(id, id);
loop("t");
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>
Update your remove function as function remove(el) { el.closest('table').remove(); }.
Update parameter in html as "</td><td onclick='remove(this)'>×</td></tr>".
And add orders_list = []; in the end of loop function.
Try it below.
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(this)'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
orders_list = [];
}
//To Remove The Specific Element User Want To Delete
function remove(el) {
el.closest('table').remove();
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

How to query an AJAX imported table (instead of a local table) using javascript

Currently, I have a script that searches column 1 of a locally-stored table, and returns the result from column 2 from the same row. Based on that result, it logs something to the console.
Here it is action. It searches the table for "dragon" in column 1, returns "2" from Column 2, then the script logs "The result is two." to the console.
var username = 'dragon'
const searchDataSetByKey = (dataSet, key) => {
return dataSet.find((data) => data[0] === key)
}
document.addEventListener('DOMContentLoaded', () => {
var tableToArray = Array
.from(document.querySelectorAll('tr'))
.reduce((_tableToArray, tableRow, tableRowIndex) => {
if(tableRowIndex !== 0) {
var tableData = tableRow.querySelectorAll('td')
var key = tableData.item(0).innerText
var value = tableData.item(1).innerText
_tableToArray.push([key, value])
}
return _tableToArray
}, [])
var searchString = searchDataSetByKey(tableToArray,username).toString()
var oneSearch = searchString.indexOf("1")
var twoSearch = searchString.indexOf("2")
var threeSearch = searchString.indexOf("3")
if (oneSearch >= 0) {
console.log('The result is one!');}
else if (twoSearch >= 0) {
console.log('This result is two.');}
else if (threeSearch >= 0) {
console.log('The answer is three! :)');}
})
<html>
<script src="script.js"></script>
<body>
<table>
<tr>
<th>Username</th>
<th>1/2/3</th>
</tr>
<tr>
<td>wisp</td>
<td>1</td>
</tr>
<tr>
<td>husky</td>
<td>2</td>
</tr>
<tr>
<td>dragon</td>
<td>2</td>
</tr>
<tr>
<td>woop</td>
<td>3</td>
</tr>
<tr>
<td>e6</td>
<td>1</td>
</tr>
</table>
</body>
</html>
This is great for locally-stored tables. The issue is, I'd like to get the same result from a Google Sheet. I've found a way to store the info from a Google Sheet into a HTML table using AJAX. The code for this can be seen here:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function drawCell(tr, val) {
var td = $("<td/>");
tr.append(td);
td.append(val);
return td;
}
function drawRow(table, rowData) {
if (rowData == null) return null;
if (rowData.length == 0) return null;
var tr = $("<tr/>");
table.append(tr);
for(var c=0; c<rowData.length; c++) {
drawCell(tr, rowData[c]);
}
return tr;
}
function drawTable(parent) {
var table = $("<table/>");
parent.append(table);
return table;
}
function readData(parent) {
var data = spData;
var table = drawTable(parent);
var rowData = [];
for(var r=0; r<data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
if (cell.col == 1) {
drawRow(table, rowData);
rowData = [];
}
rowData.push(val);
}
drawRow(table, rowData);
}
$(document).ready(function(){
readData($("#data"));
});
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData"></script>
<style type="text/css" media="print">
form {display: none;}
</style>
</head>
<body>
<div id="data"/>
</body>
</html>
I was wondering if there was any way of achieving what was done in the local HTML table, with this AJAX imported HTML table?
Thanks!
It's exactly the same work that you need to do, albeit at a different time - i.e in response to a different event. Do it straight after you've loaded the table, instead of straight after you've received the DOMContentLoaded event from the document. Here's an alternate way to go looking.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function drawCell(tr, val) {
var td = $("<td/>");
tr.append(td);
td.append(val);
return td;
}
function drawRow(table, rowData) {
if (rowData == null) return null;
if (rowData.length == 0) return null;
var tr = $("<tr/>");
table.append(tr);
for(var c=0; c<rowData.length; c++) {
drawCell(tr, rowData[c]);
}
return tr;
}
function drawTable(parent) {
var table = $("<table/>");
parent.append(table);
return table;
}
function readData(parent) {
var data = spData;
var table = drawTable(parent);
var rowData = [];
for(var r=0; r<data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
if (cell.col == 1) {
drawRow(table, rowData);
rowData = [];
}
rowData.push(val);
}
drawRow(table, rowData);
}
$(document).ready(function(){
readData($("#data"));
searchTable( 'dragon', document.querySelector('table') );
});
function searchTable(searchStr, target)
{
let rows = Array.from( target.querySelectorAll('tr') );
rows.forEach( (row,idx,col) => {
let firstCell = row.querySelector('td').textContent;
if (firstCell == searchStr)
{
let cell2 = row.querySelectorAll('td')[1].textContent;
console.log(`${searchStr} found in row ${idx}`);
console.log(`col 2 of row #${idx} is: ${cell2}`);
}
}
);
}
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData"></script>
<style type="text/css" media="print">
form {display: none;}
</style>
</head>
<body>
<div id="data"/>
</body>
</html>

Take the values of a text input and store them into an array

My code can be found here: https://www.w3schools.com/code/tryit.asp?filename=FHC2UOT0RQX6
The program accepts an array var array=[1,0,1,0,1,1,0,0,0] and solves the pseudoternary encoding scheme. All i want to do is simple. Insead of changing the elements of the array(when i want to insert a different input), i want to use the input text and take the values from it and when i press enter or the submit button, it will solve the problem depending on the user inputs. Is that possible to take the values of the text input and make them act as an array ?
Here is the script below but it is better to see the whole code, use the link above.
<script type="text/javascript">
var array=[1,0,1,0,1,1,0,0,0]; //input here
var text="";
for(var b=0;b<array.length;b++)
{
text+=array[b];
}
document.getElementById('enc').innerHTML=text;
pseudo(array);
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
for(var b=0;b<array.length;b++)
if(a[b]===1)
{
count++;
document.write('<img src="http://i.imgur.com/30DU9iC.png">');
}
else if(a[b]===0)
{
count++;
pulse=!pulse; //toggles boolean value each time it finds zero
if(pulse===true) //pulse shows up
{
document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
}
else{
document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
}
}
}
</script>
Actually you want to write your code inside a function and call the function onload and onclick respectively. Try this, http://www.w3schools.com/code/tryit.asp?filename=FALV2XZQ7V36
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
function loading() {
for (var b = 0; b < array.length; b++) {
text += array[b];
}
document.getElementById('enc').innerHTML = text;
pseudo(array);
}
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
var output = '';
var b = 0;
for (b = 0; b < a.length; b++)
if (a[b] === 1) {
count++;
//document.write('<p class="w3-center w3-text-red">'+'Step '+count+': No line'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/30DU9iC.png">');
output += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
//document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes up'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
output += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
// document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes down'+'<br>'+'</p>');
//document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
output += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
document.getElementById("js").innerHTML = output;
}
function gettext() {
var inputText = document.getElementById("tf").value;
var inparray = [inputText.length];
for (i in inputText) {
inparray[i] = parseInt(inputText[i]);
}
document.getElementById('enc').innerHTML = inputText;
pseudo(inparray);
}
body {} .pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
<html>
<head>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<!-- <link rel="stylesheet" href="style.css" type="text/css"/>-->
<h4>Use this input </h4>
<input type="text" id="tf"></input>
<input type="button" style="width:50px;" value="solve" onclick="gettext()" id="tf"></input>
</head>
<body onload="loading()" ;>
<h1>Illustration of pseudoternary encoding scheme </h1>
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center">
</div>
</body>
</html>
Note, <input> element is self-closing. <input> element should be child nodes of <body> element instead of <head> element. id of element in document should be unique. Replace duplicate "tf" id at input elements with unique values. Remove <script> element from being child node of div element. Place <script> element before closing </body> tag. Substitute concatenating .innerHTML for document.write()
Attach click event to input type="button", use String.prototype.split() with parameter "" to create an array from input type="text" .value, Array.prototype.map() with parameter Number to convert String to Number values. Assign resulting array to array variable. Set #js .innerHTML to empty string before calling function again with array as parameter.
<!DOCTYPE html>
<html>
<head>
<style>
body {}
.pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
</style>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h4 style="margin-top:240px;position:absolute">Use this input </h4>
<h1>Illustration of pseudoternary encoding scheme </h1>
<input type="text" style="position:relative" id="tf">
<input type="button" style="position:relative;width:50px;" value="solve" id="button">
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center"> </div>
<script>
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
var enc = document.getElementById("enc");
var button = document.getElementById("button");
var tf = document.getElementById("tf");
var center = document.getElementById("js");
for (var b = 0; b < array.length; b++) {
text += array[b];
}
enc.innerHTML = text;
pseudo(array);
function pseudo(a) {
var pulse = false;
var count = 0;
for (var b = 0; b < array.length; b++)
if (a[b] === 1) {
count++;
center.innerHTML += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
center.innerHTML += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
center.innerHTML += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
}
button.onclick = function() {
array = tf.value.split("").map(Number);
enc.innerHTML = array.join("");
console.log(array, enc);
center.innerHTML = "";
pseudo(array)
}
</script>
</body>
</html>

Insert multiple rows and columns to a table in html dynamically using javascript code

I am trying to insert multiple rows and columns to create a table in html dynamically by selecting the number of rows and columns in dropdown list using javascript code like in MS Word.
For example if I select number of rows as 5 and number of columns as 5 from the dropdown list of numbers. 5 rows and 5 columns should get displayed.
My question is how can I add multiple rows and columns dynamically to create a table by selecting the number of rows and columns from the drop down list.
Since, <table> element is the one of the most complex structures in HTML, HTML DOM provide new interface HTMLTableElement with special properties and methods for manipulating the layout and presentation of tables in an HTML document.
So, if you want to accomplish expected result using DOM standards you can use something like this:
Demo old
Demo new
HTML:
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="copy" />
</li>
</ul>
<div id="wrap"></div>
JS new:
JavaScript was improved.
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row = generateRow(nOfColumns);
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text = document.createTextNode("cell");
for (var i = 0; i < n; i++) {
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
JS old:
(function () {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
copy = document.getElementById("copy"),
nOfColumns = -1,
nOfRows = -1;
btnGen.addEventListener("click", generateTable);
copy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
caption = newTable.createCaption(),
//tHead = newTable.createTHead(),
//tFoot = newTable.createTFoot(),
tBody = newTable.createTBody();
nOfColumns = parseInt(setColumn.value, 10);
nOfRows = parseInt(setRow.value, 10);
caption.appendChild(document.createTextNode("Generated Table"));
// appendRows(tHead, 1);
// appendRows(tFoot, 1);
appendRows(tBody);
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.firstElementChild);
}
function appendColumns(tElement, count) {
var cell = null,
indexOfRow = [].indexOf.call(tElement.parentNode.rows, tElement) + 1,
indexOfColumn = -1;
count = count || nOfColumns;
for (var i = 0; i < count; i++) {
cell = tElement.insertCell(i);
indexOfColumn = [].indexOf.call(tElement.cells, cell) + 1;
cell.appendChild(document.createTextNode("Cell " + indexOfColumn + "," + indexOfRow));
}
}
function appendRows(tElement, count) {
var row = null;
count = count || nOfRows;
for (var i = 0; i < count; i++) {
row = tElement.insertRow(i);
appendColumns(row);
}
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}());
If you want to copy generated result to clipboard you can look at answer of Jarek Milewski - How to copy to the clipboard in JavaScript?
You can use this function to generate dynamic table with no of rows and cols you want:
function createTable() {
var a, b, tableEle, rowEle, colEle;
var myTableDiv = document.getElementById("DynamicTable");
a = document.getElementById('txtRows').value; //No of rows you want
b = document.getElementById('txtColumns').value; //No of column you want
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableEle = document.createElement('table');
for (var i = 0; i < a; i++) {
rowEle = document.createElement('tr');
for (var j = 0; j < b; j++) {
colEle = document.createElement('td');
rowEle.appendChild(colEle);
}
tableEle.appendChild(rowEle);
}
$(myTableDiv).html(tableEle);
}
}
Try something like this:
var
tds = '<td>Data'.repeat(col_cnt),
trs = ('<tr>'+tds).repeat(row_cnt),
table = '<table>' + trs + '</table>;
Then place the table in your container:
document.getElementById('tablePreviewArea').innerHTML = table;
Or with JQuery:
$('#tablePreviewArea').html(table);
Here is the JSFiddle using native js.
Here is the JSFiddle using jQuery.
About the string repeat function
I got the repeat function from here:
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
I had one sample code...try this and modify it according to your requirement. May it helps you out.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#mytab td{
width:100px;
height:20px;
background:#cccccc;
}
</style>
<script type="text/javascript">
function addRow(){
var root=document.getElementById('mytab').getElementsByTagName('tbody')[0];
var rows=root.getElementsByTagName('tr');
var clone=cloneEl(rows[rows.length-1]);
root.appendChild(clone);
}
function addColumn(){
var rows=document.getElementById('mytab').getElementsByTagName('tr'), i=0, r, c, clone;
while(r=rows[i++]){
c=r.getElementsByTagName('td');
clone=cloneEl(c[c.length-1]);
c[0].parentNode.appendChild(clone);
}
}
function cloneEl(el){
var clo=el.cloneNode(true);
return clo;
}
</script>
</head>
<body>
<form action="">
<input type="button" value="Add a Row" onclick="addRow()">
<input type="button" value="Add a Column" onclick="addColumn()">
</form>
<br>
<table id="mytab" border="1" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Instead of button , you can use select menu and pass the value to variable. It will create row ,column as per the value.

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

Categories

Resources