Adding a new row to html table on click event - javascript

I have a list with names, each name has a sublist with subitems.
I need to pass those subitems to the table when I click on the name.
Here is an example, try to expand the first name.
But if I click on it again, it will keep adding that value to different cells of the table. How may I add this only once ? Or always at the same place?
Also, I have some attributes of the disciplines:
data-time = The time the discipline start;
data-id = The ID of that discipline (all brought from database);
My Code:
/*JQuery*/
$(document).ready(function(){
$(".prof-list h3").click(function(event){
var obj = event.target;
var disciplina_id = $(this).next().find('li').data('id');
var disciplina_hora = $(this).next().find('li').data('time');
if(disciplina_hora == "14:30:00"){
var myRow = document.getElementById("prof-table").rows[3];
myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
}
else if(disciplina_hora == "08:30:00"){
var myRow = document.getElementById("prof-table").rows[1];
myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
}
if(obj.nodeName == "H3")
$(this).next().slideToggle();//Aplica efeito slide
//$("#list_prof").html("clicked: " + event.target.nodeName ); //Teste
})
})

use .cells[] to update cell content
if(disciplina_hora == "14:30:00"){
var myRow = document.getElementById("prof-table").rows[3];
// insert if `myRow` only has 1 cell
if(myRow.cells.length <= 1)
myRow.insertCell(1);
// use `cells[1]` to update the 2nd cell content
myRow.cells[1].innerHTML = $(this).next().find('li').text();
}
Edit Update
if(myRow.cells.length <= 1){
$(this).next().find('li').each(function(idx, elm) {
myRow.insertCell(idx + 1);
myRow.cells[idx + 1].innerHTML = $(elm).text();
});
} else {
while(myRow.cells.length > 1)
myRow.deleteCell(1);
}

Related

How to refresh the enhanced grid?

I am using dojo 1.10 enhanced grid. Here after loading the grid we are using onStyleRow to highlight the grid row and cells but the problem is we only see highlighted a cell when we mouse hover the grid. Also, each time we update the new rows with color in store only.
My code is this -
function rowHighlighting()
{
dojo.connect(mygrid, 'onStyleRow' , this, function(row){
var item = mygrid.getItem(row.index);
if(item){
var store = mygrid.store;
var type = store.getValue(item, 'ExceptionFixed',null);
if(type == '1'){
row.customStyles += 'font-weight: bold !important;';
var cols = store.getValue(item, 'ExceptionFixedColumns',null);
cols = cols.split(",");
for(var i=0; i<cols.length;i++){
var nd = dojo.query('td[idx="' + i + '"]', row.node)[0];
if (cols[i] == "1" && _this.context.options.hideFixesVisibility.get("value") == 'Editable')
nd.style.color = "blue";
else
nd.style.color = "black";
}
}
}
});
//dijit.byId('grid').resize();
// mygrid.render();
}
After this was not working I try to manually refresh the grid. By like this -
dijit.byId('grid').resize()
and this also
grid.render()
But it doesn't work. So, how can we manually do it as store is not reflecting?

Determine radio button not selected anymore

I wrote a javascript function that change the style of a div (here a TR tag) when I select a radio button in form (called by onchange event).
function handleCheck(myRadio) {
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.style.backgroundColor = "black";
col.style.color = "white";
}
However, often when you select option X another option is deselected while you can select only one value at the time in the same. This option is not triggered by the onchange event. Is there a way to determine that a radio button is not checked any more?
You will have to clear previously assigned classes. Take a look at this example:
function handleCheck(myRadio) {
clear(myRadio.className);
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.className += ' selected';
}
function clear(className) {
var tr = document.querySelectorAll('tr.vak' + className);
for (var i = 0; i < tr.length; i++) {
tr[i].className = 'vak' + className;
}
}
Demo: http://jsfiddle.net/abh7guv5/
If I understood correctly what you are trying to achieve, simply read document.getElementById("myRadio").checked - it will be true or false
well, if I understand you correctly, you have a function that applies some styles whenever you check a radio button, but you also would like to remove styles from elements, that corresponds to already unchecked buttons. If yes, you can store your previous checked item in a variable, then you might want something like:
var previousElement = null;
function handleCheck(myRadio) {
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.style.backgroundColor = "black";
col.style.color = "white";
if(previousElement!==null&&previousElement!==col){
previousElement.style.color = ""; // or whatever you want
}
previousElement = col;
}

jQuery loop through table to display values

