...

View Full Version : Checkboxes, Radio Buttons and Forms



lordofthesword8
07-08-2004, 02:56 PM
1. With a checkbox in a form, using Javascript can you find out if its checked or not, and with a radio button, can you find out wich of thoose is selected?

2. Can you make a Form FIled un-editable using HTML or Javascript?

LOTS8

Vincent Puglia
07-08-2004, 03:23 PM
Hi,

1) <input type='checkbox' name='chk' onclick='alert(this.checked)'>

<input type='checkbox' name='chk' onclick='doit(this)'>

function doit(theObj)
{
msg = (theObj.checked) ? "it's checked" : "it's not checked";
alert(msg)
}

2)
<form name='theForm'>
<input type='radio' name='rad' value='yes'>
<input type='radio' name='rad' value='no'>
<input type='button' value='Get Rad Value' onclick="doit(this.form)">
</form>

function doit(formObj)
{
for (var i = 0; i < formObj.length; i++)
{
if (formObj.elements[i].type == 'radio')
{
var el = formObj.elements[i];
if (el.checked)
alert(el.value)
}
}
}

3)
<input .... onfocus=this.blur()>
<input.....readonly>
<input.....disabled=true>

Vinny

lordofthesword8
07-08-2004, 08:16 PM
Thanks for 3, as it is really important. Could you please explain 1 and 2 a bit, though as I can see the logic.

Vincent Puglia
07-08-2004, 08:42 PM
'this' is a javascript reserved word. For the most part it acts like a pointer and refers to whatever element it is in. It can also be used to point to some other element within the object's tree

'alert(this.checked)' --> the 'this' means the checkbox element/object
="doit(this.form)"> --> the 'this' means the button element and thus the form in which the button is found.


msg = (theObj.checked) ? "it's checked" : "it's not checked";

variable = (true/false conditional statement) ? ''result if condition is true" : "result if condition is false";

The first doit() function is called with onclick event handlers -- only the element concerned is being sent as a parameter so it's checked property can be tested immediately.

the second doit() function is called later (through the button). Since the entire form is passed, it is necessary to loop through the form's elements and find the desired objects (in actual code more testing would probably be necessary) Once found, the object's checked property is tested. (btw: Radios, by default, are arrays and any group of elements that have the same name will also be considered arrays by javascript -- and virtually every other language I know )

Vinny

lordofthesword8
07-09-2004, 12:12 PM
Thanks a lot for this

Vincent Puglia
07-09-2004, 01:14 PM
You're welcome. if interested, http://www.htmlgoodies.com has a good series of online tutorials on javascript. You might also want to see: http://members.aol.com/grassblad -- it's my old site (scripts with explanations) that AOL was supposed to take down months ago. :D

Vinny



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum