Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #29361 > unrolled thread

Give alert if form checkbox array is empty

Started byBunyip <bunyip@koalanet.com.au>
First post2016-01-20 13:28 +1000
Last post2016-01-20 12:54 -0300
Articles 20 on this page of 60 — 14 participants

Back to article view | Back to comp.lang.javascript


Contents

  Give alert if form checkbox array is empty Bunyip <bunyip@koalanet.com.au> - 2016-01-20 13:28 +1000
    Re: Give alert if form checkbox array is empty JJ <jj4public@vfemail.net> - 2016-01-20 12:30 +0700
      Re: Give alert if form checkbox array is empty Bunyip <bunyip@koalanet.com.au> - 2016-01-20 17:55 +1000
        Re: Give alert if form checkbox array is empty JJ <jj4public@vfemail.net> - 2016-01-20 19:29 +0700
          Re: Give alert if form checkbox array is empty "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2016-01-20 13:46 +0100
    Re: Give alert if form checkbox array is empty Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2016-01-20 08:23 +0000
      Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-20 15:52 +0100
        Re: Give alert if form checkbox array is empty Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2016-01-20 15:43 +0000
          Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-20 17:15 +0100
            Re: Give alert if form checkbox array is empty Jon Ribbens <jon+usenet@unequivocal.co.uk> - 2016-01-20 17:53 +0000
              Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-20 20:39 +0100
                Re: Give alert if form checkbox array is empty Jon Ribbens <jon+usenet@unequivocal.co.uk> - 2016-01-20 22:46 +0000
            Re: Give alert if form checkbox array is empty Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2016-01-21 07:53 +0000
              Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-21 10:52 +0100
                Re: Give alert if form checkbox array is empty Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2016-01-21 10:26 +0000
                  Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-22 00:07 +0100
    Re: Give alert if form checkbox array is empty Stefan Weiss <krewecherl@gmail.com> - 2016-01-20 10:28 +0100
      Re: Give alert if form checkbox array is empty Bunyip <bunyip@koalanet.com.au> - 2016-01-21 08:05 +1000
        Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-21 00:59 +0100
          Re: Give alert if form checkbox array is empty Stefan Weiss <krewecherl@gmail.com> - 2016-01-21 03:17 +0100
            Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-21 08:54 +0100
              Re: Give alert if form checkbox array is empty Stefan Weiss <krewecherl@gmail.com> - 2016-01-21 12:17 +0100
          Re: Give alert if form checkbox array is empty John Harris <niam@jghnorth.org.uk.invalid> - 2016-01-21 14:16 +0000
          Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-21 19:52 -0800
            Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-22 09:48 +0100
              Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-22 10:45 -0800
                Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-23 19:41 +0100
                  Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-24 17:51 -0800
                    Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-25 19:46 +0100
                      Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-27 11:09 -0800
          Re: Give alert if form checkbox array is empty Dr J R Stockton <reply1600@merlyn.demon.co.uk.invalid> - 2016-01-23 22:22 +0000
          Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-27 11:06 -0800
            Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-28 14:46 +0100
              Re: Give alert if form checkbox array is empty Gene Wirchenko <genew@telus.net> - 2016-01-28 10:30 -0800
                Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-28 20:06 +0100
                  Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-28 23:32 -0800
                    Re: Give alert if form checkbox array is empty "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2016-01-29 09:05 +0100
                      Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-29 06:02 -0800
                    Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-29 20:54 +0100
                  Re: Give alert if form checkbox array is empty John Harris <niam@jghnorth.org.uk.invalid> - 2016-01-29 10:36 +0000
                    Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-02-09 04:39 +0100
                      Re: Give alert if form checkbox array is empty John Harris <niam@jghnorth.org.uk.invalid> - 2016-02-09 18:07 +0000
                  Re: Give alert if form checkbox array is empty Gene Wirchenko <genew@telus.net> - 2016-01-29 09:32 -0800
                    Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-29 20:34 +0100
                      Re: Give alert if form checkbox array is empty Aleksandro <aleksandro@gmx.com> - 2016-01-29 16:50 -0300
                      Re: Give alert if form checkbox array is empty Stefan Weiss <krewecherl@gmail.com> - 2016-01-30 03:31 +0100
                        Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-30 04:19 +0100
                          Re: Give alert if form checkbox array is empty Stefan Weiss <krewecherl@gmail.com> - 2016-01-30 05:01 +0100
                Re: Give alert if form checkbox array is empty Aleksandro <aleksandro@gmx.com> - 2016-01-28 16:39 -0300
              Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-29 06:04 -0800
                Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-29 20:54 +0100
                  Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-29 14:55 -0800
                    Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-30 04:55 +0100
                      Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-30 15:48 -0800
                        Re: Give alert if form checkbox array is empty Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-01-31 21:02 +0100
                          Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-01-31 13:08 -0800
                            Re: Give alert if form checkbox array is empty Andrew Poulos <ap_prog@hotmail.com> - 2016-02-01 12:28 +1100
                              Re: Give alert if form checkbox array is empty Scott Sauyet <scott.sauyet@gmail.com> - 2016-02-01 17:58 -0800
    Re: Give alert if form checkbox array is empty "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2016-01-20 06:25 -0800
    Re: Give alert if form checkbox array is empty Aleksandro <aleksandro@gmx.com> - 2016-01-20 12:54 -0300

Page 1 of 3  [1] 2 3  Next page →


#29361 — Give alert if form checkbox array is empty

FromBunyip <bunyip@koalanet.com.au>
Date2016-01-20 13:28 +1000
SubjectGive alert if form checkbox array is empty
Message-ID<d5vt9b95kifj8nb7phn75pl16tpijop14s@4ax.com>
I have a form as follows:

<form enctype="multipart/form-data" method="post" action="index.html"
name="artwork" onsubmit="return check_artwork_submit()">

<input type="checkbox" name="subjectType[]" value="Abstract" />
Abstract<br />
<input type="checkbox" name="subjectType[]" value="Animal" />
Animal<br />
<input type="checkbox" name="subjectType[]" value="Impressionist" />
Impressionist<br />
<input type="checkbox" name="subjectType[]" value="Landscape" />
Landscape

<input type="submit" value="Add artwork" name="add_artwork">
</form>

I need to check that at least one sunbjectType[] has been checked and,
if not, throw an alert.

I've tried e.g.:

var subjectType_count = document.getElementByName('subjectType[]');
var is_checked = false;
for (var i = 0; i < subjectType_count; i++) {
    if (document.artwork.elements['subjectType[]'].checked) {
        is_checked = true;
        break;
    }
}
if (is_checked == false) {
    alert('Please enter the subject type');
}

...and other snippets but none of them throws the alert. Can anybody
help with this please?

TIA

[toc] | [next] | [standalone]


#29362

FromJJ <jj4public@vfemail.net>
Date2016-01-20 12:30 +0700
Message-ID<50yfbg7yskwf$.1abc2ps2gb8pf$.dlg@40tude.net>
In reply to#29361
On Wed, 20 Jan 2016 13:28:24 +1000, Bunyip wrote:

> I have a form as follows:
> 
> <form enctype="multipart/form-data" method="post" action="index.html"
> name="artwork" onsubmit="return check_artwork_submit()">
> 
> <input type="checkbox" name="subjectType[]" value="Abstract" />
> Abstract<br />
> <input type="checkbox" name="subjectType[]" value="Animal" />
> Animal<br />
> <input type="checkbox" name="subjectType[]" value="Impressionist" />
> Impressionist<br />
> <input type="checkbox" name="subjectType[]" value="Landscape" />
> Landscape
> 
> <input type="submit" value="Add artwork" name="add_artwork">
> </form>
> 
> I need to check that at least one sunbjectType[] has been checked and,
> if not, throw an alert.
> 
> I've tried e.g.:
> 
> var subjectType_count = document.getElementByName('subjectType[]');
> var is_checked = false;
> for (var i = 0; i < subjectType_count; i++) {
>     if (document.artwork.elements['subjectType[]'].checked) {
>         is_checked = true;
>         break;
>     }
> }
> if (is_checked == false) {
>     alert('Please enter the subject type');
> }
> 
> ...and other snippets but none of them throws the alert. Can anybody
> help with this please?
> 
> TIA

elements property is a collection of HTML elements, not just a single HTML
element.

[toc] | [prev] | [next] | [standalone]


#29363

FromBunyip <bunyip@koalanet.com.au>
Date2016-01-20 17:55 +1000
Message-ID<h9fu9bhhqkbrbvdk3n4mjm0kpmjarl3ae0@4ax.com>
In reply to#29362
On Wed, 20 Jan 2016 12:30:06 +0700, JJ <jj4public@vfemail.net> wrote:

>On Wed, 20 Jan 2016 13:28:24 +1000, Bunyip wrote:
>
>> I have a form as follows:
>> 
>> <form enctype="multipart/form-data" method="post" action="index.html"
>> name="artwork" onsubmit="return check_artwork_submit()">
>> 
>> <input type="checkbox" name="subjectType[]" value="Abstract" />
>> Abstract<br />
>> <input type="checkbox" name="subjectType[]" value="Animal" />
>> Animal<br />
>> <input type="checkbox" name="subjectType[]" value="Impressionist" />
>> Impressionist<br />
>> <input type="checkbox" name="subjectType[]" value="Landscape" />
>> Landscape
>> 
>> <input type="submit" value="Add artwork" name="add_artwork">
>> </form>
>> 
>> I need to check that at least one sunbjectType[] has been checked and,
>> if not, throw an alert.
>> 
>> I've tried e.g.:
>> 
>> var subjectType_count = document.getElementByName('subjectType[]');
>> var is_checked = false;
>> for (var i = 0; i < subjectType_count; i++) {
>>     if (document.artwork.elements['subjectType[]'].checked) {
>>         is_checked = true;
>>         break;
>>     }
>> }
>> if (is_checked == false) {
>>     alert('Please enter the subject type');
>> }
>> 
>> ...and other snippets but none of them throws the alert. Can anybody
>> help with this please?
>> 
>> TIA
>
>elements property is a collection of HTML elements, not just a single HTML
>element.

I think you've inadvertently answered somebody else's question.

[toc] | [prev] | [next] | [standalone]


#29369

FromJJ <jj4public@vfemail.net>
Date2016-01-20 19:29 +0700
Message-ID<zwkov5tj8kby.1txvyfpr7se50.dlg@40tude.net>
In reply to#29363
On Wed, 20 Jan 2016 17:55:09 +1000, Bunyip wrote:
> 
> I think you've inadvertently answered somebody else's question.

Oops.

[toc] | [prev] | [next] | [standalone]


#29370

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2016-01-20 13:46 +0100
Message-ID<XnsA5958C18877C4eejj99@194.109.6.166>
In reply to#29369
JJ <jj4public@vfemail.net> wrote on 20 Jan 2016 in comp.lang.javascript:

> On Wed, 20 Jan 2016 17:55:09 +1000, Bunyip wrote:
>> 
>> I think you've inadvertently answered somebody else's question.
> 
> Oops.

Methinks "answering somebody else's question" 
is the whole idea behind questions.

Regularily answering your own questions in this NG, 
that is strange.

-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [next] | [standalone]


#29364

FromCezary Tomczyk <cezary.tomczyk@gmail.com>
Date2016-01-20 08:23 +0000
Message-ID<f1e60$569f43fc$11450e97$16338@nntpswitch.blueworldhosting.com>
In reply to#29361
On 20/01/2016 03:28, Bunyip wrote:
> I have a form as follows:
>
> <form enctype="multipart/form-data" method="post" action="index.html"
> name="artwork" onsubmit="return check_artwork_submit()">
>
> <input type="checkbox" name="subjectType[]" value="Abstract" />
> Abstract<br />
> <input type="checkbox" name="subjectType[]" value="Animal" />
> Animal<br />
> <input type="checkbox" name="subjectType[]" value="Impressionist" />
> Impressionist<br />
> <input type="checkbox" name="subjectType[]" value="Landscape" />
> Landscape
>
> <input type="submit" value="Add artwork" name="add_artwork">
> </form>
>
> I need to check that at least one sunbjectType[] has been checked and,
> if not, throw an alert.
[...]

I would use document.querySelector method. Example:

<form id="testForm" action="">
   <input type="checkbox" id="Abstract" name="subjectType[]" 
value="Abstract" />
   <label for="Abstract">Abstract</label>
   <input type="checkbox" id="Animal" name="subjectType[]" value="Animal" />
   <label for="Animal">Abstract</label>
   <input type="checkbox" id="Impressionist" name="subjectType[]" 
value="Impressionist" />
   <label for="Impressionist">Impressionist</label>
   <input type="checkbox" id="Landscape" name="subjectType[]" 
