Again in problem
Actually I have following jsp code in which I have few text boxes which I have made disabled by using property disabled="disabled".
Now problem is each record that I will get from database in each text box using iterator which iterates values added from databse in arraylist.If database return more than one record then using that check box I can enable textboxes but if databse resultset return only one record then I am unable to enable textboxes and throws following ERROR:
Message: 'document.f1.chk' is null or not an object
Line: 26
Char: 10
Code: 0
<script type="text/javascript">
function enable()
{
for(i=0;i<document.preapp.chk.length;i++)
{
if(document.preapp.chk[i].checked==true)
{
document.preapp.id[i].disabled=false;
document.preapp.vname[i].disabled=false;
document.preapp.comp[i].disabled=false;
document.preapp.cont[i].disabled=false;
document.preapp.wtm[i].disabled=false;
document.preapp.intime[i].disabled=false;
}
else
if(document.preapp.chk[i].checked==false)
{
document.preapp.id[i].disabled=true;
document.preapp.vname[i].disabled=true;
document.preapp.comp[i].disabled=true;
document.preapp.cont[i].disabled=true;
document.preapp.wtm[i].disabled=true;
document.preapp.intime[i].disabled=true;
}
}
}
</script>
<CENTER>Back to Search</CENTER>
<form method="post" action="" name="preapp">
<table border="1" align="center" width="100%">
<%
Iterator itr;
try
{
ArrayList al=(ArrayList)request.getAttribute("sq");
int i=0;
for(itr=al.iterator();itr.hasNext();)
{
i=i+1;
%>
<tr>
<td></td><td><input type="checkbox" name="chk" onclick="enable(this)" ></td></tr></tr>
<tr><td>Id</td><td><input type="text" name="id" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Visitor Name</td><td><input type="text" name="vname" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Comapny</td><td><input type="text" name="comp" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Contact</td><td><input type="text" name="cont" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Meeting Scheduled With</td><td><input type="text" name="wtm" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Entry Made On</td><td><input type="text" name="intime" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td></td>
</tr>
<tr>
</tr>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
%>
How Do solve this problem? please help me out!
It works like charm, except in the case you have only one TR block.
In that case, the .chk has no "length" attribute!
You should consider that case separately:
function enable()
{
if(document.preapp.chk.length == null)
{
disabledState = !document.preapp.chk.checked
document.preapp.id.disabled=disabledState;
document.preapp.vname.disabled=disabledState;
document.preapp.comp.disabled=disabledState;
document.preapp.cont.disabled=disabledState;
document.preapp.wtm.disabled=disabledState;
document.preapp.intime.disabled=disabledState;
} else {
for(i=0;i<document.preapp.chk.length;i++)
{
disabledState = !document.preapp.chk[i].checked
document.preapp.id[i].disabled=disabledState;
document.preapp.vname[i].disabled=disabledState;
document.preapp.comp[i].disabled=disabledState;
document.preapp.cont[i].disabled=disabledState;
document.preapp.wtm[i].disabled=disabledState;
document.preapp.intime[i].disabled=disabledState;
}
}
}
a couple of suggesions: instead of setting the properties of elements to true or false, try using the setAttribute and removeAttribute methods:
document.preapp.id[i].disabled=true;
//replace with:
document.preapp.id[i].setAttribute('disabled','disabled');
//to enable:
document.preapp.id[i].removeAttribute('disabled');
The way you're doing things works fine 99.9% of the time. I haven't seen the above code fail, though (I have had issues with the true/false approach).
Next: the error message you post, contains very useful information: check line 26 of your original code. 'document.f1.chk' is nowhere to be found in your snippet, so I can't check for typo's or other possible problems in your code there.
You're passing the element to the enable function, too. Why then, are you looping through all elements, checking all elems on the page?
function enable(elem)
{
var i = document.preapp.indexOf(elem);//
if (elem.checked === true)
{
document.preapp.id[i].removeAttribute('disabled');
//...
}
//functions have properties, exploit them:
if (typeof enable.previous === 'undefined' || enable.previous === i)
{
enable.previous = i;
return true;
}
document.preapp.id[enable.previous].setAttribute('disabled','disabled');
//...
enable.previous = i;
}
The last section of the enable function stores the index of the checkbox that was just clicked, so that when the enable function has been clicked before, there's no need to loop through all elements again: enable.previous holds the index of the checkbox that was clicked last time.
Lastly: there are no opening or closing bracket for the else block, and there is an extra line of whitespace. Else works fine without brackets, but only branches one line. In your code, this line is blank: either remove the else, or add brackets.
PS: Perhaps a fiddle would help to get a clear view of the situation?
As Teejay pointed out, in case of unique names, the elements are referenced directly, instead of a nodesList being passed.
Related
I have already tried all the given methods to uncheck checkbox in jquery, please find my below code.
$('#btnDeleteEnterpriseID').click(function () {
$('#chkbox').prop('checked', false);
$('#chkbox').removeAttr('checked');
$('#chkbox').checked = false;
$('#chkbox').attr('checked', false);
$('#chkbox input:checkbox').attr('checked', false);
$('#chkbox input[type=checkbox]').removeAttr('checked');
});
Have tried with all methods that I could get till now.
Below is the code for my checkbox and button.
#helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
{ <input type="checkbox" id="chkbox" value="#s"class="edit-mode" />#s <br />}
}
Here, #DisplayMultiline is helper class which I used in Web Grid column as shown below,
grid.Column(columnName: "EnterpriseID",
format:#<text><span class="display-mode">
<label id="EnterpriseId" ></label>
</span>#DisplayMultiLine(#item.EnterpriseId)</text>),
And I want this checkbox to get unchecked on click event of delete button, code for it given below.
<button type="button" id="btnDeleteEnterpriseID"
value="Delete" class="cancel-user edit-mode" onclick="DeleteEnterpriseID()">Delete</button>
I am not getting my mistake, kindly assist.
Kindly note, I have not used all those possibilities together, I just wanted to tell that I have used almost all methods and have tried them one by one.
You are generating duplicate identifiers in your foreach:
#helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
{ <input type="checkbox" id="chkbox" value="#s"class="edit-mode" />#s <br />}
}
When you have multiple objects with the same id, jquery is having trouble to distinguish which one of them you aim at.
Jquery will either work only on the first one it will match or won't work at all. Find a way to distinguish between every check box.
for example:
#helper DisplayMultiLine(string str)
int i = 0;
{ foreach (string s in str.Split(new char[] { ',' }))
{ <input type="checkbox" id="chkbox" + i value="#s"class="edit-mode" />#s
}
i++;
}
I've been searching for this for a couple hours with no luck. This seems like it should be fairly easy but I am obviously overlooking something.
I have a table, with each row displaying information in each cell. At the end of each of the rows, there is an additional cell with a checkbox in it. The checkbox is an array, and each checkbox value is an imploded array via PHP. See below:
HTML/PHP
--------
(...some html code...)
<form method="post" action="the-next-page.php">
<table>
<tr>
<?php
(...some php SQL query code...)
while ($row = oci_fetch_array($result)) {
?>
<td><input type="text">Name</td>
<td><input type="text">City</td>
<td><input type="checkbox" name="checkGroup[]" value="<?php implode(":",$someArrayvariable) ?>"></td>
<?php
}
?>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
....
</html>
Passing the imploded values to the next page works fine. No problem there.
I have been trying to create a javascript function to check all of the boxes that are in this form, or under the checkbox group's name, or whatever I can do to check them all with the click of a button. I've tried variations of the following with no success:
HTML (On the top of the same script as above)
----
<button name="checkAll" onclick="checkAll()">Check All</button>
Javascript (On the bottom of the same script as above)
----
<script type="text/javascript">
function checkAll() {
var checks = document.getElementByName("checkGroup");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
</script>
I can't figure out what I'm doing wrong. I know that a variation of this question has been asked before many times, but I don't seem to be getting any results. I'm guessing because my checkboxes name is an array (checkGroup[] ???).
When I click the button to check all of the checkboxes in the form, nothing happens.
Any ideas? Thanks in advance.
-Anthony
You can use JQuery to make this easier on yourself.
I would also assign a general class name to each checkbox input, so then in Javascript (using JQuery):
$(".classname").each(function() {
$(this).prop("checked",true);
});
I would also give the Check All button a unique class/id so you can do this
$(document).ready(function() {
$("#allcheckboxid").on("click",function() {
$(".classname").each(function() {
$(this).prop("checked",true);
});
});
})
Two minor things:
function checkAll() {
var checks = document.getElementsByName("checkGroup[]");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
getElementByName should be getElementsByName, and checkGroup should be checkGroup[]. Other than that your code should be good to go!
Try this way to get all checked check box elements
<button name="checkAll" onclick="checkAll()">Check All</button>
<script type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('checkGroup[]');
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
</script>
I have the following code to check a checkbox as soon as the user types something in the textbox. This works fine for a single text box.
function activateCheckbox() {
if (document.myForm.box1.checked == false) {
document.myForm.box1.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox()"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
However suppose there are more than one text boxes with a checkbox against each one and I want that only the corresponding checkbox should be checked. I modified the above code as shown below by passing a parameter to the function but it's not working, because "document.myForm.id.checked" doesn't work as it accepts the checkbox name instead of "id". Please suggest if there are better alternatives or how do I modify my code to make it working?
function activateCheckbox(id) {
if (document.myForm.id.checked == false) {
document.myForm.id.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox('box1')"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch2" name="mySearch2" size="40" onkeypress="activateCheckbox('box2')"/></td>
<td><input type="checkBox" id="box2" name="box2"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch3" name="mySearch3" size="40" onkeypress="activateCheckbox('box3')"/></td>
<td><input type="checkBox" id="box3" name="box3"/></td>
</tr>
You have a couple of options. You can do:
function activateCheckbox(id) {
if (document.myForm[id].checked == false) {
document.myForm[id].checked = true;
}
}
...or personally, I think this is a bit more clear:
function activateCheckbox(id) {
var checkbox = document.getElementById(id);
if (! checkbox.checked) {
checkbox.checked = true;
}
}
The first approach works because in JavaScript obj.someProperty means the same semantically as obj["someProperty"]. So if you have a variable that stores the name of the property you want to access, you can always do obj[name] to access the property.
The second approach is just finding the checkbox in the DOM by its id. It seems cleaner to me, since you are setting the id of each checkbox anyways and since you called your variable "id".
Also note that your if statement is superfluous. The checked attribute will only ever be true or false (you can subvert this by storing other things there, but that's a completely separate topic). So setting it to true whenever it is false is logically equivalent to always setting it to true, and you can implement your handler function with a single line, like:
function activateCheckbox(id) {
document.getElementById(id).checked = true;
}
.id means literally the id property. In case you want to have it set dynamically, use the [] notation:
function activateCheckbox(id) {
if (document.myForm[id].checked == false) {
document.myForm[id].checked = true;
}
}
['test'] means .test, ['abc'] means .abc. So [id] means: access the property that id has as its value.
I advise you to use a JQuery (www.jquery.com). By adding one code line
<script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"></script>
you can solve your problem problem by write just one code line:
$('#checkboxId').attr('checked','checked');
or you can check
$('input[type="checkbox"]').attr('checked','checked');
or unckeck
$('input[type="checkbox"]').attr('checked','');
all checkboxes in you document
I am relatively new to Javascript so I'm hoping this is a simple mistake. I building a generic form validation function that is called on the form's onSubmit. The function loops through all the form's child elements, looks for certain classes, and analyzes the contents of the appropriate fields. If it finds something missing or erroneous, it displays the appropriate error message div and returns false, thus preventing the form from being submitted to the php page.
It works well in firefox 3.6.3, but in every other browser I've tested (Safari 4.0.4, Chrome 4.1, IE8) it seems to ignore the onSubmit and jump straight to the php processing page.
HTML CODE:
<form name='myForm' id='myForm' action='process_form.php' method='post' onSubmit="return validateRequired('myForm')">
<fieldset class="required radioset">
<label for='selection1'>
<input type='radio' name='selection' id='selection1' value='1'/>
Option 1
</label>
<label for='selection2'>
<input type='radio' name='selection' id='selection2' value='2'/>
Option 2
</label>
<label for='selection3'>
<input type='radio' name='selection' id='selection3' value='3'/>
Option 3
</label>
<label for='selection4'>
<input type='radio' name='selection' id='selection4' value='4'/>
Option 4
</label>
<div class='errorBox' style='visibility:hidden'>
Please make a selection
</div>
</fieldset>
<fieldset class="required checkset">
<label>
Choice 1
<input type='checkbox' name='choices' id='choice1' value='1'/>
</label>
<label>
Choice 2
<input type='checkbox' name='choices' id='choice2' value='2'/>
</label>
<label>
Choice 3
<input type='checkbox' name='choices' id='choice3' value='3'/>
</label>
<label>
Choice 4
<input type='checkbox' name='choices' id='choice4' value='4'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please choose at least one
</div>
</fieldset>
<fieldset class="required textfield" >
<label for='textinput1'>
Required Text:
<input type='text' name='textinput1' id='textinput1' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please enter some text
</div>
</fieldset>
<fieldset class="required email textfield">
<label for='email'>
Required Email:
<input type='text' name='email' id='email' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
The email address you have entered is invalid
</div>
</fieldset>
<div>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
</div>
</form>
JAVASCRIPT CODE:
function validateRequired(id){
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
/*RADIO BUTTON or CHECK BOX SET*/
if(hasClass(elem,"radioset") || hasClass(elem,"checkset")){
var inputs = elem.getElementsByTagName("input");
var check = false;
for(j = 0; j < inputs.length; j++){
if(inputs[j].checked){
check = true;
}
}
if(check == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
/*TEXT FIELD*/
else if(hasClass(elem,"textfield")){
var input = elem.getElementsByTagName("input");
if(input[0].value == ""){
errors += 1;
showError(elem);
} else {
hideError(elem);
/*EMAIL ADDRESS*/
if(hasClass(elem,"email")){
if(isValidEmail(input[0].value) == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
}
}
}
}
if(errors > 0){
returnVal = false;
} else {
returnVal = true;
}
return returnVal;}
I know this is a lot of code to look at, but any help would be appreciated. Since it works fine in one browser, Im not sure how to start debugging.
Thanks
Andrew
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
The problem is that your required and other classes are put on the <fieldset> element.
Fieldset elements are included in the form.elements collection on IE, Firefox and Opera, but not WebKit browsers (Chrome, Safari). It is these browsers where your form fails for me.
It has always been a weird quirk that <fieldset> was included in the elements collection. The DOM Level 2 HTML spec states that only ‘form control elements’ should be present in the collection, and by HTML4's definition that would seem not to include fieldsets, which have no control name or value.
You could perhaps change your code to use getElementsByTagName to pick up the fieldsets instead:
var fieldsets= form.getElementsByTagName('fieldset');
for (var i= 0; i<fieldsets.length; i++) {
var elem= fieldsets[i];
I would not use hasClass. Here's another way to try that might work better for you:
var node_list = document.getElementsByTagName('input');
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
// do something here with a <input type="text" .../>
alert(node.value);
}
}
I know that IE has problems getting the classes from some elements which have multiple classes associated with them. Regardless, this is a handy function.
If you have any kind of JavaScript error, the function will not return false, and therefore the default behavior of submitting the data will be triggered.
Try running your code through [http://www.javascriptlint.com/online_lint.php][1] first, then a debugger.
try not to use if(errors > 0)...just in every condition (for wrong input) put return false;
and at the end before the last bracket put return true;
and better use:
onSubmit="return validateRequired(this)"
and there is no need in this lines (in case you remove the errors var)
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
Not the cause of your problem, I'm sure, but it's best not to serve a set of radio buttons without one of them selected.
In your particular case, if you know that you set one when you serve the page, you don't need a "required" check; there's no way the user can get the radio buttons into a state where none are selected. Pick a sensible default, make it the first option, and make it selected. Simplify your life :)
From the W3C:
http://www.w3.org/TR/html401/interact/forms.html#radio
If no radio button in a set sharing
the same control name is initially
"on", user agent behavior for choosing
which control is initially "on" is
undefined. Note. Since existing
implementations handle this case
differently, the current specification
differs from RFC 1866 ([RFC1866]
section 8.1.2.4), which states:
At all times, exactly one of the radio
buttons in a set is checked. If
none of the <INPUT> elements of a set
of radio buttons specifies `CHECKED',
then the user agent must check the
first radio button of the set
initially.
Since user agent behavior differs,
authors should ensure that in each set
of radio buttons that one is initially
"on".
Back to basics for a second: You say it "seems to ignore the onsubmit". That leaves three possibilities that I can think of:
Your function is never called
It's called, and is bombing out part-way through due to an error
It's called, and isn't doing what you think it is, always returning true
It's not clear from your question which it is, so if I were you I'd start debugging this by putting an alert at the beginning of the function to see whether IE's calling it at all - then move that alert down and run the validation again, and see where it stops appearing (any error must be above that point).
I'd also want to alert the return value from the place it was called, to see what was coming back. If it's always true, then your code is working but not doing what you think it does.
From there, you at least have a clearer grasp of what's going on, if not an exact block of code to be scrutinising.
for (i = 0; i < document.checks.user.length; i++) //for all check boxes
{
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
<body>
<form action="" method=POST name="checks" ID="Form2">
I have a bike:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<br>
<br>
</form>
<input type="button" value="Delete"
class="btn" onclick="sub_delete()"
onmouseover="hov(this, 'btn btnhov')" onmouseout="hov(this, 'btn')"
id="Button1" name="Button1"
/>
</body>
as you probably already know when there is only one check box left document.checks.user.length = undefined. Whats the most efficient way to make sure that when there is only one check box, it will be deleted. I was thinking just thinking to add it as a seperate if statement before the if statement here.....any suggesstions.
Thanks.
Use a loop control variable, and set it to 1 if length is undefined...
var len = document.checks.user.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++) //for all check boxes
Best regards...
if (document.getElementById('Checkbox1').checked) { /* do something */ }
if you want to loop a bunch of checkboxes, you could loop the input fields of your form, like:
var formNodes = document.checks.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
}
if(document.checks.user[0]) {
//it's an array
}
else {
//it's a single element
}
Your question is somewhat confusing, since your javascript would obviously have to be inside a function called 'sub_delete' to be any use... someone with the mighty power to edit questions might improve the question by making that clearer...
So the first issue you have to get around is the fact that for single checkbox, with a given name 'user', is not an array, and therefore has no defined length, but also if you try and access it as an array.. things get confused.. a full rewrite of your javascript function might look like this:
function sub_delete{
if (typeof document.checks.user.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.checks.user.checked == true )
{
document.checks.submit();
return 0;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.checks.user.length; i < max; i++){
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
}
}//sub_delete end
HTH,
-FT
I too face the same proble with total of 5 checkboxes out of which 4 are disabled and 1 is enabled. Now the checkboxId.length is undefined, so the only option I could think of is if(checkboxId.length ==undefined ){checkboxId.checked=true & submith the form}.
It's very simple, just create a hidden input tag with the name same as the existing checkbox input tag.
For example:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<input type="hidden" name="user" value=""/>
I'd probably iterate across document.checks.elements, looking for .type == 'checkbox'.
jQuery is your friend:
$("input[type='checkbox']").attr('checked', false);
(... if jQuery is available to you?)