Javascript misfunction with checked box on internet explorer 6 - javascript

i've this script that is supposed to check a list of checkbox:
function onchangeSelectAllAnalysable() {
var selectAll = document.forms[0].selectAllAnalysable;
var selectedItems = document.forms[0].selectedItemsAnalysable;
if(selectedItems != undefined) {
if(selectedItems.length != undefined) {
for (var i=0; i<selectedItems.length; i++) {
selectedItems[i].checked = selectAll.checked;
}
} else {
selectedItems.checked = selectAll.checked;
}
}
toggleShuntDiscardButtons();
}
On FF Chrome and IE7/8/9 it works fine but i need it on IE6.
Now when i activate the script i've seen that it gos thru every single box
and check it but at the end when they are all checked they get unchecked again.
It seems strange even because, after that script nothing is executed...
Thx
Daniele

Because you haven't posted relevant source code, I added my working base. After a couple of changes my code work also with IE6.
The code:
<html>
<head>
<script type="text/javascript">
function onchangeSelectAllAnalysable()
{
var selectAll = document.forms[0].elements["selectAllAnalysable"];
var selectedItems = document.forms[0].elements["selectedItemsAnalysable"];
if (typeof (selectedItems) == "object")
{
if(selectedItems.length != 0)
{
for (var i=0; i<selectedItems.length; i++) {
selectedItems[i].checked = selectAll.checked;
}
} else {
selectedItems.checked = selectAll.checked;
}
}
toggleShuntDiscardButtons();
}
function toggleShuntDiscardButtons(){/*whatever you do here*/}
</script>
</head>
<body>
<form name="x" action="http://www.stackoverflow.com" method="post">
<input type="checkbox" name="selectedItemsAnalysable"><br>
<input type="checkbox" name="selectedItemsAnalysable"><br>
<p><input type="checkbox" name="selectAllAnalysable" onClick="onchangeSelectAllAnalysable()"></p>
</form>
</body>
</html>
Attention! IE6 don't accept the event 'onChange' for radiobuttons and checkboxen. You have to use 'onClick' instead.
As you wrote, the checkboxes will be rechecked and you haven't provide the code for the function toggleShuntDiscardButtons(), you should checked the code there. Maybe you forgott some code to remove.

Related

javascript implement "select all" check box not working in IE

I have found this code online, and it is okay on Firefox and Chrome, but it doesn't work on IE, do anyone know how to fix it for IE?
the value of the button does toggle, but just the checkbox not able to change
<html>
<head>
<script type="text/javascript">
function do_this(){
var checkboxes = document.getElementsByName('approve[]');
var button = document.getElementById('toggle');
if(button.value == 'select'){
for (var i in checkboxes){
checkboxes[i].checked = 'FALSE';
}
button.value = 'deselect'
}else{
for (var i in checkboxes){
checkboxes[i].checked = '';
}
button.value = 'select';
}
}
</script>
</head>
<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />
<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>
</html>
It is considered a best practice to put your handler in code and not in-line. You can save some code, and put the onclick handler in your code like so:
// add event handler
function init() {
document.getElementById('toggle').onclick = function () {
do_this(this);
};
}
window.onload = init;
// me is the button here
function do_this(me) {
var checkboxes = document.getElementsByName('approve[]');
for (var i = 0; i < checkboxes.length; i++) {
// toggle to what it is not
checkboxes[i].checked = !checkboxes[i].checked;
}
me.value = me.value == 'select' ? 'deselect' : 'select';
}
Sample fiddle to show it in action: http://jsfiddle.net/qK2qS/
You must pass a boolean value to the checked property. The other browsers are understanding your bizarre logic, and converting 'FALSE' to the boolean true (checking the box), and '' to false (unchecking it)
Use the actual true and false booleans, and it might just work ;)

document.getElementById("items_" + i) is null

