jquery search for a table cell -> update neighboring cell - javascript

How do I go about finding a table cell with value (text) of "foo" and setting the next cell in that row to "bar"?
The cell to be set may already contain some text that needs to be overwritten.

Try this but i haven`t tested it.
$('td').filter(function(){
return $(this).text() === 'foo'
}).next('td').text('bar')
Demo

var rowList = document.getElementById('tableID').children;
for (var i=0, len = rowList.length; i < len; ++i) {
var row = rowList[i];
var cellList = row.children;
for (var j=0, size = cellList.length; j < size; ++j) {
var cell = cellList[j];
//need additional check to avoid out of bounds issues
if (cell.innerHTML == 'foo' && cellList[j + 1]) {
cellList[j + 1].innerHTML = 'bar';
}
}
}
EDIT
sorry missed the jQuery tag. The answer above is fine but I believe the calls to .text() should be .html()

Related

Name each cell on each row from 1 to 9

the problemI want to make a sudoku solver and to do that I need to name each cell from 1 to 9 in every row. If you know another way to make this please tell me. Here's the code:
function crear (){
var table = document.getElementById("table");
// enter code here
for (var i = 1; i < 10; i++) {
var showfila = document.createElement("TR");
showfila.setAttribute("id", "myTr" + i);
document.getElementById("table").appendChild(showfila);
for (var a = 1; a < 10; a++) {
var input = document.createElement("INPUT");
input.setAttribute("id", "myInp" + a);
document.getElementById("myTr" + i).appendChild(input);
document.getElementById("myInp" + a).value=a;
}
}
}
I'm assuming the "name" you are talking about for each cell is the name property and also that these cells need to be created (based on your code) so you can do something like this:
EDIT
The name now includes the corresponding row and column. I also added comments so that if this is not what you are looking for, you can refer to them to edit your code correctly.
function createTable(){
var table = document.getElementById("table");
//Loop for rows
for (var i = 1; i < 10; i++) {
//Loop for columns
for (var j = 1; j < 10; j++) {
var cell = document.createElement("TR");
//var i would be the row and var j would be the column
cell.name=i+"-"+j;
table.appendChild(cell);
}
}
}

Strange behaviour in the if statement

I have a piece of code that is meant to hide table elements depending on given array. I am running loops to compare innerText of one of the cells and the given array.
However, my if statement is statement is acting weird, once i set the operator to === the operation is successful and table rows that match the array are hidden. But i need my if to hide the elements that are not a part of the array, so naturally I set my operator to !== but once i do it it just executes anyway and of course hides all of the elements in the table.
Any idea why this is happening here is the code:
var td1 = document.querySelectorAll("#course");
var rowss = document.querySelectorAll("#rows");
var courseNames1 = [td1.innerText];
var diff = _.difference(soretedArray, courseNames1)
console.log(diff);
for (var i = 0; i < rowss.length; i++) {
for (var j = 0; j < diff.length; j++) {
if (td1[i].innerText === diff[j]) { // if i set the logic operator to !== it hides all of the elements rather the ones that don't match
console.log(rowss[i]);
rowss[i].style.display = "none";
break;
}
}
}
I added the code as I have understood your request: You want the negation of "contains" to hide the element. This is as complete as possible based on the information you gave.
var soretedArray = [];//initialized elsewhere
var td1 = document.querySelectorAll("#course");
var rowss = document.querySelectorAll("#rows");
function tdContains(td) {
for(var j= 0 ; j< soretedArray.length; j++){
if(td.innerText === soretedArray[j]){
return true;
}
}
return false;
}
for(var i = 0 ; i < rowss.length; i++){
if(!tdContains(td1[i])) {
console.log(rowss[i]);
rowss[i].style.display= "none";
}
}

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

table row incertCell : Index or size was negative, or greater than the allowed value

when I try to dynamically insert cells to a table with an unknown size (in cells) I got an "Index or size was negative, or greater than the allowed value." error :
function addTableRow(id, at)
{
at = typeof at !== 'undefined' ? at : 0;
var table=document.getElementById(id);
var row=table.insertRow(at);
var cells = table.rows[0].cells.length;
for(var i = 0; i < cells; ++i)
{
row.insertCell(i);
row.className="success";
row.innerHTML = "OMG";
}
}
and if I put an alert in the 'for' the error happens in the second row, I think I miss something somewhere, any idea ?
You're overriding the content of the tr when setting some innerHTML to it. This wipes out the first created td, and if there's not existing row.cells[0], you can't create row.cells[1]. This causes the invalid index error.
You can fix your problem by setting the innerHTML of the newly created cell instead:
for (var i = 0; i < cells; ++i) {
var cell = row.insertCell(i);
cell.className = "success"; // or row.className?
cell.innerHTML = "OMG";
}
A live demo at jsFiddle.

javascript equivalent of jquery code

Can someone help what's the javascript equivalent of below jquery line.
$("#abc option[value='1']").text();
abc is the id of selectbox
var options = document.getElementById("abc").options;
for (var i = 0, j = options.length; i < j; i++) {
if (options[i].value == "1") {
alert(options[i].text);
}
}
The value and text attributes are available on the HTMLOptionElement per DOM Level 2.
(demo)
UPDATE
Updated demo with combined text, cf. comments:
var options = document.getElementById("abc").options,
text = "";
for (var i = 0, j = options.length; i < j; i++) {
if (options[i].value == "1") {
text += options[i].text;
}
}
This would be 100% equivalent to the selector:
var options = document.getElementById('abc').getElementsByTagName('option'),
text = "";
for(var i = 0, l = options.length; i < l; i++) {
var option = options[i];
if(option.value === '1') {
text += option.text;
}
}
Or if querySelectorAll is available:
var options = document.querySelectorAll('#abc option[value="1"]'),
text = "";
for(var i = 0, l = options.length; i < l; i++) {
text += options[i].text;
}
That said, you can make improvements depending on the HTML structure (e.g. if #abc is the select element etc).
In modern browsers it can be:
var option = document.querySelector('#abc option[value="1"]').textContent
The statement doesn't make sense. It gets the text from an option, and then just throws it away. I assume that you want to do something with the text, like assigning it to a variable.
// A variable for the result
var text = null;
// Get the options from the select element
var options = document.getElementById('abc').options;
// Find the option with the value "1"
for (var i = 0; i < options.length; i++) {
if (options[i].value == '1') {
// Get the text from the option
text = options[i].text;
// Exit from the loop
break;
}
}
Note: The original code would get the text from all options with the specified value, but this code only gets the text from the first option found. Having more than one option with the same value is pretty useless, so that feature of the original code is most likely unintended.
This Will Work.
document.querySelector(".producer option[value='1']").text;

Categories

Resources