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

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?)

Related

Javascript not running when triggered by javascript

I have an html form in with a drop down menu and a series of checkboxes. The dropdown has two options. Each option is supposed to check several of the checkboxes using javascript with an onchange event within the "select" tag. This works 100%, but it fails when I trigger it with more javascript.
I have narrowed it down to the part where is resets all the checkboxes to be unchecked. It is then supposed to select the boxes it needs based on the drop down, but because it fails to uncheck them all, they all remain checked.
Here is the code:
select box:
<select name='myrp_autogroups' id='myrp_autogroups' onchange='myrp_group_selector();'>
<option></option>
<?php
$presets = get_option("myrp_presets");
for ($i = 0; $i < count($presets); $i++) {
$preset = $presets[$i];
echo "<option value='";
for ($b = 0; $b < count($preset[1]); $b++) {
$checkbox = $preset[1][$b];
echo $checkbox . ",";
}
echo "'";
echo ">" . $preset[0] . "</option>";
}
update_option("myrp_presets", $presets);
?>
</select>
<input type="button" value="change" onclick="change_group();">
<script type='text/javascript'>
window.onload = change_group();
</script>
Javascript:
function myrp_group_selector()
{
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=false;
document.getElementById("myrp_average_value_top").value="";
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_value_bottom").value="";
document.getElementById("myrp_average_bottom").checked=false;
}
var checkThese = document.getElementById("myrp_autogroups")[document.getElementById("myrp_autogroups").selectedIndex].value;
var checkArray = checkThese.split(",");
var average = "avg";
// check the new stuff
for(var i in checkArray)
{
if(checkArray[i] == average)
{
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=true;
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_bottom").checked=true;
}
}
else
{
document.getElementById("myrp_c_"+checkArray[i]).checked=true;
document.getElementById("myrp_value_"+checkArray[i]).disabled=false;
}
}
}
function change_group() {
select = document.getElementById('myrp_autogroups');
if(select.value != '2,3,4,5,6,'){
select.value = '2,3,4,5,6,';
select.onchange();
}
}
I have narrowed it down to this section, keep in mind it functions perfectly if i manually select an option from the dropdown and doesn't work when triggered by java:
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
the wrong is :
window.onload = change_group() ;
it should be
window.onload = change_group;

Select multiple HTML table rows with Ctrl+click and Shift+click