value="Landscape" />
   <label for="Landscape">Landscape</label>
   <input type="submit" value="Click" />
</form>

var formElement = document.getElementById('testForm');

function processSubmit(event) {
   var isOneInputChecked = document.querySelector('#testForm 
input[name="subjectType[]"]:checked');
   console.log(isOneInputChecked);

   if (isOneInputChecked) {
     window.alert('You have checked at least one input');
   }

   event.preventDefault();
}

formElement.addEventListener('submit', processSubmit);

Working example: https://jsfiddle.net/hfo2euep/

-- 
Cezary Tomczyk
http://www.ctomczyk.pl/

[toc] | [prev] | [next] | [standalone]


#29373

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2016-01-20 15:52 +0100
Message-ID<5888602.Nj0jmESFCg@PointedEars.de>
In reply to#29364
Cezary Tomczyk wrote:

> On 20/01/2016 03:28, Bunyip wrote:
>> <form enctype="multipart/form-data" method="post" action="index.html"

That does not strike me as a sensible “action” attribute value, so hopefully 
it is just an example.  The target resource should generate a confirmation 
or error message *server-side* so that it works even without client-side 
scripting.  And if it is server-side, then it is inefficient to have all 
“.html” resources be processed by the server-side applications.  Usually one 
would have something like “index.php” there, where the “.php” suffix in this 
example can be omitted if, as recommended, one uses content negotiation to 
avoid technology-specific suffixes.

<https://www.w3.org/QA/Tips/uri-choose>

>> name="artwork" onsubmit="return check_artwork_submit()">
>>
>> <input type="checkbox" name="subjectType[]" value="Abstract" />
>> Abstract<br />
>> <input type="checkbox" name="subjectType[]" value="Animal" />
>> Animal<br />

This should be a list of checkboxes instead (“ul” element), so that the 
labels are properly wrapped.  That also implies that you properly mark up 
checkbox labels with the “label” element as suggested by Cezary.  But, 
different to his suggestion, if the “label” element contains both the 
checkbox and the label text, no “for” and “id” attributes are necessary
on the child elements, respectively.

<https://www.w3.org/TR/html5/grouping-content.html#the-ul-element>
<https://www.w3.org/TR/html5/forms.html#the-label-element>

>> […]
>> <input type="submit" value="Add artwork" name="add_artwork">
>> </form>
>>
>> I need to check that at least one sunbjectType[] has been checked and,
>> if not, throw an alert.
> [...]
> 
> I would use document.querySelector method. Example:

I would not; it is inefficient incompatible overkill here.

> <form id="testForm" action="">
>    <input type="checkbox" id="Abstract" name="subjectType[]"
> value="Abstract" />
>  […]
> </form>
> 
> var formElement = document.getElementById('testForm');

So far, so good.
 
> function processSubmit(event) {
>    var isOneInputChecked = document.querySelector('#testForm
> input[name="subjectType[]"]:checked');

Here you are looking for the form element object that you have just found.

>    console.log(isOneInputChecked);
> 
>    if (isOneInputChecked) {
>      window.alert('You have checked at least one input');
>    }
> 
>    event.preventDefault();

There is no reason to *always* prevent the default submit action, and if you 
use the event-handler attribute as the OP did, you can simply return “false” 
instead (which is backwards-compatible).

> }

  function processSubmit (event)
  {
    /*
     * or .some(el => el.checked) in an ES 6 implementation
     * such as Google V8 JavaScript in Chromium 46.0.2490.71
     */
    var isOneInputChecked = 
      [].slice.call(formElement.elements["subjectType[]"])
        .some(function (el) { return el.checked; });

    if (isOneInputChecked) {
      window.alert('You have checked at least one input');
      event.preventDefault();
    }  
  }

If Array.prototype.slice() and Array.prototype.some() are not or cannot be 
made available, you can write the loop that the latter defines explicitly 
(this is a good example where a ”break” statement would be useful).

window.alert() should not be used here.  In general, it should be avoided in 
favor of displaying additional content in the form or marking controls that 
have been filled inappropriately.  Consider, for example that in 
Firefox/Iceweasel a window.alert() is modal; it blocks the entire tab and 
darkens its viewport.  Also, the icon that is commonly used, if any, does 
not match the user’s expectation of a purely informative message.
 
> formElement.addEventListener('submit', processSubmit);

It is not necessary to do this (which does not work in in IE < 9 and IE 9 in 
Compatibility Mode) if you specify the “onsubmit” attribute in the markup as 
the OP did.

-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#29374

FromCezary Tomczyk <cezary.tomczyk@gmail.com>
Date2016-01-20 15:43 +0000
Message-ID<405a9$569fab1d$11450e97$16733@nntpswitch.blueworldhosting.com>
In reply to#29373
On 20/01/2016 14:52, Thomas 'PointedEars' Lahn wrote:
> Cezary Tomczyk wrote:
>
>> On 20/01/2016 03:28, Bunyip wrote:
>>> <form enctype="multipart/form-data" method="post" action="index.html"
>
> That does not strike me as a sensible “action” attribute value, so hopefully
> it is just an example.  The target resource should generate a confirmation
> or error message *server-side* so that it works even without client-side
> scripting.  And if it is server-side, then it is inefficient to have all
> “.html” resources be processed by the server-side applications.  Usually one
> would have something like “index.php” there, where the “.php” suffix in this
> example can be omitted if, as recommended, one uses content negotiation to
> avoid technology-specific suffixes.
>
> <https://www.w3.org/QA/Tips/uri-choose>
>
>>> name="artwork" onsubmit="return check_artwork_submit()">
>>>
>>> <input type="checkbox" name="subjectType[]" value="Abstract" />
>>> Abstract<br />
>>> <input type="checkbox" name="subjectType[]" value="Animal" />
>>> Animal<br />
>
> This should be a list of checkboxes instead (“ul” element), so that the
> labels are properly wrapped.  That also implies that you properly mark up
> checkbox labels with the “label” element as suggested by Cezary.  But,
> different to his suggestion, if the “label” element contains both the
> checkbox and the label text, no “for” and “id” attributes are necessary
> on the child elements, respectively.
>
> <https://www.w3.org/TR/html5/grouping-content.html#the-ul-element>
> <https://www.w3.org/TR/html5/forms.html#the-label-element>

I am not sure whether using implicitly labels is a good idea. I think 
there were some problems with screen readers, but I am not quite sure at 
the moment.

Also, on the other page W3C says:

"Whenever possible, use the label element to explicitly associate text 
with form elements."

Source: https://www.w3.org/WAI/tutorials/forms/labels/

>>> […]
>>> <input type="submit" value="Add artwork" name="add_artwork">
>>> </form>
>>>
>>> I need to check that at least one sunbjectType[] has been checked and,
>>> if not, throw an alert.
>> [...]
>>
>> I would use document.querySelector method. Example:
>
> I would not; it is inefficient incompatible overkill here.

I would, personally, rather measure if this impacts on performance 
significantly and decide to change the approach or not. Otherwise 
"inefficient" here, I think, is not important.

As for compatibility - in some old environments that may not be 
supported, but again, if somebody have to support those environments 
then different solution can be considered.

>> <form id="testForm" action="">
>>     <input type="checkbox" id="Abstract" name="subjectType[]"
>> value="Abstract" />
>>   […]
>> </form>
>>
>> var formElement = document.getElementById('testForm');
>
> So far, so good.
>
>> function processSubmit(event) {
>>     var isOneInputChecked = document.querySelector('#testForm
>> input[name="subjectType[]"]:checked');
>
> Here you are looking for the form element object that you have just found.

My mistake. The var declaration I left accidentally.

>>     console.log(isOneInputChecked);
>>
>>     if (isOneInputChecked) {
>>       window.alert('You have checked at least one input');
>>     }
>>
>>     event.preventDefault();
>
> There is no reason to *always* prevent the default submit action, and if you
> use the event-handler attribute as the OP did, you can simply return “false”
> instead (which is backwards-compatible).

In the event-handler attribute return "false" is fine, but I think, when 
used in my example it also stops propagation and that may not be always 
desired.

>> }
>
>    function processSubmit (event)
>    {
>      /*
>       * or .some(el => el.checked) in an ES 6 implementation
>       * such as Google V8 JavaScript in Chromium 46.0.2490.71
>       */
>      var isOneInputChecked =
>        [].slice.call(formElement.elements["subjectType[]"])
>          .some(function (el) { return el.checked; });
>
>      if (isOneInputChecked) {
>        window.alert('You have checked at least one input');
>        event.preventDefault();
>      }
>    }
>
> If Array.prototype.slice() and Array.prototype.some() are not or cannot be
> made available, you can write the loop that the latter defines explicitly
> (this is a good example where a ”break” statement would be useful).
>
> window.alert() should not be used here.  In general, it should be avoided in
> favor of displaying additional content in the form or marking controls that
> have been filled inappropriately.  Consider, for example that in
> Firefox/Iceweasel a window.alert() is modal; it blocks the entire tab and
> darkens its viewport.  Also, the icon that is commonly used, if any, does
> not match the user’s expectation of a purely informative message.

The window.alert is used there just for the sake of example. ;-)

>> formElement.addEventListener('submit', processSubmit);
>
> It is not necessary to do this (which does not work in in IE < 9 and IE 9 in
> Compatibility Mode) if you specify the “onsubmit” attribute in the markup as
> the OP did.

Alternatively some library might be used to handle cross-browser issues 
with events.

Also, I just prefer not to use inline event-handlers in favour of 
addEventListener method.

-- 
Cezary Tomczyk
http://www.ctomczyk.pl/

[toc] | [prev] | [next] | [standalone]


#29376

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2016-01-20 17:15 +0100
Message-ID<3964788.uURLdzOTfL@PointedEars.de>
In reply to#29374
Cezary Tomczyk wrote:

> On 20/01/2016 14:52, Thomas 'PointedEars' Lahn wrote:
> 
> I am not sure whether using implicitly labels is a good idea. I think
> there were some problems with screen readers, but I am not quite sure at
> the moment.

I would like to see evidence of that.  I would understand problems with 
layout engines (like dotted borders around the checkbox on focus), but 
screen readers?
 
> Also, on the other page W3C says:
> 
> "Whenever possible, use the label element to explicitly associate text
> with form elements."
> 
> Source: https://www.w3.org/WAI/tutorials/forms/labels/

But also:

<https://www.w3.org/WAI/tutorials/forms/labels/#associating-labels-implicitly>

| In some situations, form controls cannot be labelled explicitly. For 
| example, a content author might not know the id of a form field generated 
| by a script, or that script might not add an id at all. In this case the 
| label element is used as a container for both the form control and the 
| label text, so that the two are associated implicitly.

>>>> […]
>>>> <input type="submit" value="Add artwork" name="add_artwork">
>>>> </form>
>>>>
>>>> I need to check that at least one sunbjectType[] has been checked and,
>>>> if not, throw an alert.
>>> [...]
>>> I would use document.querySelector method. Example:
>> I would not; it is inefficient incompatible overkill here.
> 
> I would, personally, rather measure if this impacts on performance
> significantly and decide to change the approach or not. Otherwise
> "inefficient" here, I think, is not important.

document.querySelector(), if it works, is as efficient as the layout engine 
when matching the selector in a stylesheet against the document.
 
> As for compatibility - in some old environments that may not be
> supported, but again, if somebody have to support those environments
> then different solution can be considered.

The problem with document.querySelector() is that it depends not only on the 
layout engine’s DOM support but also on the degree of its CSS support.  You 
need a fallback in case you get a false negative from lack of support (for 
example, support for “:checked” is not a given if document.querySelector() 
is supported), but then you should have implemented the fallback approach 
that does not use document.querySelector() in the first place.
 
>>> function processSubmit(event) {
>>>     var isOneInputChecked = document.querySelector('#testForm
                                                        ^^^^^^^^^
>>> input[name="subjectType[]"]:checked');
>>
>> Here you are looking for the form element object that you have just
>> found.
> 
> My mistake. The var declaration I left accidentally.

That is another point, but it was not mine.  See the marking.
 
>>>     if (isOneInputChecked) {
>>>       window.alert('You have checked at least one input');
>>>     }
>>>
>>>     event.preventDefault();
>> There is no reason to *always* prevent the default submit action, and if
>> you use the event-handler attribute as the OP did, you can simply return
>> “false” instead (which is backwards-compatible).
> 
> In the event-handler attribute return "false" is fine, but I think, when
> used in my example it also stops propagation and that may not be always
> desired.

The point here is that your call of event.preventDefault() is independent of 
“isOneInputChecked”, in contrast to how the OP’s code was supposed to work.
 
>> window.alert() should not be used here.  […]
> 
> The window.alert is used there just for the sake of example. ;-)

Hopefully.  It was in the OP’s code already.
 
>>> formElement.addEventListener('submit', processSubmit);
>>
>> It is not necessary to do this (which does not work in in IE < 9 and IE 9
>> in Compatibility Mode) if you specify the “onsubmit” attribute in the
>> markup as the OP did.
> 
> Alternatively some library might be used to handle cross-browser issues
> with events.

There are libraries that emulate addEventListener() the wrong way.  Granted, 
I have just removed active support for IE < 9 this week from our code.
 
> Also, I just prefer not to use inline event-handlers in favour of
> addEventListener method.

Why?
 
-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#29377

FromJon Ribbens <jon+usenet@unequivocal.co.uk>
Date2016-01-20 17:53 +0000
Message-ID<slrnn9vihb.2bt.jon+usenet@wintry.unequivocal.co.uk>
In reply to#29376
On 2016-01-20, Thomas 'PointedEars' Lahn <PointedEars@web.de> wrote:
> Cezary Tomczyk wrote:
>> I am not sure whether using implicitly labels is a good idea. I think
>> there were some problems with screen readers, but I am not quite sure at
>> the moment.
>
> I would like to see evidence of that.  I would understand problems with 
> layout engines (like dotted borders around the checkbox on focus), but 
> screen readers?

WCAG 1.0 checkpoint 12.4 says "Associate labels explicitly with their
controls". "Explicitly" probably means "using the 'for' attribute" as
opposed to "implicitly by nesting the control within the label
element", because that's the way the HTML 4.01 spec uses those terms.
It's not entirely clear what the W3C meant when they wrote the
standard, because WCAG 1.0 is a mess.

  https://www.w3.org/TR/WCAG10-TECHS/#tech-associate-labels
  https://www.w3.org/TR/html401/interact/forms.html#edef-LABEL

There was presumably a reason for this rule, and I suspect it was
along the lines of what Cezary says, however I would rather hope that
screen readers have improved in the 16+ years since the rule was
created and it is no longer necessary.

On the other hand, WCAG 2.0 Technique H44 describes a way of
conforming to WCAG 2.0 by using the explicit 'for' attribute,
and there is no other technique I can see at a glance which
describes a way of conforming by using nesting instead. On the
other other hand, WCAG 2.0 Failure Technique F68, which is also
relevant, does mention the implicit nesting method. It's not
entirely clear what the W3C meant when they wrote the standard,
because WCAG 2.0 is a mess.

  https://www.w3.org/TR/WCAG20-TECHS/H44.html
  https://www.w3.org/TR/WCAG20-TECHS/F68.html

[toc] | [prev] | [next] | [standalone]


#29378

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2016-01-20 20:39 +0100
Message-ID<5616093.ohUElf7dUC@PointedEars.de>
In reply to#29377
Jon Ribbens wrote:

> On 2016-01-20, Thomas 'PointedEars' Lahn <PointedEars@web.de> wrote:
>> Cezary Tomczyk wrote:
>>> I am not sure whether using implicitly labels is a good idea. I think
>>> there were some problems with screen readers, but I am not quite sure at
>>> the moment.
>> I would like to see evidence of that.  I would understand problems with
>> layout engines (like dotted borders around the checkbox on focus), but
>> screen readers?
> 
> WCAG 1.0 checkpoint 12.4 says "Associate labels explicitly with their
> controls". "Explicitly" probably means "using the 'for' attribute" as
> opposed to "implicitly by nesting the control within the label
> element", because that's the way the HTML 4.01 spec uses those terms.
> It's not entirely clear what the W3C meant when they wrote the
> standard, because WCAG 1.0 is a mess.

Not only that; it has been succeeded by WCAG 2.0 more than 5 years ago, and

,-<http://www.w3.org/TR/2008/REC-WCAG20-20081211/>
| 
| […] Although it is possible to conform either to WCAG 1.0 or to WCAG 2.0
| (or both), the W3C recommends that new and updated content use WCAG 2.0.
| The W3C also recommends that Web accessibility policies reference WCAG
| 2.0.
 
>   https://www.w3.org/TR/html401/interact/forms.html#edef-LABEL

HTML 4.01, too, is no longer the current version of HTML.  It has been 
succeeded by HTML5 more than a year ago:

<https://www.w3.org/TR/2014/REC-html5-20141028/>

> There was presumably a reason for this rule,

Yes, but not only is that assumption not enough for a design decision, is 
irrelevant now that more recent layout engines are no longer based on HTML 
4.01.

> On the other hand, WCAG 2.0 Technique H44 describes a way of
> conforming to WCAG 2.0 by using the explicit 'for' attribute,
> and there is no other technique I can see at a glance which
> describes a way of conforming by using nesting instead. On the
> other other hand, WCAG 2.0 Failure Technique F68, which is also
> relevant, does mention the implicit nesting method. It's not
> entirely clear what the W3C meant when they wrote the standard,
> because WCAG 2.0 is a mess.

I was not of that opinion before, but reading this I have to agree: it is a 
mess :)
 
So, given these contradictory recommendations regarding accessibility, one 
should do what I said in the first place: If there is no known problem with 
nested elements, do not insist on using “for” and “id” attributes instead.

-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#29380

FromJon Ribbens <jon+usenet@unequivocal.co.uk>
Date2016-01-20 22:46 +0000
Message-ID<slrnna03n5.2bt.jon+usenet@wintry.unequivocal.co.uk>
In reply to#29378
On 2016-01-20, Thomas 'PointedEars' Lahn <PointedEars@web.de> wrote:
> Jon Ribbens wrote:
>> WCAG 1.0 checkpoint 12.4 says "Associate labels explicitly with their
>> controls". "Explicitly" probably means "using the 'for' attribute" as
>> opposed to "implicitly by nesting the control within the label
>> element", because that's the way the HTML 4.01 spec uses those terms.
>> It's not entirely clear what the W3C meant when they wrote the
>> standard, because WCAG 1.0 is a mess.
>
> Not only that; it has been succeeded by WCAG 2.0 more than 5 years ago, and
...
> HTML 4.01, too, is no longer the current version of HTML.  It has been 
> succeeded by HTML5 more than a year ago:
...
> Yes, but not only is that assumption not enough for a design decision, is 
> irrelevant now that more recent layout engines are no longer based on HTML 
> 4.01.

Well, yes, hence my specifically mentioning the 16+ years that have
passed since WCAG 1.0 and HTML 4.01 were published. I was referring
to them as evidence of the historical situation, not as any sort of
recommendation as to what to do now.

There were several bits of WCAG 1.0 that seemed to be expectations
that every web site in the world should work-around various ridiculous
bugs in specific screen readers of the time, rather than that the
vendors of those screen readers should spend a few hours fixing their
buggy software.

> So, given these contradictory recommendations regarding accessibility, one 
> should do what I said in the first place: If there is no known problem with 
> nested elements, do not insist on using “for” and “id” attributes instead.

I agree; I think the software has moved on considerably this
millennium and there is much less need for bug-compatibility with
very old user-agent software these days.

[toc] | [prev] | [next] | [standalone]


#29389

FromCezary Tomczyk <cezary.tomczyk@gmail.com>
Date2016-01-21 07:53 +0000
Message-ID<19572$56a08e96$520da86c$20767@nntpswitch.blueworldhosting.com>
In reply to#29376
On 20/01/2016 16:15, Thomas 'PointedEars' Lahn wrote:
> Cezary Tomczyk wrote:
>
>> On 20/01/2016 14:52, Thomas 'PointedEars' Lahn wrote:
>>
>> I am not sure whether using implicitly labels is a good idea. I think
>> there were some problems with screen readers, but I am not quite sure at
>> the moment.
>
> I would like to see evidence of that.  I would understand problems with
> layout engines (like dotted borders around the checkbox on focus), but
> screen readers?

Sorry, I have no evidence at the moment. I just heard about that a time 
ago and that may not be valid today's day.

>> Also, on the other page W3C says:
>>
>> "Whenever possible, use the label element to explicitly associate text
>> with form elements."
>>
>> Source: https://www.w3.org/WAI/tutorials/forms/labels/
>
> But also:
>
> <https://www.w3.org/WAI/tutorials/forms/labels/#associating-labels-implicitly>
>
> | In some situations, form controls cannot be labelled explicitly. For
> | example, a content author might not know the id of a form field generated
> | by a script, or that script might not add an id at all. In this case the
> | label element is used as a container for both the form control and the
> | label text, so that the two are associated implicitly.

Fair enough. I think it's always better to have label (no matter if 
implicitly or explicitly way associated) than not at all.

>>>>> […]
>>>>> <input type="submit" value="Add artwork" name="add_artwork">
>>>>> </form>
>>>>>
>>>>> I need to check that at least one sunbjectType[] has been checked and,
>>>>> if not, throw an alert.
>>>> [...]
>>>> I would use document.querySelector method. Example:
>>> I would not; it is inefficient incompatible overkill here.
>>
>> I would, personally, rather measure if this impacts on performance
>> significantly and decide to change the approach or not. Otherwise
>> "inefficient" here, I think, is not important.
>
> document.querySelector(), if it works, is as efficient as the layout engine
> when matching the selector in a stylesheet against the document.

Good to know. However, I strongly suppose in that specified case there 
is no significant impact on performance.

>> As for compatibility - in some old environments that may not be
>> supported, but again, if somebody have to support those environments
>> then different solution can be considered.
>
> The problem with document.querySelector() is that it depends not only on the
> layout engine’s DOM support but also on the degree of its CSS support.  You
> need a fallback in case you get a false negative from lack of support (for
> example, support for “:checked” is not a given if document.querySelector()
> is supported), but then you should have implemented the fallback approach
> that does not use document.querySelector() in the first place.

document.querySelector has been implemented couple of years already and 
I strongly suppose when some environment is not supporting it than it 
has to be very old environment.

>>>> function processSubmit(event) {
>>>>      var isOneInputChecked = document.querySelector('#testForm
>                                                          ^^^^^^^^^
>>>> input[name="subjectType[]"]:checked');
>>>
>>> Here you are looking for the form element object that you have just
>>> found.
>>
>> My mistake. The var declaration I left accidentally.
>
> That is another point, but it was not mine.  See the marking.
>
>>>>      if (isOneInputChecked) {
>>>>        window.alert('You have checked at least one input');
>>>>      }
>>>>
>>>>      event.preventDefault();
>>> There is no reason to *always* prevent the default submit action, and if
>>> you use the event-handler attribute as the OP did, you can simply return
>>> “false” instead (which is backwards-compatible).
>>
>> In the event-handler attribute return "false" is fine, but I think, when
>> used in my example it also stops propagation and that may not be always
>> desired.
>
> The point here is that your call of event.preventDefault() is independent of
> “isOneInputChecked”, in contrast to how the OP’s code was supposed to work.

Fair enough.

return window.alert should be instead.

>>> window.alert() should not be used here.  […]
>>
>> The window.alert is used there just for the sake of example. ;-)
>
> Hopefully.  It was in the OP’s code already.

:-)

>>>> formElement.addEventListener('submit', processSubmit);
>>>
>>> It is not necessary to do this (which does not work in in IE < 9 and IE 9
>>> in Compatibility Mode) if you specify the “onsubmit” attribute in the
>>> markup as the OP did.
>>
>> Alternatively some library might be used to handle cross-browser issues
>> with events.
>
> There are libraries that emulate addEventListener() the wrong way.  Granted,
> I have just removed active support for IE < 9 this week from our code.
>
>> Also, I just prefer not to use inline event-handlers in favour of
>> addEventListener method.
>
> Why?

*I* just prefer not to have behaviour defined in presentation layer.

Also, when I write for Chrome extension then I simply can't use inline 
event-handlers due to Content Security Police. See:

https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution

-- 
Cezary Tomczyk
http://www.ctomczyk.pl/

[toc] | [prev] | [next] | [standalone]


#29392

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2016-01-21 10:52 +0100
Message-ID<2757422.ibQTPl4PXH@PointedEars.de>
In reply to#29389
Cezary Tomczyk wrote:

> On 20/01/2016 16:15, Thomas 'PointedEars' Lahn wrote:
>> Cezary Tomczyk wrote:
>>> As for compatibility - in some old environments that may not be
>>> supported, but again, if somebody have to support those environments
>>> then different solution can be considered.
>>
>> The problem with document.querySelector() is that it depends not only on
>> the layout engine’s DOM support but also on the degree of its CSS 
>> support.  You need a fallback in case you get a false negative from lack
                                                   ^^^^^^^^^^^^^^^^^^^^^^^^
>> of support (for example, support for “:checked” is not a given if
   ^^^^^^^^^^
>> document.querySelector() is supported), but then you should have
>> implemented the fallback approach that does not use
>> document.querySelector() in the first place.
> 
> document.querySelector has been implemented couple of years already and
> I strongly suppose when some environment is not supporting it than it
> has to be very old environment.

Apparently I am not making myself clear.  The *support* of 
document.querySelector() does _not_ imply support of certain *selectors* 
*because* certain selectors were not yet specified/supported when 
document.querySelector() was introduced.  For example, the “:checked” pseudo 
class was standardized with CSS3 Selectors in 2011 [1]; 
document.querySelector() was standardized with Selectors API Level 1 in 2013 
[2].

[1] <https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked>
[2] <https://www.w3.org/TR/2013/REC-selectors-api-20130221/>

>> The point here is that your call of event.preventDefault() is independent
>> of “isOneInputChecked”, in contrast to how the OP’s code was supposed to
>> work.
> 
> Fair enough.
> 
> return window.alert should be instead.

What is that supposed to accomplish?
 
-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#29393

FromCezary Tomczyk <cezary.tomczyk@gmail.com>
Date2016-01-21 10:26 +0000
Message-ID<a5d87$56a0b254$11450e97$21447@nntpswitch.blueworldhosting.com>
In reply to#29392
On 21/01/2016 09:52, Thomas 'PointedEars' Lahn wrote:
> Cezary Tomczyk wrote:
>
>> On 20/01/2016 16:15, Thomas 'PointedEars' Lahn wrote:
>>> Cezary Tomczyk wrote:
>>>> As for compatibility - in some old environments that may not be
>>>> supported, but again, if somebody have to support those environments
>>>> then different solution can be considered.
>>>
>>> The problem with document.querySelector() is that it depends not only on
>>> the layout engine’s DOM support but also on the degree of its CSS
>>> support.  You need a fallback in case you get a false negative from lack
>                                                     ^^^^^^^^^^^^^^^^^^^^^^^^
>>> of support (for example, support for “:checked” is not a given if
>     ^^^^^^^^^^
>>> document.querySelector() is supported), but then you should have
>>> implemented the fallback approach that does not use
>>> document.querySelector() in the first place.
>>
>> document.querySelector has been implemented couple of years already and
>> I strongly suppose when some environment is not supporting it than it
>> has to be very old environment.
>
> Apparently I am not making myself clear.  The *support* of
> document.querySelector() does _not_ imply support of certain *selectors*
> *because* certain selectors were not yet specified/supported when
> document.querySelector() was introduced.  For example, the “:checked” pseudo
> class was standardized with CSS3 Selectors in 2011 [1];
> document.querySelector() was standardized with Selectors API Level 1 in 2013
> [2].
>
> [1] <https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked>
> [2] <https://www.w3.org/TR/2013/REC-selectors-api-20130221/>

Got it.

Can you recommend some reliable way of test if specified selector is 
supported or not?

>>> The point here is that your call of event.preventDefault() is independent
>>> of “isOneInputChecked”, in contrast to how the OP’s code was supposed to
>>> work.
>>
>> Fair enough.
>>
>> return window.alert should be instead.
>
> What is that supposed to accomplish?

I thought about return window.confirm :-) but wrote window.alert.

