Solved

Javascript:  detecting table cell clicks -- first click versus second click

Posted on 2004-03-25
12
280 Views
Last Modified: 2012-08-13
Dear Expert:

Can you supply complete functionioning ASP source code that does the following:


1)  Creates a 2 x 2 HTML table.  Each cell has a JavaScript OnButtonClick event that passes in the row and column of the cell that was clicked.

2)  Captures row and column clicked for the first cell clicked and the second cell clicked (total of 4 variables)

3)  If second click, compares row (first click) to row (second click) and says if they are the same or different.  Same thing with column (first click) column (second click).


Here's the sequence of events:

1)  Page loads
2)  2 x 2 table is displayed
3)  User clicks cell in first column first row
(internally the assignment is made:)

firstClickRow = 1
firstClickColumn = 1

4)  User clicks cell in second column second row
(internally the assignment is made:)

secondClickRow = 2
secondClickColumn = 2

5)  firstClickRow = secondClickRow?   FALSE

6)  firstClickColumn = secondClickColumn?   FALSE



Many thanks,

Tom
0
Comment
Question by:knowlton
  • 6
  • 6
12 Comments
 
LVL 5

Author Comment

by:knowlton
ID: 10681400
Example:

http://www.knowltonfamily.com/robotzweb/test_cells.html
 

alert should only fire on the SECOND cell click.
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10681473
I made it more complex :(

<html>
<head>
<script>
firstClickRow = -1;
firstClickColumn = -1;
secondClickRow = -1;
secondClickColumn = -1;
clicks = 0;
function clickCell(e){
  clicks++;
  cell = (event.srcElement)?event.srcElement:e.target;
  row = cell.parentNode;
  tab = row.parentNode;
  for(i=0;i<tab.rows.length;i++){
    if(tab.rows[i]==row){
      rowNum = i;
    }
  }
  for(i=0;i<row.cells.length;i++){
    if(row.cells[i]==cell){
      cellNum = i;
    }
  }
  if(clicks==1){
    firstClickRow = rowNum;
    firstClickColumn = cellNum;
    window.status = "1Row: "+rowNum+";  1Col: "+cellNum;
  } else {
    secondClickRow = rowNum;
    secondClickColumn = cellNum;
    window.status = "2Row: "+rowNum+";  2Col: "+cellNum;
    if(firstClickRow==secondClickRow && firstClickColumn==secondClickColumn){
      alert("Same Cell")
    }
    clicks = 0;
  }
}
function init(){
  cell = document.getElementsByTagName('TD');
  for(i=0;i<cell.length;i++){
    cell[i].onclick = clickCell;
  }
}
</script>
</head>
<body onLoad="init()">
<table border="1">
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
<tr><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td><td>A</td></tr>
</table>
</body>
</html>


0
 
LVL 63

Accepted Solution

by:
Zvonko earned 500 total points
ID: 10681519
Your example is reducing it to this:


<html>
<head>
<script>
var sLastClicked;

function ClickCompare(oObject) {
  if(!sLastClicked) {
    sLastClicked = oObject;
  } else {
    if(sLastClicked == oObject){
      alert('Clicked same cell');
    } else {
      alert('Clicked different cell');
    }
    sLastClicked = null;
 }
}
</script>
</head>
<body>
<table width="300" border="1">
     <tr>
          <td id="cell_1" width="150" onclick="ClickCompare(this);"><p>&nbsp;</p></td>
          <td id="cell_2" width="150" onclick="ClickCompare(this);"><p>&nbsp;</p></td>
     </tr>
     <tr>
          <td id="cell_3"width="150" onclick="ClickCompare(this);"><p>&nbsp;</p></td>
          <td id="cell_4"width="150" onclick="ClickCompare(this);"><p>&nbsp;</p></td>
     </tr>
</table>
</body>
</html>


0
 
LVL 5

Author Comment

by:knowlton
ID: 10681636
You code seems to do the trick, thanks:

http://www.knowltonfamily.com/robotzweb/another_test.html
0
 
LVL 5

Author Comment

by:knowlton
ID: 10681656
Here is your "more complex" example:


http://www.knowltonfamily.com/robotzweb/more_complex.html
0
 
LVL 5

Author Comment

by:knowlton
ID: 10681686
Question for you.

Can your function

ClickCompare(this)


be expanded to include additional parameters?

as in:

ClickCompare(this, param2, param3, param4)
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 63

Expert Comment

by:Zvonko
ID: 10681764
Yea, of course.
But with what intention?
0
 
LVL 5

Author Comment

by:knowlton
ID: 10681828
The end goal is to be able to record information as each cell is clicked (always in a two click sequence)

First click:   Record information about that square (which game piece, health, attack ability)

Second click:  Record information about that square (which game piece, health, attack ability)


OnSecondClick:    Compare First Click to Second Click....determine what should happen:

1)  Piece moves to new square
2)  Piece attacks enemy
3) ???? whatever ??????