Demo
I want to select multiple rows using Windows Shift and Ctrl keys, like multiple folder selection in Windows.
From table of selected rows I have to get the first column (student id) and pass to server side C# and delete those records from database.
I have written a code in javascript but the classname is not being applied to <tr> on Shift or Ctrl+ left click.
HTML
<table id="tableStudent" border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr onmousedown="RowClick(this,false);">
<td>1</td>
<td>John</td>
<td>4th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>2</td>
<td>Jack</td>
<td>5th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>3</td>
<td>Michel</td>
<td>6th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>4</td>
<td>Mike</td>
<td>7th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>5</td>
<td>Yke</td>
<td>8th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>6</td>
<td>4ke</td>
<td>9th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>7</td>
<td>7ke</td>
<td>10th</td>
</tr>
</tbody>
</table>
JavaScript
var selectedrow;
function RowClick(currenttr, lock) {
var trs =tableStudent.tBodies[0].getElementsByTagName("tr");
var cnt;
if(window.event.button==2)
{
if(currenttr.className=='selected')
return false;
}
alert(trs.length);
if (((window.event.shiftKey) && (window.event.ctrlKey) ) ||(window.event.shiftKey))
{
for(var j=0; j<trs.length; j++)
{
if (trs[j].className!='normallock')
{
trs[j].className='normal';
}
}
var mark=false;
if (typeof(selectedrow)=="undefined")
{
selectedrow=currenttr;
selectedrow.className='selected'
return false;
}
for(var j=0; j<trs.length; j++)
{
if ((trs[j].id ==selectedrow.id) || (trs[j].id ==currenttr.id) )
{
if (trs[j].className!='normallock')
{
trs[j].className='selected'
mark = !(mark);
}
}
else
{
if(mark==true)
{
if (trs[j].className!='normallock')
trs[j].className='selected'
}
}
}
}
else if(window.event.ctrlKey)
{
//if ctrl key is seelcted while selecting the patients
// select the patient with currently clicked row plus
// maintain the previous seelcted status
cnt=0;
for(var j=0; j<trs.length; j++)
{
if(trs[j].id == currenttr.id)
{
if(trs[j].className=='selected')
{
trs[j].className='normal';
}else
{
trs[j].className='selected';
}
}
if(trs[j].className=='selected')
{
cnt++;
}
}
if(cnt==0)
{
selectedrow=undefined;
return false;
}
}
else
{
for(var j=0; j<trs.length; j++)
{
if(trs[j].id == currenttr.id)
{
trs[j].className='selected'
}
else
{
if (trs[j].className!='normallock')
trs[j].className='normal';
}
}
}
selectedrow=currenttr;
}
It's probably not all of the functionality you want, since the question is a bit vague, but he's an attempt at adding Ctrl or Shift+ left mouse button to select or deselect multiple table rows - see demo and code below. Disclaimer: Only tested in Chrome and code can almost certainly be optimised.
JavaScript
var lastSelectedRow;
var trs = document.getElementById('tableStudent').tBodies[0].getElementsByTagName('tr');
// disable text selection
document.onselectstart = function() {
return false;
}
function RowClick(currenttr, lock) {
if (window.event.ctrlKey) {
toggleRow(currenttr);
}
if (window.event.button === 0) {
if (!window.event.ctrlKey && !window.event.shiftKey) {
clearAll();
toggleRow(currenttr);
}
if (window.event.shiftKey) {
selectRowsBetweenIndexes([lastSelectedRow.rowIndex, currenttr.rowIndex])
}
}
}
function toggleRow(row) {
row.className = row.className == 'selected' ? '' : 'selected';
lastSelectedRow = row;
}
function selectRowsBetweenIndexes(indexes) {
indexes.sort(function(a, b) {
return a - b;
});
for (var i = indexes[0]; i <= indexes[1]; i++) {
trs[i-1].className = 'selected';
}
}
function clearAll() {
for (var i = 0; i < trs.length; i++) {
trs[i].className = '';
}
}
HTML
<table id="tableStudent" border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr onmousedown="RowClick(this,false);">
<td>1</td>
<td>John</td>
<td>4th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>2</td>
<td>Jack</td>
<td>5th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>3</td>
<td>Michel</td>
<td>6th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>4</td>
<td>Mike</td>
<td>7th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>5</td>
<td>Yke</td>
<td>8th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>6</td>
<td>4ke</td>
<td>9th</td>
</tr>
<tr onmousedown="RowClick(this,false);">
<td>7</td>
<td>7ke</td>
<td>10th</td>
</tr>
</tbody>
</table>
CSS
.selected {
background: lightBlue
}
I would also look at addEventListener vs onclick and move the event handler binding out of the HTML and into JavaScript. This is known as Unobtrusive Javascript.
Resources you might want to read:
Retrieve Table Row Index of Current Row
disable text selection while pressing 'shift'
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
I made it work with all the Windows 7 explorer behaviors and jquery mouse events.
http://jsfiddle.net/ubershmekel/nUV23/6/
Note that:
When you just click, you set a pivot for the next shift-click
Use Ctrl-Shift to expand your current selection and not pivot like Shift-alone does.
Use Ctrl-click to add a pivot, you can use Ctrl-Shift to then expand that selection around the new pivot.
The js:
var selectionPivot;
// 1 for left button, 2 for middle, and 3 for right.
var LEFT_MOUSE_BUTTON = 1;
var trs = document.getElementById('tableStudent').tBodies[0].getElementsByTagName('tr');
var idTds = $('td:first-child');
idTds.each(function(idx, val) {
// onselectstart because IE doesn't respect the css `user-select: none;`
val.onselectstart = function() { return false; };
$(val).mousedown(function(event) {
if(event.which != LEFT_MOUSE_BUTTON) {
return;
}
var row = trs[idx];
if (!event.ctrlKey && !event.shiftKey) {
clearAll();
toggleRow(row);
selectionPivot = row;
return;
}
if (event.ctrlKey && event.shiftKey) {
selectRowsBetweenIndexes(selectionPivot.rowIndex, row.rowIndex);
return;
}
if (event.ctrlKey) {
toggleRow(row);
selectionPivot = row;
}
if (event.shiftKey) {
clearAll();
selectRowsBetweenIndexes(selectionPivot.rowIndex, row.rowIndex);
}
});
});
function toggleRow(row) {
row.className = row.className == 'selected' ? '' : 'selected';
}
function selectRowsBetweenIndexes(ia, ib) {
var bot = Math.min(ia, ib);
var top = Math.max(ia, ib);
for (var i = bot; i <= top; i++) {
trs[i-1].className = 'selected';
}
}
function clearAll() {
for (var i = 0; i < trs.length; i++) {
trs[i].className = '';
}
}
And the CSS:
.selected {
background: #bdf;
}
td:first-child {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
td,th {
padding: 3px;
border: 2px solid #aaa;
}
table {
border-collapse: collapse;
}
Here's a jQuery plugin I wrote recently for a project. Thought sharing...
Works exactly like you're used to, +
it's extremely fast cause it operates over an Array without the need to check for attributes, classes etc, and the add/removeClass triggers only on the selected elements:
// Use like:
// $("table").selekt();
//
// Available options:
$("table").selekt({
children: "tr", // Elements to target (default: "tbody tr")
className: "selected", // Desired CSS class (default: "selected")
onSelect: function(sel) { // Useful callback
$("span").text(sel.length + ' in ' + this.id);
}
});
.selected { background: #0bf; }
table {border: 1px solid #555;display: inline-block; vertical-align: top;}
<p>Seleceted: <span id="info">0</span></p>
<table id="table_1">
<tr><td>1 SELECT ME</td></tr>
<tr><td>2 SELECT ME</td></tr>
<tr><td>3 SELECT ME</td></tr>
<tr><td>4 SELECT ME</td></tr>
<tr><td>5 SELECT ME</td></tr>
<tr><td>6 SELECT ME</td></tr>
</table>
<table id="table_2">
<tr><td>1 SELECT ME</td></tr>
<tr><td>2 SELECT ME</td></tr>
<tr><td>3 SELECT ME</td></tr>
<tr><td>4 SELECT ME</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
;(function($) {
// selekt jQuery plugin // http://stackoverflow.com/a/35813513/383904
$.fn.selekt = function() {
var settings = $.extend({
children: "tbody tr",
className: "selected",
onSelect: function() {}
}, arguments[0] || {});
return this.each(function(_, that) {
var $ch = $(this).find(settings.children),
sel = [],
last;
$ch.on("mousedown", function(ev) {
var isCtrl = (ev.ctrlKey || ev.metaKey),
isShift = ev.shiftKey,
ti = $ch.index(this),
li = $ch.index(last),
ai = $.inArray(this, sel);
if (isShift || isCtrl) ev.preventDefault();
$(sel).removeClass(settings.className);
if (isCtrl) {
if (ai > -1) sel.splice(ai, 1);
else sel.push(this);
} else if (isShift && sel.length > 0) {
if (ti > li) ti = [li, li = ti][0];
sel = $ch.slice(ti, li + 1);
} else {
sel = ai < 0 || sel.length > 1 ? [this] : [];
}
last = this;
$(sel).addClass(settings.className);
settings.onSelect.call(that, sel);
});
});
};
}(jQuery));
</script>
Check this example:
JSFiddle: Highlight list with shift and ctrl
Part of the code:
switch(e.type) {
case "keydown" :
console.log('k_down');
keysPressed.push(e.keyCode);
break;
case "keyup" :
console.log('k_up');
var idx = keysPressed.indexOf(e.keyCode);
if (idx >= 0)
keysPressed.splice(idx, 1);
break;
}
Sources could be found here:
Source files github
I know this question is already answered and it's pretty old, but I found the answer by andyb to be super helpful. Perhaps it was because andyb's answer might be outdated now, but I ended up having to change his solution a bit to work with my project, so I figured I'd share my updated version. Here is what I ended up with, using a sprinkling of jQuery.
$(document).ready(function(){
//put all the table rows in a variable after page load to pass in to RowClick
var trs = $('#tableStudent tr')
//bind the click handler to all the table rows
$('tr').on('click', function(){
//call the RowClick function on click event
RowClick($(this),false,trs)
})
})
//declare variable to store the most recently clicked row
var lastSelectedRow;
// disable text selection
document.onselectstart = function() {
return false;
}
function RowClick(currentrow, lock, rows) {
//if control is held down, toggle the row
if (window.event.ctrlKey) {
toggleRow(currentrow);
}
//if there are no buttons held down...
if (window.event.button === 0) {
//if neither control or shift are held down...
if (!window.event.ctrlKey && !window.event.shiftKey) {
//clear selection
clearAll(rows);
//toggle clicked row
toggleRow(currentrow);
}
//if shift is held down...
if (window.event.shiftKey) {
//pass the indexes of the last selected row and currently selected row along with all rows
selectRowsBetweenIndexes([lastSelectedRow.index(), currentrow.index()], rows)
}
}
}
function toggleRow(row) {
//if the row is not the header row...
if (!row.hasClass('header-row')){
//if the row is selected...
if (row.hasClass('selected')){
//deselect it
row.removeClass('selected')
}
else{
//otherwise, select it
row.addClass('selected')
}
//reassign the most recently selected row
lastSelectedRow = row;
}
}
function selectRowsBetweenIndexes(indexes,rows) {
//sort the indexes in ascending order
indexes.sort(function(a, b) {
return a - b;
});
//for every row starting at the first index, until the second index...
for (var i = indexes[0]; i <= indexes[1]; i++) {
//select the row
$(rows[i+1]).addClass('selected');
}
}
function clearAll(rows) {
//for all rows...
for (var i = 0; i < rows.length; i++) {
//deselect each row
$(rows[i]).removeClass("selected");
}
}
Following code is modification from Robo C Buljan, since i wanted to multiselect using checkboxes and shift key
<includeScript value="/jquery-3.2.0.min.js" />
<script>
;(function($) {
// selekt jQuery plugin // http://stackoverflow.com/a/35813513/383904
$.fn.selekt = function() {
var settings = $.extend({
children: "td input[type='checkbox'][name='ids']",
onSelect: function(){
}
}, arguments[0] || {});
return this.each(function(_, that){
var $ch = $(this).find(settings.children),
sel = [],
last;
$ch.on("mouseup", function(ev) {
/* Note 1: Remember this code is run when a checkbox is clicked and is run before checbox's state changes because of click
i.e. to say if the checkbox was checked and we clicked it to uncheck, then this event handler (mouse up)code is called before the unchecing happens */
if(ev.shiftKey || ev.ctrlKey){
ev.preventDefault();
ev.stopPropagation();
}
var self = this;
var ti = $ch.index(this), // index of current element in the matching elements
li = $ch.index(last), // index of last element in the matching elements
ai = $.inArray(this, sel); // index of this in the sel array
if(ev.ctrlKey) {
if(ai > -1) sel.splice(ai, 1);
else sel.push(this);
}
else if(ev.shiftKey && sel.length > 0) {
if(ti > li) ti = [li, li=ti][0];
sel = $ch.slice(ti, li+1);
}
else {
sel = ai < 0 || sel.length > 1 ? [this] : [];
}
last = this;
/* purpose 2
code to check checkboxes inside the array*/
$(sel).each(function(index, checkbox){
/* see/search Note 1 in comments, if the checkbox is already checked/unchecked then uncheck/check all the elements straight from the last element correspondingly */
if(self.checked) {
if( checkbox != self){
checkbox.checked = false;
}
} else {
if( checkbox != self){
checkbox.checked = true;
}
}
})
/*end of purpose 2*/
// settings.onSelect.call(that, sel); // this is defined just in case we want to call some function after the select/deselect operation
});
});
};
}(jQuery));
setTimeout(function(){
$("table.list").selekt();
},500)
</script>

Dynamic Div ID and Creating Elements Inside it

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());

Background change not working in javascript. whats wrong?

I am using jquery slider, i have a single layout and a center div for content..i need to change the color of the layout while i slide on a different page. This is What i am doing using asp.net mvc3.
HTML:
<div id="iPhone_Product">
<div class="slides_containeriphone" >
#if (Model == null)
{
<div class="animateriphone" id="1" title="iphone">
#Html.Partial("`enter code here`_iPhone_Main")
</div>
<div class="animateriphone" id="2" title="salah">
#Html.Partial("Salah")
</div>
<div class="animateriphone" id="3" title="tasbeeh">
#Html.Partial("_Tasbeeh")
</div>
}
else
{
foreach (string s in Model)
{
<div class="animateriphone">
#Html.Partial(s);
</div>
}
}
</div>
</div>
Javascript:
function color_change() {
var ids = new Array();
ids[0] = '1';
ids[1] = '2';
ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
}
if (x.id == '1' && x.title=='iphone') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
else
if (x.id == '2' && x.title == 'salah') {
$(".st_tabs_container").css({ "background-color": "yellow" });
}
else
if (x.id == '3' && x.title == 'tasbeeh') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
}
$(document).ready(function () {
color_change();
});
i have used this javascript to change the background but its not working, any help would be appericiated.
I think the issue is that you are using numbers for ids. Try starting your id values with letters. I think you should consider prefixing your ids, i.e. id1, id2, or something like that.
And you are closing the for loop too early, Nest all your if/else logic inside it as well.
Isn't x always going to be 3 since you are reseting x inside a loop.
You are looping over all your elements without doing anything to them, so depending on what you are trying to do, you might need to move the if-statements into the for-loop as well, or make use of the x in a proper way from within the for-loop.
Not entirely sure what you want to accomplish, but I've put together what I believe you are trying to do: http://jsfiddle.net/ZuzTU/1/
function color_change() {
var ids = new Array(); ids[0] = '1'; ids[1] = '2'; ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
if (x.id == '1' && x.title=='iphone') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
else if (x.id == '2' && x.title == 'salah') {
$("#" + x.id).css({ "background-color": "yellow" });
}
else if (x.id == '3' && x.title == 'tasbeeh') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
}
}
$(document).ready(function () {
color_change();
});​
Pretty sure you're not calling the ids right, try this:
<div class="animateriphone" id="id2" title="salah">
var x = document.getElementById('id'+ ids[item]);