Plus, in that particular case window.confirm has nothing to do :-)

-- 
Cezary Tomczyk
http://www.ctomczyk.pl/

[toc] | [prev] | [next] | [standalone]


#29398

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2016-01-22 00:07 +0100
Message-ID<1667727.3LLY7Eaobt@PointedEars.de>
In reply to#29393
Cezary Tomczyk wrote:

> On 21/01/2016 09:52, Thomas 'PointedEars' Lahn wrote:
>> […]  The *support* of document.querySelector() does _not_ imply support$
>> of certain *selectors* *because* certain selectors were not yet
>> specified/supported when document.querySelector() was introduced.  For
>> example, the “:checked” pseudo class was standardized with CSS3 Selectors
>> in 2011 [1]; document.querySelector() was standardized with Selectors API
>> Level 1 in2013 [2].
>>
>> [1] <https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked>
>> [2] <https://www.w3.org/TR/2013/REC-selectors-api-20130221/>
> 
> Got it.

It was a bad example, though, because specification-wise “:checked” 
*predates* querySelector() (qS) and querySelectorAll() (qSA).  On the other 
hand it shows the chronological disparity between the support of either 
feature.  That is, “:checked” *might* be safe with qS() and qSA() – and a 
comparison on <http://caniuse.com/> suggests it is [1]¹ – because it became 
a standard before d.qS(), but you can think of more recently 
introduced/supported selectors to which this does not apply because of that.
<https://www.w3.org/TR/2013/WD-selectors4-20130502/#overview> where the 
“Level” is “4” only, are prime candidates.
 