<!--#include File="connections.asp" -->
<%


Dim sInitGame
'Dim moveState
'squareOne = "One"
'squareTwo = "Two"
sInitGame = Request.Form("newgame")
'sInitGame = "New Game"

fv = request("ItemValueFirst")
sv = request("ItemValueSecond")

if request("subform") = "Yes" then
      Response.Write "Subform value was YES"
      Response.Write "<br>"
      
      Response.Write "First value:  " & fv & "<br>" & "Second value: " & sv
      
      if(fv="2") And (sv="512") then      
            Response.Write "<br>" & "Destroyer moved to blank square"
      end if

      if(fv="4") And (sv="512") then      
            Response.Write "<br>" & "Medic moved to blank square"
      end if

      if(fv="8") And (sv="512") then      
            Response.Write "<br>" & "Engineer moved to blank square"
      end if
      
      Response.Write "<br>" & "EVALUATION:  " & fv * sv
      
       strUp = "UPDATE tblGameBoard, tblGameBoard tb SET tblGameBoard.Value = " & sv & ", tblGameBoard.[Image] = tb.[Image] WHERE tblGameBoard.SquareID="&request("NewSqID")&" AND tb.SquareID = "&request("OldSqID")&";"
      strUp2 = "Update tblGameBoard set Value = 512, [Image]='blank' Where SquareID = "&request("OldSqID")
      Conn.execute(strUp)
      Conn.execute(strUp2)  
end if
%>

<form name="GameForm" action="game.asp" method=get>

<%
call sbInitGame()

Sub sbInitGame()
      response.Write "Initializing Game"
      response.Write "<br><br><br>"
      response.Write "Game board:   Click a game piece to select it, then click new square to move game piece to"
      response.Write "<br><br><br>"
       set rs=Server.CreateObject("ADODB.recordset")
      rs.CursorType = 3
      sql="select [Row], [Column], [Image], [Value], [SquareID] from tblGameBoard where GameNumber='1' Order by [Row], [Column]"
        rs.Open sql, Conn
      oldRow=""
      %><table><%
      if (rs.EOF or rs.BOF) then                
          response.write "No Row in the table<br>"
      else
            do until rs.eof    
                  currentRow = rs("row")
                  currentImage = rs("Image")
                  ValueReadIn = rs("Value")
                if not(currentRow = oldRow) then
                      %><tr><%                    
                end if%>
                  <td onclick="OnSquareClick('<%=rs("SquareID")%>','<%=currentImage%>','<%=ValueReadIn%>')">
              <img src="images\<%=currentImage%>.jpg">
                 </td>  
                 <%oldRow = currentRow
                 rs.MoveNext     'This tells the rows to move to the next row
            loop          'This tells the 'DO UNTIL' to move on and do it all over again.
            rs.close
          set rs=nothing     'Its a really good idea to close recordsets and connections when your done.
            %></tr><%
      end if                
      %></table><%
End Sub
%>


<!--#include File="closeconnections.asp" -->


Old Square ID:&nbsp;&nbsp;<input name="OldSqID" value="None">
<br>
New Square ID:&nbsp;&nbsp;<input name="NewSqID" value="None">
<br>
Item Value First:&nbsp;&nbsp;<input name="ItemValueFirst" value="None">
<br>
Item Value Second:&nbsp;&nbsp;<input name="ItemValueSecond" value="None">
<br>
Sub Form:&nbsp;&nbsp;<input name="SubForm" value="No">
<br>

<br>
<br>
</form>


<script type="text/javascript"  language="Javascript">

