Dynamic Div ID and Creating Elements Inside it - javascript

I am creating a dynamic Div where i can import values from the showModalDialog when it is closed. So after closing the modal, i get couple of values.
What i am trying to do here is:
I have couple of dynamic div's and against each div, i have a link to open a window.
After selection of the files they are return back to the parent window as comma separated.
I want to insert those values inside the div to which that popup was opened. but in this scenario i am facing the trouble. the Divid's are generated dynamically
Here is the Complete Code for Javascript + Jquery Based, I am getting the following error.
TypeError: theDiv.appendChild is not a function
[Break On This Error]
theDiv.appendChild(newNode);
<script type="text/javascript" src="JS/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function eliminateDuplicates(arr,divID)
{
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++)
{
obj[arr[i]]=0;
}
for (i in obj)
{
out.push(i);
}
return out;
}
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
Test= function(str,divID)
{
var arrID = new Array();
arrID = str.split(',');
arrID = eliminateDuplicates(arrID);
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
alert(theDiv);
var cmp= $("#projectIDS"+divID).val(); //document.getElementById("projectIDS").value;
var cnp = $("#countProj"+divID);//document.getElementById("countProj")
var cproj;
if(cnp.val().length == 0)
cproj=0;
else
cproj=parseInt(cnp.val());
for (var j=0; j<arrID.length; j++)
{
if (parseInt(cproj) + 1 > 50)
{
alert("You cannot add more than 50 Project id's ");
return;
}
if( cmp!="" && cmp.indexOf(arrID[j])!=-1)
continue;
var newNode = document.createElement('div');
newNode.style.cssText = "background:#CCCCCC;border:1px solid #666666;width:100px;word-wrap:break-word;margin:3px;float:left;color:black;text-decoration:none!important;height:auto;vertical-align:middle;padding-top:2px;";
newNode.title = arrID[j]+" ";
newNode.innerHTML = '<input type=hidden name=Proj_' + j + ' ' + 'value=' + arrID[j] + '>' + arrID[j] + ' <b>X</b>';
theDiv.appendChild(newNode);
if(cmp.length == 0)
{
//document.getElementById("projectIDS").value=arrID[j]
$("#projectIDS"+divID).val(arrID[j]);
}
else
{
//document.getElementById("projectIDS").value = document.getElementById("projectIDS").value+","+arrID[j];
$("#projectIDS"+divID).val($("#projectIDS"+divID).val()+","+arrID[j]);
}
cproj = parseInt(cproj)+1;
//document.getElementById("countProj").value =cproj;
cnp.value(cproj);
}
}
removetext = function(par)
{
var strremove=par.text();
var strexist = document.getElementById("projectIDS").value;
strremove = strremove.replace(" X","");
tempRemove(strexist, strremove);
par.remove();
var cproj;
if(document.getElementById("countProj").value.length == 0)
cproj=0;
else
{cproj=parseInt(document.getElementById('countProj').value);
cproj=parseInt(cproj)-1;}
document.getElementById("countProj").value =cproj;
}
function tempRemove(strexist,strremove)
{
var b = strexist.indexOf(strremove);
var after = strexist.indexOf(",",b);
var newstrexist;
var before = strexist.lastIndexOf(",",b);
if(after!=-1)
{newstrexist=strexist.replace(strremove+',',"");}
else if(before!=-1)
{newstrexist=strexist.replace(','+strremove,"");}
else
{newstrexist= strexist.replace(strremove,"");}
document.getElementById("projectIDS").value=newstrexist;
//remove current friend
}
function openWindow(divID)
{
var lookUpAlys=window.showModalDialog("files.cfm?d=" + Math.random() + '&fileID=' + divID,window,"center=yes;dialogWidth:895px:dialogHeight:785px;status:no");
if(lookUpAlys.forename!=undefined)
{
var temp = lookUpAlys.forename;
Test(temp,divID);
}
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="1">
<tr>
<td>Choose</td>
<td>Files</td>
<td>Action</td>
</tr>
<cfloop from="1" to="5" index="i">
<cfoutput>
<tr>
<td><input type="checkbox" name="getFile" id="getFile" value="#i#" /></td>
<td><div id="projectsList#i#" style="width:500px;height:60px;overflow-y:scroll;border:1px solid gray;"></div><input type="text" name="projectIDS#i#" id="projectIDS#i#" data-id="#i#" value="" /><input type="text" data-id="#i#" name="countProj#i#" id="countProj#i#" value="" /></td>
<td>Files</td>
</tr>
</cfoutput>
</cfloop>
</table>
</body>
</html>
so my apologies if i had entered the code incorrectly. Basically trying do it Classic Javascript Way

This does not do what I think you think it does:
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
You should do
var theDiv = $("#projectsList"+divID)[0];
to get the DOM element.
Or, for this scenario, just do
var theDiv = document.getElementById("projectsList" + divID);
Also, I'm not sure why you are mixing raw DOM operations and jQuery wrapped operations everywhere. Just stick to one of them, and be consistent.

var container = $('.itemsList');
var divSubmit = $(document.createElement('div'));
//assigning id to div
$(divSubmit).attr('id','itemTemplate');
$(divSubmit).css({"font-family":"Gotham, Helvetica Neue, Helvetica, Arial, sans-serif","position":"relative","height": "70px","clear" : "both","background-color":"#FFF","border-bottom": "0.09em solid #EBEBEB"});
//adding class to main container
$(divSubmit).addClass('itemTemplate');
//adding Child's name label and assigning id to it.
var Name = '<label class="lblName" id="lblName" for="Name">'+getName()+'</label>';
$(divSubmit).append(Name);
$(divSubmit).append(container);
Here's a sample code. first of all there is sample container called itemslist
that will contain the generated div.
divSubmit will be gernerate dynamically and append to container.
To find some div for click event. Lets say we want to get child name.
alert($($(this).find("label.lblName")).val());

Related

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

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.

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

HTML + javascript mouse over, mouseout, onclick not working in firefox

My question is to get onMouseover,onMouseout,onMousedown,onClick on a table row. For which i am calling javascript userdefined functions.
onMouseover --- Background color should change.
onMouseout --- Reset to original color
onClick --- First column checkbox/radio button should be set and background color should change
onMousedown --- background color should change.
My code in html is:-
<tr onMouseOver="hover(this)" onMouseOut="hover_out(this)" onMouseDown="get_first_state(this)" onClick="checkit(this)" >
and the methods in javascripts are:-
var first_state = false;
var oldcol = '#ffffff';
var oldcol_cellarray = new Array();
function hover(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
oldcol_cellarray[i] = element.cells[i].style.backgroundColor;
element.cells[i].style.backgroundColor='#e6f6f6';
}
}
}
}
// -----------------------------------------------------------------------------------------------
function hover_out(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
if (typeof oldcol_cellarray != undefined) {
element.cells[i].style.backgroundColor=oldcol_cellarray[i];
} else {
element.cells[i].style.backgroundColor='#ffffff';
}
//var oldcol_cellarray = new Array();
}
}
}
}
// -----------------------------------------------------------------------------------------------
function get_first_state(element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
first_state = element.cells[0].firstChild.checked;
}
// -----------------------------------------------------------------------------------------------
function checkit (element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.cells[0].firstChild.type == 'radio') {
var typ = 0;
} else if (element.cells[0].firstChild.type == 'checkbox') {
typ = 1;
}
if (element.cells[0].firstChild.checked == true && typ == 1) {
if (element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = false;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
} else {
if (typ == 0 || element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = true;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
}
if (typ == 0) {
var table = element.parentNode;
if (table.tagName != "TABLE") {
table = table.parentNode;
}
if (table.tagName == "TABLE") {
table=table.tBodies[0].rows;
//var table = document.getElementById("js_tb").tBodies[0].rows;
for (var i = 1; i< table.length; i++) {
if (table[i].cells[0].firstChild.checked == true && table[i] != element) {
table[i].cells[0].firstChild.checked = false;
}
if (table[i].cells[0].firstChild.checked == false) {
set_rowstyle(table[i], false);
}
}
}
}
}
function set_rowstyle(r, on) {
if (on == true) {
for (var i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'bold';
r.cells[i].style.backgroundColor = '#f2f2c2';
}
} else {
for ( i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'normal';
r.cells[i].style.backgroundColor = '#ffffff';
}
}
}
It is working as expected in IE.
But coming to firefox i am surprised on seeing the output after so much of coding.
In Firefox:--
onMouseOver is working as expected. color change of that particular row.
onClick -- Setting the background color permenantly..eventhough i do onmouseover on different rows. the clicked previous row color is not reset to white. -- not as expected
onclick on 2 rows..the background of both the rows is set..Only the latest row color should be set. other rows that are selected before should be set back..not as expected i.e if i click on all the rows..background color of everything is changed...
Eventhough i click on the row. First column i.e radio button or checkbox is not set..
Please help me to solve this issue in firefox. Do let me know where my code needs to be changed...
Thanks in advance!!
Sorry for making everything inline, but this should work in all browsers:
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
Here is a complete page you can test out:
<html>
<head>
<style type="text/css">
tr.click{
background:yellow;
}
tr.hover{
background:green;
}
</style>
</head>
<body>
<table border="1">
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
</table>
</body>
</html>
I would strongly advise moving everything to an external JS file and using some sort of initialization function to assign the event listeners, instead of writing them all inline like me.
I hope this helps in some way.
There may be a particular reason you haven't, but have you considered using a library such as JQuery to tackle this? What you're trying to achieve here could be done very easily and simply with JQuery's CSS-like selectors and .parent/.parents.
As MartyIX says, I would start by using console.log and/or breakpoints in Firebug / Chrome to check exactly which code blocks are being executed. Using the javascript debugging tools can be a little daunting at first until you get how each of the options (step into, step over) work, but they do allow you to check that the code is working as you think it is very easily.
One thing I notice in checkit() - be careful with where you declare variables. I'm not an expert with javascripts variable scoping, but to me it looks like the typ variable only exists within the if block. I would declare "var typ" before the if block and use a third value or second variable to check whether any checkbox or radio is found (what happens if no checkbox and no radio is found?)

Categories

Resources