I have the following code:
<script type="text/javascript">
for(var i=1; i<=3; i++) {
document.getElementById("items_"+i).checked=true;
}
</script>
With the following HTML
<input type="checkbox" id="items_1" name="myitems" value="1" />
<input type="checkbox" id="items_2" name="myitems" value="2" />
<input type="checkbox" id="items_3" name="myitems" value="3" />
I get an error saying:
document.getElementById("items_" + i) is null.
How do I fix this?
The first index in your for loop will be zero.
Do you have an element with the id items_0 ?
That's likely what's causing your problem. Set the initial value of i to 1
Secondly, you want to make sure that your Javascript code executes after the DOM has loaded.
I recomend you look into using jQuery as this makes it so much simpler to do these kinds of things.
Well your code looks like it's first iteration is pointed to i = 0 so it's trying to find an input tag with the id of 'items_0'.
Here is a JSBin that shows the code working correctly:
http://jsbin.com/amonel/edit
var VanillaRunOnDomReady = function() {
// code to execute after DOM has loaded
for (var i = 1; i <= 3; i++) {
document.getElementById("items_" + i).checked = true;
}
}
var alreadyrunflag = 0;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
}
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}
I ended up using:
$('#items_'+i).attr("checked", true);

Simple JavaScript check not working?

I have this validate form function:
function ValidateForm() {
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
for (var i=0;i<chks.length;i++){
if (chks[i].checked){
hasChecked = true;
break;
}
}
if (!hasChecked){
alert("Please select at least one friend.");
chks[0].focus();
return false;
}
}
html for this is:
<input type="checkbox" name="sendto[]" value="2" >
I know this is not full code. Full code is huge. But basically if i have only one checkbox in the code the above code gives a message undefined on ValidateForm(). Which is called when form is submitted and and above checkbox is checked.
But if i have two checkboxes in the code like this:
<input type="checkbox" name="sendto[]" value="2" >
<input type="checkbox" name="sendto[]" value="4" >
On submit when ValidateForm() function is called this works correctly. Am i doing something wrong that it is not working for 1 checkbox even if it is checked?
The statement
var chks = document.register.elements['sendto[]'];
gets the element (element*s*, if there are more then one) with namesendto[]
If there is only one element with name sendto[] then you have the reference of that element in chks.
If there are more than one element with name sendto[], then chks holds the reference to the array of those elements.
When you do this:
for (var i=0;i<chks.length;i++){
You try to loop based on chks.length. If chks is an array (see above: when there are multiple elements by name sendto[]), then chks.length will hold the number of elements in the array.
If there is only one sendto[] element, then chks will hold that element and since the element (<input type="checkbox" name="sendto[]" value="2" >) does not have a property called length, the browser says length is indefined
So you have o differentiate between two scenarios, when there is only one sendto[] checkbox and when there are more than one.:
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
//Check whether there is one checkbox or whether there are more
if(chks.length)
{
for (var i=0;i<chks.length;i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
}
else
{
if(chks.checked)
{
haschecked = true;
}
}
PS:
code gives a message undefined on ValidateForm() does not convey much. Even for you it is not clear what this means right (That's why you have asked this question). Try to give more details. Any modern browser will give more details on the undefined, the what is undefined which line etc. Even pre-historic browsers will tell you the line number where the undefined error was thrown. With those details you can try to find the line and try to see what is happening. You most likely will find out. If you don't, post it to the community here with all these details.
<script language="javascript">
function validate() {
var chks = document.getElementsByName('sendto[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
hasChecked = true;
break;
}
}
if (hasChecked == false) {
alert("Please select at least one friend.");
return false;
}
return true;
}
</script>
Here is how I would do it.
if(!validate()){
alert("Please select at least one.");
return false;
}
function validate(){
var els=document.getElementsByName('sendto[]');
for(var i=0;i<els.length;i++){
if(els[i].checked){
return true;
}
}
return false;
}
You could use validate as an anonymous function.

Validating a single radio button is not working in available javascript validation script

I have randomly generated radio button series like
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
.....so on
But I get only ONE radio button and execute the javascript validation given for it to chk whether the radio button is selected or not, then it doesnt work
Ples help me out in resolving this.
mycreator = -1;
for (i=frm.creatorusers.length-1; i > -1; i--) {
if (frm.creatorusers[i].checked) {
mycreator = i; i = -1;
}
}
if (mycreator == -1) {
alert("You must select a Creator User!");
return false;
}
Always (!) use the var keyword. Otherwise your variables will be in the global scope (yes, even those in function bodies), which can make for some bugs that are hard to track down.
As #Felix pointed out, creatorusers will only be an array if there is more than one element with that name in the form. You can create a single-element array when necessary to work around that.
Here is an abstracted function that can validate an arbitrary checkbox list.
function ensureChecked(checkboxes, error) {
if (checkboxes) {
var cbx = (checkboxes.length > 0) ? checkboxes : [checkboxes];
for (var i=0; i<cbx.length; i++) {
if (cbx[i].checked) {
return true;
}
}
alert(error);
}
return false;
}
call as
ensureChecked(frm.creatorusers, "You must select a Creator User!");
Ah now I got. If you only have one radio button, then frm.creatorusers is not an array. Just skip it:
var mycreator = -1;
var checked = false;
if(typeof frm.creatorusers.length === 'number') {
for (var i=frm.creatorusers.length; i--; ) {
if (frm.creatorusers[i].checked) {
mycreator = i;
checked = true;
break;
}
}
}
else if(frm.creatorusers.checked){
mycreator = //? what here?
checked = true;
}
if(!checked) {
alert("You must select a Creator User!");
return false;
}
If mycreator was just for checking whether a button was selected or not, you can completely remove it from the code above.
Some further notes to your code:
Always declare variables with var, otherwise they will be global.
Use break to end a loop.
Maybe it is just because of copy and paste, but having a lot of radio buttons with the same value does not make much sense.
You can do something like this:
function validate(frm){
var isChecked = false;
for (var i=0; i<frm.elements.length; i++)
{
if (frm.elements[i].type === 'radio'){
if (frm.elements[i].checked === true){
isChecked = true;
break;
}
}
}
if (isChecked === true){
return true;
}
else{
alert('You should select an option first !');
}
}
Now you should call above function on onsubmit event of the form:
<form onsubmit="return validate(this);">
Now the validate function will make sure that at least one radio button is checked otherwise it won't submit.
this should do it
function isRadioSelected(btn) {
if(typeof btn.length === 'number') {
for(var i=0;i<btn.length;i++)
if(btn[i].checked) return true
}else{
if(btn.checked) return true
}
return false
}
You could try something like this instead:
<html>
<head>
<script type="text/javascript">
function confirmsubmit() {
var btn = document.formname.buttonname
if (btn.checked == false)
{
window.alert("You did not click the button.");
btn.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="mailto:youremail#yourdomain.com"
name="formname" onsubmit="return confirmsubmit();">
click here: <input type="radio" name="buttonname"><br />
<p><input type="submit" value="Submit" name="submit"></p>
</form>
</body>
</html>

document.form.submit(); won't submit in safari

I'm using a javascript function to submit my form. This works in every browser except safari and I can't figure out why
My javascript function looks like this
function submitForm() {
var selectBox = '';
sel_guide_options = document.subForm.sel_guides;
if (sel_guide_options.type == "select-multiple") {
for (var i = 0; i <sel_guide_options.options.length; i++) {
sel_guide_options.options[i].selected = true;
}
}
document.subForm.submit();
}
and in my form I use this
<input type="submit" name="btnSubmit" value="#modification_type# #page_item#" id="btnSubmit" onclick="submitForm();">
does document.subForm.sel_guides point to a select list?
if so I would revise your code to (presuming subForm is the name of your form):
function submitForm() {
var selectBox = '';
var sForm = document.forms['subForm'];
sel_guide = sForm.elements['sel_guides'];
if (sel_guide.type == "select-multiple") {
for (var i = 0; i <sel_guide.options.length; i++) {
sel_guide.options[i].selected = true;
}
}
sForm.submit();
}
I seemed to have fixed it using document.subForm['0'].submit();
instead of document.subForm.submit();
No idea why that would make a difference but its not giving me any problems now. Works on the other browsers too.
Try changing the form element from a type="submit" to type="button".
Both should work but it's worth a try.

Categories

Resources