How to check< 2 and > 4 checkbox in javascript

I am trying to check the user input for greater than 2 and less than 4 checkbox selected.
I have to do this check before the form gets submitted.
Although I am using AlloyUI for client side validation. You can help me with vanilla javascript.
Please help me with my code...
<% for(loop here which generates more than one checkbox) { %>
<form name=".." method=".." action=".." onSubmit="return checkBox();">
<input type="checkbox" id=".." name=".."/>
</form>
%>
My javascript
function checkBox(){
alert("start");
var total = 0;
var max = form.checkcompare.length;
alert(max);
for(var idx = 0; idx < max; idx++)
{
if(eval("document.compareform.checkcompare[" + idx + "].checked") == true)
{
alert("checking");
total += 1;
}
}
if (total==2 || total==4)
{
/* document.compareform.submit(); */
alert("success");
}
else
{
alert('Select minimum of 2 or maximum of 4 Estimates');
}
//alert("You selected " + total + " boxes.");
}
Its not working..can someone help..Thanks
Something tells me you have little idea what you're doing.
First off, you're creating one form for EVERY checkbox. Open the form tag, then put in your loop to add the checkboxes, then close the form.
Now for your script...
form is undefined, so you can get its elements. form.checkcompare is undefined, so you can't get its length. You probably want to pass this in the onSubmit event (onSubmit="return checkBox(this);"), and function checkBox(form). Then use form.querySelectorAll('input[type=checkbox]');.
Next, why in the world are you using evil eval just to get an array index?
As if that weren't enough you say you want "between 2 and 4" but your code considers "3" invalid.
Finally, you're not returning anything.
Fixed (and improved) code:
function checkBox(form){
var total = 0;
var boxes = form.querySelectorAll('input[type=checkbox]:checked').length;
if (boxes < 2 || boxes > 4)
return true;
else {
alert('Select minimum of 2 or maximum of 4 Estimates');
return false;
}
}
function getNumberOfCheckedCheckboxes ( form ) {
var returnValue = 0;
var inputElements = form.getElementsByTagName("input");
for (var i = 0; i < inputElements.length; i ++) {
if (inputElements.type == "checkbox") {
if (inputElments.checked) {
returnValue ++;
}
}
}
return returnValue;
}

Categories

Resources