By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,916 Members | 1,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,916 IT Pros & Developers. It's quick & easy.

Finding srcElement element value

P: n/a
I am trying to write a function that will test all the checkboxes in a
particular group of a form (it's a questionnaire), see whether more
than three of them are ticked, and display a message if there are. To
avoid putting an onClick on each individual checkbox, I am trying to
put an onClick in the <TABLEtag that surrounds each question and use
srcElement to tell which group has been clicked on and check each
checkbox within that group in turn, counting up any ticked ones as I
go. I am having trouble accessing each individual element index
within the group, ie if a batch of checkboxes were all grouped as V6,
the first one would be called V6[0], then V6[1] etc. I thought I could
use a for...next loop to cycle through them. Have a look at what I've
got so far, which doesn't work. Does anyone see where I am going
wrong?

function limitchecked(){
obj=event.srcElement;
if (obj.type=="checkbox"){
var group=form.elements[obj.name] // try to create a group based on
the name of the question
var count=0;
for(var i=0;i<group.length;count+=Number(group[i++].checked)) //
cycle through the group
if(count>3){
alert("You may only check three items.");
event.srcElement.id=false;}}}
Steve Wylie

Feb 1 '07 #1
Share this Question
Share on Google+
9 Replies


P: n/a
Daz
On Feb 1, 3:49 pm, stev...@hotmail.com wrote:
I am trying to write a function that will test all the checkboxes in a
particular group of a form (it's a questionnaire), see whether more
than three of them are ticked, and display a message if there are. To
avoid putting an onClick on each individual checkbox, I am trying to
put an onClick in the <TABLEtag that surrounds each question and use
srcElement to tell which group has been clicked on and check each
checkbox within that group in turn, counting up any ticked ones as I
go. I am having trouble accessing each individual element index
within the group, ie if a batch of checkboxes were all grouped as V6,
the first one would be called V6[0], then V6[1] etc. I thought I could
use a for...next loop to cycle through them. Have a look at what I've
got so far, which doesn't work. Does anyone see where I am going
wrong?

function limitchecked(){
obj=event.srcElement;
if (obj.type=="checkbox"){
var group=form.elements[obj.name] // try to create a group based on
the name of the question
var count=0;
for(var i=0;i<group.length;count+=Number(group[i++].checked)) //
cycle through the group
if(count>3){
alert("You may only check three items.");
event.srcElement.id=false;}}}

Steve Wylie

Hi Steve.

I can't really see what the script does in the context you show it in
(i.e. without the form that's being processed), however, I am
wondering why you have "count+=Number(group[i++].checked" in the
actual for loop?

I don't believe running a for loop without a body of some sort, is
syntactically correct, and I believe it might be running your if
statement more than once as a result.

If you truly want an empty for loop, you can do it like this: for (var
i = 0; i < 10; i++) { ; }

Note that the body is empty, and to save confusion, I have added a
semi-colon so we can see it was intended that way, and hopefully the
JavaScript engine won't see it as being a mistake. The closing curly
brace tells the JavaScript engine that the for loop ends there.
Without it, I am certain that the JavaScript engine will look for the
for loop body, which will be the line after.

In your particular situation, I believe it might benefit you to do
something like this:

function limitchecked(){
obj=event.srcElement;
if (obj.type=="checkbox"){
var group=form.elements[obj.name]
var count=0;
for(var i=0;i<group.length; i++)
{
count+= (Number(group[i].checked)) ? 1 :
0;
}
if(count>3){
alert("You may only check three items.");
event.srcElement.id=false;
}
}
}
I have used a shorthand if statement, which will add 1 to 'count', if
the box is checked, and 0 if it's not. I know this isn't perfect, and
it's totally untested, so it could be completely wrong. I would also
suggest you put an alert() in at different stages of the function, to
make sure that it's getting through the if statements, as I am not
sure if it will get past the first, but again, I could be wrong.

Good luck.

Daz.

Feb 1 '07 #2

P: n/a
It does work, Daz, perfectly. Thanks very much for your help.

I did change one line: "obj.checked=false" rather than
"event.srcElement.id=false" - this has the effect of taking the tick
out of the extra unwanted checkbox.

I must confess, I did get the original script from another user of
this newsgroup, back in September 2002. If you do a general Google
Groups search on "limitchecked" you should only find two messages -
this one and the 2002 one. The thing about the original 2002 script
is you had to put an onclick on each checkbox - and I was looking for
a way round that, using srcElement.

I must confess the shorthand for...next statement you refer to still
perplexes me. I know it works but even my limited knowledge of
Javascript "shorthand" (you know, the x?y:z way of doing simple "if"
statements - I think they're called conditional operators) cannot help
figure out how.

But anyway, your solution appears to work, so again thank you.

Steve Wylie
Canterbury
England

Feb 2 '07 #3

P: n/a
On Feb 2, 1:49 am, stev...@hotmail.com wrote:
I am trying to write a function that will test all the checkboxes in a
particular group of a form (it's a questionnaire), see whether more
than three of them are ticked, and display a message if there are. To
avoid putting an onClick on each individual checkbox, I am trying to
put an onClick in the <TABLEtag that surrounds each question and use
srcElement to tell which group has been clicked on
event.srcElement belongs to the IE event model, many browsers support
the W3C event model with event.target instead so be careful not to
exclude those users.
and check each
checkbox within that group in turn, counting up any ticked ones as I
go. I am having trouble accessing each individual element index
within the group, ie if a batch of checkboxes were all grouped as V6,
the first one would be called V6[0], then V6[1] etc. I thought I could
use a for...next loop to cycle through them. Have a look at what I've
got so far, which doesn't work. Does anyone see where I am going
wrong?

function limitchecked(){
obj=event.srcElement;
This depends on the IE event model. To cover both IE and W3C event
models, you need something like:

[HTML]

<table onclick="limitchecked(event);">
...
<form ... >
...
<input type="checkbox" name="v6" ...>
<input type="checkbox" name="v6" ...>
...

[script]

<script type="text/javascript">

function limitchecked (e)
{
var e = e || window.event;
var obj = e.target || e.srcElement;
...

if (obj.type=="checkbox"){
var group=form.elements[obj.name] // try to create a group based on
the name of the question
var group = obj.form.elements[obj.name];

var count=0;
for(var i=0;i<group.length;count+=Number(group[i++].checked)) //
cycle through the group
for (var i=0; i<group.length; i++) {
if (group[i].checked) count++;
if(count>3){
alert("You may only check three items.");
event.srcElement.id=false;}}}
I have no idea what that is supposed to do. If you are trying to
deselect element that was just clicked on, do:

obj.checked = false;
}
}
}

Untested, but it should to the job.
--
Rob

Feb 2 '07 #4

P: n/a
Daz
On Feb 2, 8:43 am, stev...@hotmail.com wrote:
It does work, Daz, perfectly. Thanks very much for your help.

I did change one line: "obj.checked=false" rather than
"event.srcElement.id=false" - this has the effect of taking the tick
out of the extra unwanted checkbox.

I must confess, I did get the original script from another user of
this newsgroup, back in September 2002. If you do a general Google
Groups search on "limitchecked" you should only find two messages -
this one and the 2002 one. The thing about the original 2002 script
is you had to put an onclick on each checkbox - and I was looking for
a way round that, using srcElement.

I must confess the shorthand for...next statement you refer to still
perplexes me. I know it works but even my limited knowledge of
Javascript "shorthand" (you know, the x?y:z way of doing simple "if"
statements - I think they're called conditional operators) cannot help
figure out how.

But anyway, your solution appears to work, so again thank you.

Steve Wylie
Canterbury
England

The shorthand if works like this:

(conditional statement) ? if_true_return_this_value :
else_if_false_return_this_value;

You can also nest them like this:

(conditional statement) ? if_true_do_this (conditional
statement) ? if_true_return_this_value :
else_if_false_return_this_value; : else_if_false_return_this_value;

If the first conditional statement returns true, then the next
conditional statement is executed. You can nest as many statements as
you wish, although it gets hard to read. But basically this:

var answer = (some_var == 1) ? true : false;

is the equivilent of this:

var answer;
if (some_var == 1)
answer = true;
else
answer = false;

Feb 2 '07 #5

P: n/a
Thanks for that Daz - and to RobG for his response. I have used
simple conditional operators before, but only for simple statements.
Nesting them should prove fun...

Am I right, though, that you cannot have multiple statements for the
True and False bits (ie after the question mark)? I did try before
grouping them together with {braces} separated by semi-colons but it
didn't work. Does this method only work if you have a single action
for each True/False?
Feb 2 '07 #6

P: n/a
Daz wrote:
But basically this:

var answer = (some_var == 1) ? true : false;

is the equivilent of this:

var answer;
if (some_var == 1)
answer = true;
else
answer = false;
Both of which are long-winded ways of writing:

var answer = (some_var==1);

:-)

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
Feb 2 '07 #7

P: n/a
Daz
On Feb 2, 2:45 pm, stev...@hotmail.com wrote:
Thanks for that Daz - and to RobG for his response. I have used
simple conditional operators before, but only for simple statements.
Nesting them should prove fun...

Am I right, though, that you cannot have multiple statements for the
True and False bits (ie after the question mark)? I did try before
grouping them together with {braces} separated by semi-colons but it
didn't work. Does this method only work if you have a single action
for each True/False?

If I understand you correctly, that is exactly how you would nest
them. Here's a slightly better example, but this time it's using PHP
as I can't think up anything simple with JavaScript.

This is a line I would use to set a variable to the value of the
appropriate POST or GET variable if it exists.

$my_variable = (isset($_GET['my_var']) || isset($_POST['my_var']))) ?
($_POST['my_var']) ? $_POST['my_var'] : $_GET['my_var'] : '';

PHP might be familiar to you, but id it's not it shouldn't be too hard
to understand as the syntax is very similar to that of JavaScript.

The variable '$my_variable', is initialised using the shorthand 'if
statement'.

The 'if statement', checks to see if the $_POST variable 'my_var' is
set, or if the $_GET variable 'my_var' is set (using the isset()
function).

If neither are set, then the statement returns '' (see at the end of
the statement? That's the value that is returned if the conditional
statement fails). You should note that it doesn't have to return a
value. You can also have it return a function, or just run a function
if it's not a function that returns a result. If this is the case, you
wouldn't need to set a variable with the conditional statement, you
could just have the statement on it's own.

If the conditional statement returns 'true', then the conditional
statement nested inside the conditional statement is run.

The nested statement checks whether or not it's the $_POST['my_var']
that's set. If it is, then the value of that is returned, if it's not,
then it must mean it's the $_GET['my_var'] that's set. so that is
returned instead.

I hope this hasn't confused you too much, I am not too great at
explaining things, so if anyone else can give a simpler explanation, I
would appreciate it. In the meantime, if I can think of a better
JavaScript example that you can see working, I will post that.
Good luck.

Daz.

Feb 2 '07 #8

P: n/a
Daz
On Feb 2, 4:59 pm, Toby A Inkster <usenet200...@tobyinkster.co.uk>
wrote:
Daz wrote:
But basically this:
var answer = (some_var == 1) ? true : false;
is the equivilent of this:
var answer;
if (some_var == 1)
answer = true;
else
answer = false;

Both of which are long-winded ways of writing:

var answer = (some_var==1);

:-)

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~http://tobyinkster.co.uk/contact
Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!

Thanks for that Tony. I totally agree, but sadly my imagination is
seriously lacking a clear explanation of the shorthand if statement,
so I did it the simplest way I could. :)

Feb 2 '07 #9

P: n/a
Daz
On Feb 2, 2:45 pm, stev...@hotmail.com wrote:
Thanks for that Daz - and to RobG for his response. I have used
simple conditional operators before, but only for simple statements.
Nesting them should prove fun...

Am I right, though, that you cannot have multiple statements for the
True and False bits (ie after the question mark)? I did try before
grouping them together with {braces} separated by semi-colons but it
didn't work. Does this method only work if you have a single action
for each True/False?

I posted this before, and more than an hour later, it doesn't appear
to have gone through to the server, so I apologise if it shows up
twice.

Steve, you are correct in your statement. I didn't understand the
question earlier, and posted a wrong response. I also posted the
correct response shortly after, which again doesn't appear to have
made it to the server. I often misread things as I suffer from mild
reading difficulties, although as you can see, my typing is not
affected. Hehe.

Below is a working example of the nested shorthand 'if' statement.
Simply copy and paste it into a blank file, with an html extension,
open it in your browser of choice, and ensure JavaScript is enabled. I
have only tested it on Firefox 1.5.0.8, however.

<html>
<head>
<script type="text/javascript">

function testNumber(number)
{
if (isNaN(number))
{
alert("You did not enter a valid number");
return false;
}
var message = (number < 50)
? (number < 25)
? (number < 0)
? "less than zero"
: "between 0 and 25"
: "between 24 and 50"
: (number < 75)
? "between 49 and 75"
: (number < 100)
? "between 74 and 101"
: "more than 100";
alert(number +" is "+ message);
}
</script>
</head>
<body>
Please enter a number:<br />
<input id="input" type="text" size="3"
maxlength="3" />
<input type="submit" value="Test Number"

onclick="testNumber(document.getElementById('input ').value)" />
</body>
</html>

I have tried to make the code as readable as possible, although I am
not entirely sure if my method is the best method of acheiving this. I
am however, quite certain that using normal 'if' statements would take
up more space in the file and consume more bandwidth (which would most
likely be negligable), but normal 'if' statements would probably be
easier to read.

Basically, whatever follows the question marks (?), will be returned/
executed when the condition in the brackets in-line and above it
returns 'true'. Anything following a colon (:), will be returned/
executed when the corresponding condition returns 'false'.

As you can see, I have nested shorthand 'if' statements within
shorthand 'if' statements to demonstrate how it can be done. The code
doesn't really serve any practical purpose other than to illustrate
how shorthand 'if' statements can be nested.

To anyone who's reading this and can see bad coding practises, please
feel free to point them out to me, but bare in mind I am fairly new to
JavaScript, so my knowledge is limited. With that said, I am always
looking for ways to better my coding skills, so constructive
criticism, along with a suitable explanation is appreciated.

All the best.

Daz.

Feb 2 '07 #10

This discussion thread is closed

Replies have been disabled for this discussion.