Dynamically changing the Tab Index for the textbox - javascript

I have a requirement to accomplish to change the tab index of the cursor based on how the user wishes to perform. I am not sure what is the best way to achieve this. I have created a fiddle to ensure what is explained here is understood by all.
The requirement is the following:
There is a table with a series of text box on all the rows and columns.
A radio button is provided below the table for the user to be able to move through the text boxes on the table.
Selecting "Move Horizontally" will make the cursor move from each textbox horizontally when a tab is pressed or the max length is reached.
Selection "Move Vertically" will make the cursor move from each textbox vertically when a tab is pressed or the max length is reached.
By default the tab indexes move vertically.
When reaching the last textbox on either the row on the column, the cursor should automatically move to the next row or columns first textbox.
How can I achieve this dynamically when selecting the radio buttons.
JS Fiddle: http://jsfiddle.net/2uzfT/4/embedded/result/

Your Complete Solution :)
HTML
<table border="1" id="mytable">
<thead>
<tr>
<th> Description </th>
<th> Column1 </th>
<th> Column2 </th>
<th> Column3 </th>
</tr>
</thead>
<tbody>
<tr>
<td> Stephen </td>
<td><input type="text">
</td>
<td><input type="text">
</td>
<td><input type="text">
</td>
</tr>
<tr>
<td> Malcom </td>
<td><input type="text">
</td>
<td><input type="text">
</td>
<td><input type="text">
</td>
</tr>
<tr>
<td> Judith </td>
<td><input type="text">
</td>
<td><input type="text">
</td>
<td><input type="text">
</td>
</tr>
</tbody>
</table>
<br>
<br>
<INPUT TYPE=RADIO NAME="selection" VALUE="V">
Move Verically<BR>
<INPUT TYPE=RADIO NAME="selection" VALUE="H">
Move Horizontally<BR>
jQuery
$(function() {
var inputBox = $('#mytable input[type="text"]').length;
var row = $('#mytable tbody tr').length;
var column = $('#mytable tbody tr:first td').length;
// Vertical
$('input:radio').change(function() {
var self = $(this);
if(self.val() == "V") {
var counter = 1;
for(i=1; i<column; i++) {
for(j=2; j<=row+1; j++) {
$('#mytable tbody tr td:nth-child('+j+')').find('input[type="text"]').attr('tabindex', counter);
counter++;
}
}
}
else {
$('#mytable input[type="text"]').removeAttr('tabindex');
}
});
});

A rough idea is below by jQuery:
// For columns
var textBoxes = $('#tableid input[type="textbox"]').length;
var rowNums = 4;
for(i=0; i<=textBoxes; i++) {
for(j=0; j<=rowNums; j++) {
$('#tableid').find('tr:eq('+j+') input[type="textbox"]').attr('tabindex', i);
}
}
Row indexing can be done also same as above

Related

Dragging a html table column value and increment the column value by 1 in java script

I need to increment an html table column value by 1.
For example, I have three columns in the table and the column value for the first row is 1, the second should be 2 etc.
So, If I have Roll No column with first column value is 1 then the next two rows Roll No value should be 2 and 3.
The following script does not work.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
//document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('sample_table');
var rollNo=document.getElementById('input2').value;
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
var count=0;
for (var i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
count++;
//alert('hi'+count);
if(count>1){
myTab.rows[i].cells[j+1].innerHTML=rollNo+1;
}
}
}
}
</script>
</head>
<body onload="myFunction()">
<table id='sample_table'>
<tr>
<th> Name</th>
<th> Roll No</th>
</tr>
<tr>
<td><input id='input1' value='abc' readonly></td>
<td><input id='input2' value='1' ></td>
</tr>
<tr>
<td><input id='input3' value='def' readonly></td>
<td><input id='input4' ></td>
</tr>
<tr>
<td><input id='input5' value='xyz' readonly></td>
<td><input id='input6' ></td>
</tr>
</table>
</body>
</html>
You can get all the inputs in a column using querySelectorAll, like this:
document.addEventListener('DOMContentLoaded', function() {
// Collects all the inputs from the 2nd column
const inputs = document.querySelectorAll('#sample_table td:nth-child(2) input');
// Get the value of the first input in the collection, and convert it to number
const first = +inputs[0].value;
// Iterate through the inputs in the collection excluding the first one
for (let n = 1, eN = inputs.length; n < eN; n++) {
inputs[n].value = first + n;
}
});
<table id="sample_table">
<tr>
<th> Name</th>
<th> Roll No</th>
</tr>
<tr>
<td><input id="input1" value="abc" readonly></td>
<td><input id="input2" value="5"></td>
</tr>
<tr>
<td><input id="input3" value="def" readonly></td>
<td><input id="input4"></td>
</tr>
<tr>
<td><input id="input5" value="xyz" readonly></td>
<td><input id="input6"></td>
</tr>
</table>
If the column of the inputs is changed, the number in nth-child() can be changed to point to the correct column. This indexing is 1-based.
I'm guessing something like
rowspan="2"
or
colspan="2"
but we need the code the image is good for reference but we need something to work with.

How to get the value of input type text from the last row of a table

I have a table in my page and i have input type text in each row, one of them is for srno
I want to get the value of srno text box from the last row of the table using JavaScript.
Here's a code snippet with my HTML:
<table id="vattable" class="table table-sm table-striped">
<thead class="thead-light">
<tr>
<th style="width:50px">SRNo</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="text-control input-sm" readonly name="srno[]" id="srno" value=1 style="text-align:right;max-width:40px;" maxlength="13" /></td>
</tr>
</tbody>
</table>
Actually I am adding rows on button click event in JavaScript, I want to get the last value of srno column and give the next srno with +1 each time the row is created in the table. when the page is loaded I am selecting data from database and fetching in this table so sometime this table may have few rows already and when I click button to create row it should take the last srno and add +1 to the new row srno.
I think that this should work for you if you have a similar HTML structure.
What it basically does is:
Scanning the table structure for all inputs with name=srno.
Getting the last input and logging in the javascript console.
You can get its value with lastInput.value.
function getLastInput() {
//get all inputs with name srno in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
return lastInput;
}
$(document).ready(function() {
var rowcnt = $('#vattable tr').length;
var count = rowcnt;
$(document).on('click', '#addrow', function() {
count = count + 1;
var html_code = '';
html_code += '<tr id="row_id_' + count + '">';
html_code += '<td><input type="text" class="text-control input-sm" name="srno[]" id="srno" readonly style="text-align:right;width:40px" value="' + count + '"/></td>';
html_code += '</tr>';
$('#vattable').append(html_code);
console.log(getLastInput());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="vattable">
<tr>
<td>
<input type="text" name="srno[]" value="1" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="2" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="3" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="4" />
</td>
</tr>
</table>
<button id="addrow">Add row</button>
EDIT:
Use this if your input name is srno[].
//get all inputs with name srno[] in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
console.log(lastInput);

How to check if all textboxes in a row are filled using jquery

I have 3 textboxes in each row. At least one of the rows should be filled completely. All the textboxes in any of the rows should not be empty. I have tried below code, it's for the first row only.
var filledtextboxes= $(".setup_series_form tr:first input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
We want to get the maximum number of non-empty textboxes in any row, TIA.
Loop through all the rows. In each row, get the number of filled boxes. If this is higher than the previous maximum, replace the maximum with this count.
var maxboxes = -1;
var maxrow;
$(".setup_series_form tr").each(function(i) {
var filledtextboxes = $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (filledtextboxes > maxboxes) {
maxboxes = filledtextboxes;
maxrow = i;
}
});
You are targeting only first tr here $(".setup_series_form tr:first input:text") so you will not get the expected output.
You have to iterate with every row(tr) inside form and then find the count of
text field having not empty values and store in a maxCount variable by comparing it previous tr count.
Here is a working snippet:
$(document).ready(function() {
var maxCountInRow =0;
var rowNumber;
$(".setup_series_form tr").each(function(index){
var filledtextboxes= $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if(filledtextboxes>maxCountInRow){
maxCountInRow=filledtextboxes;
rowNumber=index;
}
});
console.log("Row Number:"+rowNumber+" having maxCount: "+maxCountInRow);
});
.registrant_table{width: 100%;border: 1px solid #ccc;text-align: center;}
.registrant_table tr td{border: 1px solid #ccc;height: 42px;font-weight: bolder;}
.registrant_table input{border: 0px !important;width: 100%;height: 42px;text-align: center;font-weight: normal;}
label.error{color: red !important;}
.err-fields{background-color:red;color: white !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="setup_series_form">
<div>
<table class="registrant_table">
<tr class="title">
<td>No</td>
<td>Official Full Name</td>
<td>Mobile Contact</td>
<td>Email</td>
</tr>
<tr class="in-fields">
<td>1</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="" name="phone[]"></td>
<td><input type="text" value="" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>2</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="sas" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>3</td>
<td><input type="text" name="firstname[]"></td>
<td><input type="text" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
</table>
</div>
</form>

Code isn’t executed after removing rows in a table

I wrote a JavaScript function to remove selected rows in a table and it works fine but when I try to write some jQuery to change color of some button it doesn’t work. I have no clue what am I doing wrong.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button type="button" onclick="DeleteRow()" class="btn"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
<script>
function DeleteRow() { //this function delete selected rows from table
var i, chkbx, td;
var table = document.getElementById("myTable"); //table itself
var rows = table.getElementsByTagName("tr"); //rows in table-body
var numRows = rows.length; //number of rows
for (i = 1; i < numRows; i++) { //in this "for loop" , I try to remove selected rows
td = rows[i].getElementsByTagName("td")[0];
chkbx = td.getElementsByTagName("input")[0];
if (chkbx.checked == true) {
table.deleteRow(i);
--i; //each time we delete one row we decrease i
}
}
$(document).ready(function() {
$(".btn").css("background-color", "#ff0000");
}); //this jquery wont work
}
</script>
</body>
</html>
There are couple of issues in your loop causing an error, so I've fixed those, and moved your inline event listener to the JS file. Comments in the code. I also switched from jQuery to vanilla JS because there's no reason to use it if you're using vanilla JS everywhere else.
// Grab the button and add an click event for DeleteRow
document.querySelector(".btn").addEventListener('click', DeleteRow, false)
function DeleteRow() {
var i, chkbx, td;
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
// When removing items from the DOM it's usually a good idea
// to reverse the loop and simply use the length of the array.
// That way you don't have to decrement the index manually
for (let i = rows.length - 1; i > 0; i--) {
td = rows[i].getElementsByTagName("td")[0];
chkbx = td.getElementsByTagName("input")[0];
if (chkbx.checked == true) {
table.deleteRow(i);
}
}
// You don't have to use jQuery (it's a waste if everything
// else is native JS. Here we use `this` which is the element attached
// the click event
this.style.backgroundColor = '#ff0000';
}
<button type="button" class="btn"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
A short refined version of your code could be like below. This will only change button background if the row is selected / deleted.
function DeleteRow() { //this function delete selected rows from table
var i, chkbx, td;
var table = $("#myTable tbody>tr input:checked"); //table itself
table.each(function() {
$(this).parent().parent().remove();
})
if (table.length) {
return true;
}
}
$(document).ready(function() {
$('#del').click(function() {
if (DeleteRow()) {
$(".btn").css("background-color", "#ff0000");
}
}); //this jquery wont work
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" id="del"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
If you already have jQuery, why are you mixing it with plain js? You can do this in jQuery very simply:
function DeleteRow() { //this function delete selected rows from table
$('input[type=checkbox]').each(function () {
if ($(this).prop('checked')) {
$(this).closest('tr').remove();
}
});
$(".btn").css("background-color", "#ff0000");
}

Insert HTML table row clone at index without jquery

I am attempting to insert a row at the index of the addmorebutton td row.
First attempt indeed adds a row at the desired index however not as I would have expected, simply as space vs actually adding a bounded row column box.
How do I insert a new row at the clicked index of td that is empty and is indeed apart of the table?
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('Table').deleteRow(i);
}
function addRow() {
var i = row.parentNode.parentNode.rowIndex;
document.getElementByID('Table').insertRow(i);
}
turkSetAssignmentID();
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'>
<input type='hidden' value='' name='assignmentId' id='assignmentId' />
<h1>This is a test</h1>
<div id="tablediv">
<input type="button" id="addbutton" value="Add Index" /><br/><br/>
<table id="Table" border="1">
<tr>
<td>Index</td>
<td>Measured Depth</td>
<td>Inclination</td>
<td>Azimuth</td>
<td>Delete?</td>
<td>Add Row?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="Measured Depth" contenteditable='true'></td>
<td><input size=25 type="text" id="Inclination" contenteditable='true'></td>
<td><input size=25 type="text" id="Azimuth" contenteditable='true'></td>
<td><input type="button" id="delbutton" value="Delete" onclick="deleteRow(this)" /></td>
<td><input type="button" id="addmorebutton" value="Add More Indexs" onclick="addRow.apply(this)" /></td>
</tr>
</table>
</div>
<p><input type='submit' id='submitButton' value='Submit' /></p>
</form>
You could try to add the respective cells to new row, saving the row on a var and the with the appendChild() function. Something like this:
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex + 1;
var nextRow = document.getElementById('Table').insertRow(i);
// Start iterating over all the cells on the row
var cell = nextRow.insertCell(0);
cell.appendChild(document.createTextNode(i));
cell = nextRow.insertCell();
cell = nextRow.insertCell();
cell = nextRow.insertCell();
cell = nextRow.insertCell();
cell = nextRow.insertCell();
input = document.createElement("Input");
input.type = "button";
input.setAttribute("onclick", "addRow(this)");
input.value = "Add More Indexs"
cell.appendChild(input);
}
And of course append on each cell the respective input.
Then maybe you would like to add a function to increase the index number of the rows under the new one...
Also I changed the onclick value on the original button to addRow(this).

Categories

Resources