function OnSquareClick(square,imagename,ValueOfItem)
{
  Origin=document.GameForm.OldSqID;
  Dest=document.GameForm.NewSqID;
  SubForm=document.GameForm.SubForm;
  VOI_First=document.GameForm.ItemValueFirst;
  VOI_Second=document.GameForm.ItemValueSecond;
 
  if(Origin.value == Dest.value)
  {
    Origin.value = square;
      VOI_First.value= ValueOfItem;
    SubForm.value = "No";
  }
  else if(Origin.value != Dest.value)
  {
    Dest.value = square
    SubForm.value = "Yes";
      VOI_Second.value=ValueOfItem;
    document.forms[0].submit();
  }
}//End of OnSquareClick



</script>
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10681949
I do not see there a problem.
Add the cell reference to the onClick call.
Like this:
<td onclick="OnSquareClick(this, '<%=rs("SquareID")%>','<%=currentImage%>','<%=ValueReadIn%>')">

And extend your OnSquareClick() function to do the basic cell object comapre and based on that condition use the following parameters if present.
Like this:
<script type="text/javascript"  language="Javascript">
var sLastClicked;

function OnSquareClick(theCell, square,imagename,ValueOfItem){
    if(!sLastClicked) {
    sLastClicked = oObject;
  } else {
    if(sLastClicked == oObject){
      alert('Clicked same cell');
    } else {
      Origin=document.GameForm.OldSqID;
      Dest=document.GameForm.NewSqID;
      SubForm=document.GameForm.SubForm;
      VOI_First=document.GameForm.ItemValueFirst;
      VOI_Second=document.GameForm.ItemValueSecond;
 
      if(Origin.value == Dest.value){
        Origin.value = square;
        VOI_First.value= ValueOfItem;
        SubForm.value = "No";
      } else if(Origin.value != Dest.value){
        Dest.value = square
        SubForm.value = "Yes";
        VOI_Second.value=ValueOfItem;
        document.forms[0].submit();
      }
    }
    sLastClicked = null;
  }
}//End of OnSquareClick



</script>



0
 
LVL 5

Author Comment

by:knowlton
ID: 10681978
Origin=document.GameForm.OldSqID;
Dest=document.GameForm.NewSqID;


Dest will be NULL on the first click?


This is where I get confused.
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10682042
On first click is only this executed:

   if(!sLastClicked) {
      sLastClicked = oObject;
   }


Uhps sorry, I confused with old parameters.
Check this:

var sLastClicked;

function OnSquareClick(theCell, square,imagename,ValueOfItem){
    if(!sLastClicked) {
    sLastClicked = theCell;
  } else {
    if(sLastClicked == theCell){
      alert('Clicked same cell');
    } else {
      Origin=document.GameForm.OldSqID;
      Dest=document.GameForm.NewSqID;
      SubForm=document.GameForm.SubForm;
      VOI_First=document.GameForm.ItemValueFirst;
      VOI_Second=document.GameForm.ItemValueSecond;
 
      if(Origin.value == Dest.value){
        Origin.value = square;
        VOI_First.value= ValueOfItem;
        SubForm.value = "No";
      } else if(Origin.value != Dest.value){
        Dest.value = square
        SubForm.value = "Yes";
        VOI_Second.value=ValueOfItem;
        document.forms[0].submit();
      }
    }
    sLastClicked = null;
  }
}//End of OnSquareClick


0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10682177
Here a tested version:

<script type="text/javascript"  language="Javascript">
var sLastClicked;

function OnSquareClick(theCell, square,imagename,ValueOfItem){
  theForm = document.GameForm;
  Origin = theForm.OldSqID;
  Dest = theForm.NewSqID;
  SubForm = theForm.SubForm;
  VOI_First = theForm.ItemValueFirst;
  VOI_Second = theForm.ItemValueSecond;

  if(!sLastClicked) {
    sLastClicked = theCell;
    Origin.value = square;
    VOI_First.value= ValueOfItem;
    SubForm.value = "No";
  } else {
    if(sLastClicked == theCell){
      alert('Clicked same cell');
    } else {
      Dest.value = square
      SubForm.value = "Yes";
      VOI_Second.value=ValueOfItem;
      document.forms[0].submit();
    }
    sLastClicked = null;
  }
}//End of OnSquareClick


</script>

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now