I'm at a loss here.
I created a quick script that will add a new row to a table and also has the capability to delete a row.
jsFiddle -->http://jsfiddle.net/wLpJr/10/
What I want to achieve is this:
Display each value of each row (in the div with id='thedata')
I originally started off with adding a number at the end of each id, starting at '1', and incrementing each time the user adds a row.
//This is random code
var rowcount = parseInt($('#rowcount').val());
var newcount = rowcount + (1*1);
var x = $('#radioinput' + newcount).val('a value');
$('#rowcount').val(newcount);
The problem is that lets say you add 5 rows. Now delete row 3. When you loop through the table of data you will get an error because row "3" does not exist. You have rows 1, 2, 4, 5, 6. Specifically - the input with id = 'radioinput3' will not be present.
I then decided to do this:
$('#maintable > tbody > tr').each(function() {
radiovalue[i] = $("input[type='hidden']", this).map(function() {
var vid = 'radio' + i;
var myval = this.value;
var radioinput = document.createElement("input");
radioinput.type = "hidden";
radioinput.value = myval; // set the CSS class
radioinput.id = vid;
$('#maintable').append(radioinput);
}).get()
text1value[i] = $('td > input', this).map(function() {
var vid = 'text1pos' + i;
var myval = this.value;
var text1input = document.createElement('input');
text1input.type='hidden';
text1input.value = myval;
text1input.id = vid;
$('#maintable').append(text1input);
}).get()
text2value[i] = $('td > input', this).map(function() {
var vid = 'text2pos' + i;
var myval = this.value;
var text2input = document.createElement('input');
text2input.type='hidden';
text2input.value = myval;
text2input.id = vid;
$('#maintable').append(text2input);
}).get();
});
The problem here is that I'm getting 'undefined' values.
You are looping through a counter, which you increment everytime you add a new row, but do not take into account that a row can be deleted at any time. Instead, just use the each function to loop over the elements remaining in the DOM.
Add thead and tbody tags to your table, it will make your life easier.
I'm not sure why you have those hidden div to hold the input[type=radio] values, you don;t need them, access the values directly.
$('#showdata').click(function() {
$("#maintable tbody tr").each(function(i, v) {
var myp = "<p>Radio value is = " + $(this).find('input[type=radio]:checked').val()
+ "\nText1 value is = " + $(this).find('input[id$=text1]').val()
+ "\nText2 value is = " + $(this).find('input[id$=text2]').val() + "</p>";
$('#thedata').append(myp);
});
});
jsFiddle Demo
You could add a CSS class to the input text fields to make it easier to get, but i just used the jQuery ends with selector.
Also, you delete selector if far too high up the DOM tree on (document), instead restrict it as near as you can, in this case the #maintable.

Printing array into table through javascript