> Can you recommend some reliable way of test if specified selector is
> supported or not?

Perhaps. (Wrong question ;-))

(But: Good question, in this case.)  There might be a reliable way.  It is 
specified both in Selectors API Level 1 (which refers to CSS Selectors Level 
3) and DOM Level 4 (which refers to CSS Selectors Level 4 [WD/ED]) that for 
an “*invalid*” selector a DOMException with the “code” attribute set to 
DOMException::SYNTAX_ERR (12) should be thrown by qS() and qSA():

<https://www.w3.org/TR/2013/REC-selectors-api-20130221/#processing-selectors>
<https://www.w3.org/TR/2015/REC-dom-20151119/#scope-match-a-selectors-string>

This is implemented so in Blink 537.26 (tested in Chromium 46.0.2490.71 on 
Debian GNU/Linux) and Gecko 38.0 (Iceweasel 38.1.0), i.e. a DOMException is 
thrown whose “code” property has the value 12.

Blink:

| > try { document.querySelector(":blub") } catch (e) { console.log(e, 
| > e.code) }
| DOMException: Failed to execute 'querySelector' on 'Document': ':blub' is 
| not a valid selector.(…) 12

Gecko:

| < try { document.querySelector(":blub") } catch (e) { e }
| > […] DOMException [SyntaxError: "An invalid or illegal string was 
| > specified"
| code: 12
| nsresult: 0x8053000c
| location: debugger eval code:1]