Currently when you add some values in the 4 textboxes identified by "Special" it outputs in a concatenated string. How would I break that up into a table where I could print it out in a table nicely.
$add.click(function() {
var elem = document.createElement("div");
var dmenu = document.getElementById("days");
var dmenuvalue = dmenu.options[dmenu.selectedIndex].text;
var regex = /^\d+(?:\.\d{0,2})$/;
if (dmenuvalue != "temp" && $name.val().indexOf("%") == -1 && ($origprice.val().indexOf("%") == -1 && regex.test($origprice.val())) && ($specprice.val().indexOf("%") == -1 && regex.test($specprice.val()))) {
var name = dmenuvalue + "%" + $name.val() + "%" + $origprice.val() + "%" + $specprice.val();
$(elem).text(name);
var dailyDeal = [
dmenuvalue,
$name.val(),
$origprice.val(),
$specprice.val()
];
dailyDeals.push(dailyDeal);
for (i = 0; i < 4; i++) {
$('<input type="hidden">').attr({
'name': 'name[' + ctr + '][' + i + ']',
'value': dailyDeal[i]
}).appendTo(elem);
}
$('<a>').attr({
'href': '#'
}).text("X").click(function() {
$(elem).remove();
//ctr--;
return false;
}).appendTo(elem);
$list.append(elem);
ctr++;
document.getElementById("dailydeals").innerHTML = '';
return false;
} else {
document.getElementById("dailydeals").innerHTML = '*Please complete all required fields above.';
return false;
}
});
The code is below:
http://jsfiddle.net/protron/xGhnv/4/
Full solution on JSFiddle:
http://jsfiddle.net/protron/xGhnv/9/
Basically what I did was:
In the HTML I replaced the <div> called list for a new <table>:
<table id="tableDailyDeals"></table>
In the Javascript instead of calling $(elem).text(... I create a new table row (<tr>) in the table just defined:
var $tr = $('<tr>').appendTo('#tableDailyDeals');
Then besides adding the input-hidden for each dailyDeal attribute (for 0 to 3) I also create a table cell (<td>) and inside it a new <span> with the text you already have in your array named dailyDeal (the span is optional, but as I also put the input-hidden in the same td I think is better this way):
var $td = $('<td>').appendTo($tr);
$('<span>').text(dailyDeal[i]).appendTo($td);
Then just add another table cell (<td>) for the row remover link:
var $tdRemoveRow = $('<td>').appendTo($tr);
The rest is just some css styling and minor details.

jQuery: too much recursion But I need recursion for minesweeper

I am relatively new to javascript. I am trying to code my web version of minesweeper. Here is a recursive function I needed, and it looks to work fine until browser gives this "too much recursion" error. The problem is that i need that recursion. Is there any other way to code minesweeper? Here is the demo: http://altynachar.com/minesweeper/
I can post my php code if needed.
function recursive(id){
var id = id;
//Determine what kind of cell this is: Clean, Bomb or Adjasent to bomb
if($("#"+id).hasClass("adj")== true)
var under = "adj";
if($("#"+id).hasClass("bomb")==true)
var under = "bomb";
if($("#"+id).hasClass("clean")==true)
var under = "clean";
//open up the cell
$("#"+id).hide();
$("#under_"+id).show();
//if it is bomb, open up whole grid and button for restart
if(under == 'bomb')
{
$(".cover").hide();
$(".under").show();
$("body").append("<br /><input type='button' value='restart' onClick='javascript:window.location.reload();' />");
} else {
//if it is clean cell
if(under == "clean")
{
//get all the adjasent cell ids
var split = id.split('-');
var row = parseInt(split[0]);
var col = parseInt(split[1]);
var adjasent = new Array();
adjasent[0] = (row-1)+"-"+ (col+1);
adjasent[1] = row +"-"+(col+1);
adjasent[2] = (row+1)+"-"+(col+1);
adjasent[3] = (row+1)+"-"+col;
adjasent[4] = (row+1)+"-"+(col-1);
adjasent[5] = row+"-"+(col-1);
adjasent[6] = (row -1)+"-"+(col-1);
adjasent[7] = (row -1)+"-"+col;
//loop through adjasent cells
for(var i=0; i<adjasent.length; i++)
{
var split2 = adjasent[i].split('-');
var row2 = parseInt(split2[0]);
var col2 = parseInt(split2[1]);
//check if cell is existent
if(row2 > 0 && row2 < 17)
{
if(col2 > 0 && col2 < 17)
{
//perform recursion
var adj = adjasent[i];
recursive(adj);
}
}
}
}
}
}
My guess is that if you have 2 clean cells next to each other your code will get in an infinite recursion.
Each iteration recurses to all adjacent cells. So say cell A and B are next to each other, and both are clean. A will call recurse to B, which will then recurse to A, which recurses to B, and so on.
You can either try to clean up your recursion so that it doesn't look at cells that were already seen, or remove the recursion. You can accomplish the same thing by adding any unseen clean cells to a queue, and just keep popping off the end of the queue until it's empty. That might make it easier to avoid checking the same cell twice too.
Also, please don't build up strings just to split them into separate data later. Instead of:
adjasent[0] = (row-1)+"-"+ (col+1);
/* ... */
var split2 = adjasent[i].split('-');
var row2 = parseInt(split2[0]);
var col2 = parseInt(split2[1]);
just do
adjacent[0] = { row: row-1, col: col+1 };
/* ... */
var row2 = adjacent[0].row
var col2 = adjacent[0].col
Your recursion is essentially a depth-first search. The problem is that you do not account for visited cells. In other words, say you have 2 cells, A & B:
A B
When you click on A, it searches for adjacent cells, and comes up with a list containing B. You recurse, and then look for neighbors of B, which is a list containing A, and then you recurse again. This cycle never ends.
You need to mark each cell you visit and return if it has already been visited:
function recursive(id){
var id = id;
if( $("#"+id).hasClass('visited') ) {
return;
}
$("#"+id).addClass('visited');
...
}
Then you need to remove 'visited' from everything after recursion is complete:
$('div').removeClass('visited');
Keep a running array of cell id's to check, and delete these values from the array as you check them.
var stack = ["first_id_to_check"];
function check(id){
var id = id;
//Determine what kind of cell this is: Clean, Bomb or Adjasent to bomb
if($("#"+id).hasClass("adj")== true)
var under = "adj";
if($("#"+id).hasClass("bomb")==true)
var under = "bomb";
if($("#"+id).hasClass("clean")==true)
var under = "clean";
//open up the cell
$("#"+id).hide();
$("#under_"+id).show();
//if it is bomb, open up whole grid and button for restart
if(under == 'bomb')
{
$(".cover").hide();
$(".under").show();
$("body").append("<br /><input type='button' value='restart' onClick='javascript:window.location.reload();' />");
} else {
//if it is clean cell
if(under == "clean")
{
//get all the adjasent cell ids
var split = id.split('-');
var row = parseInt(split[0]);
var col = parseInt(split[1]);
var adjasent = new Array();
adjasent[0] = (row-1)+"-"+ (col+1);
adjasent[1] = row +"-"+(col+1);
adjasent[2] = (row+1)+"-"+(col+1);
adjasent[3] = (row+1)+"-"+col;
adjasent[4] = (row+1)+"-"+(col-1);
adjasent[5] = row+"-"+(col-1);
adjasent[6] = (row -1)+"-"+(col-1);
adjasent[7] = (row -1)+"-"+col;
//loop through adjasent cells
for(var i=0; i<adjasent.length; i++)
{
var split2 = adjasent[i].split('-');
var row2 = parseInt(split2[0]);
var col2 = parseInt(split2[1]);
//check if cell is existent
if(row2 > 0 && row2 < 17)
{
if(col2 > 0 && col2 < 17)
{
stack.push(adjasent[i]);
}
}
}
}
}
}
while(stack[0]!==undefined) {
check(stack[0]);
stack.splice(0,1);
}

Categories