Therefore, the following works there:

  try
  {
    document.querySelector(":blub");
  }
  catch (e)
  {
    if (e instanceof DOMException && e.code === 12)  // ²
    {
      /* handling for invalid/unsupported selector */
    }
  }

This can be confirmed for specified but unsupported selectors in that Gecko 
version with ":read-write" and in that Blink version with ":drop(…)".

________
¹  Something can be learned here: In a compatibility matrix, it can be 
   useful to provide functionality to compare the support for *several*
   features in one view.  caniuse.com does not provide such yet, so
   I had to open several tabs and switch between them.
²  They should have standardized Mozilla’s “… catch (e if …) { … }”
   so that you can have “… catch (e if e instanceof DOMException) { … }”
   as a shortcut everywhere.

[1] <http://caniuse.com/#search=querySelector>
    <http://caniuse.com/#search=%3Achecked>
-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#29365

FromStefan Weiss <krewecherl@gmail.com>
Date2016-01-20 10:28 +0100
Message-ID<n7njvu$51k$1@news.albasani.net>
In reply to#29361
On 01/20/2016 04:28, Bunyip wrote:
> var subjectType_count = document.getElementByName('subjectType[]');
> var is_checked = false;
> for (var i = 0; i < subjectType_count; i++) {
>     if (document.artwork.elements['subjectType[]'].checked) {

getElementByName() doesn't exist.
getElementsByName() returns a NodeList (not its length).

var subjectTypes = document.getElementsByName('subjectType[]');
for (var i = 0; i < subjectTypes.length; i++) {
      if (subjectTypes[i].checked) {
          ...

The querySelector() suggestion works, too.


- stefan

[toc] | [prev] | [next] | [standalone]


#29379

FromBunyip <bunyip@koalanet.com.au>
Date2016-01-21 08:05 +1000
Message-ID<mu00ablmp9s6ronvrrejt2npfp5uffhpc5@4ax.com>
In reply to#29365
On Wed, 20 Jan 2016 10:28:29 +0100, Stefan Weiss
<krewecherl@gmail.com> wrote:

>
>var subjectTypes = document.getElementsByName('subjectType[]');
>for (var i = 0; i < subjectTypes.length; i++) {
>      if (subjectTypes[i].checked) {
> 
Many thanks, Stefan. This worked:

var subjectTypes = document.getElementsByName('subjectType[]');
var STchecked;
for (var i = 0; i < subjectTypes.length; i++) {
	if (subjectTypes[i].checked) {
		STchecked = 1;
		break;
	}
}
if (!STchecked){
	alert("Please enter the subject type");
	form.focus();
	return false;
}

[toc] | [prev] | [next] | [standalone]


#29382

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2016-01-21 00:59 +0100
Message-ID<1851504.v7CTRd67sv@PointedEars.de>
In reply to#29379
Bunyip wrote:
^^^^^^
Please post using your full (real) name.

> On Wed, 20 Jan 2016 10:28:29 +0100, Stefan Weiss
> <krewecherl@gmail.com> wrote:
>>var subjectTypes = document.getElementsByName('subjectType[]');
>>for (var i = 0; i < subjectTypes.length; i++) {
>>      if (subjectTypes[i].checked) {
>> 
> Many thanks, Stefan. This worked:
> 
> var subjectTypes = document.getElementsByName('subjectType[]');

The disadvantage of using “document.getElementsByName()” over (here) the 
“form.elements” collection is that the former applies to all names in the 
document, while the latter only applies to the controls of that specific 
form.  As as result, the latter is not only more efficient, but also less 
error-prone.

Also, since the reference to the form element object is available in the 
event-handler attribute and in the listener with “this” (unless you unwisely 
use attachEvent()), the latter can be made to work regardless of the form 
name or position in the document.

> var STchecked;

Names should not start with a capital letter unless the value of the 
variable/property is intended to be a reference to a constructor.

> for (var i = 0; i < subjectTypes.length; i++) {

  for (var i = 0, len = subjectTypes.length; i < len; i++) {

But make sure that you do not modify “len” elsewhere.

> if (subjectTypes[i].checked) {
> STchecked = 1;
> break;
> }

You should familiarize yourself with the Array methods introduced with 
implementations of ECMAScript Edition 5 at the latest, in order to not write 
explicit loops where they are not necessary.  Examples have been given.  

Keep in mind that the built-in implementation of an algorithm is naturally 
always the most efficient one to use as it is, at best, provided in machine 
code already.

> }
> if (!STchecked){
> alert("Please enter the subject type");

Again, do not use alert(); update the form instead.  In this case, the 
“fieldset” element for the checkbox group could be highlighted.

> form.focus();

Pointless.  The form already receives the focus once the alert message is 
closed, since it had the focus when it was submitted.  You should focus the 
offending form control instead.

-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#29386

FromStefan Weiss <krewecherl@gmail.com>
Date2016-01-21 03:17 +0100
Message-ID<n7pf3c$973$1@news.albasani.net>
In reply to#29382
On 01/21/2016 00:59, Thomas 'PointedEars' Lahn wrote:
>> for (var i = 0; i < subjectTypes.length; i++) {
> 
>   for (var i = 0, len = subjectTypes.length; i < len; i++) {
> 
> But make sure that you do not modify “len” elsewhere.

Premature optimization is the root of all evil.

> You should familiarize yourself with the Array methods introduced with 
> implementations of ECMAScript Edition 5 at the latest, in order to not write 
> explicit loops where they are not necessary.  Examples have been given.  
> 
> Keep in mind that the built-in implementation of an algorithm is naturally 
> always the most efficient one to use as it is, at best, provided in machine 
> code already.

Had you tested this, you would have discovered that your version - the
one with `[].slice.call(...)` - takes 2 to 17 times longer than the
simple loop, depending on the browser and which checkboxes are checked.

Also, storing `subjectTypes.length` in a variable has almost no benefit:
it makes the loop a tiny bit faster in Firefox (about 5 nanoseconds per
iteration on my laptop), and a tiny bit slower in Chrome (about the same
difference in the other direction). Making assumptions about the
performance of modern JS engines without testing or intimate knowledge
of the internal optimizations is pointless.

Not that speed matters in this case - there are four checkboxes to test,
what kind of performance do you think we need for that? But you were
criticizing posted code for its performance and at the same time
advocating a slower and less readable version, so I thought you'd like
to know.

- stefan

[toc] | [prev] | [next] | [standalone]


Page 1 of 3  [1] 2 3  Next page →

Back to top | Article view | comp.lang.javascript


csiph-web