forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy path18_http.html
More file actions
695 lines (469 loc) · 108 KB
/
18_http.html
File metadata and controls
695 lines (469 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>HTTP and Forms :: Eloquent JavaScript</title>
<link rel=stylesheet href="js/node_modules/codemirror/lib/codemirror.css">
<script src="js/acorn_codemirror.js"></script>
<link rel=stylesheet href="css/ejs.css">
<script src="js/sandbox.js"></script>
<script src="js/ejs.js"></script><script>var chapNum = 18;var sandboxLoadFiles = ["code/chapter/18_http.js"];</script></head>
<article>
<nav><a href="17_canvas.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a> <a href="19_paint.html" title="next chapter">▶</a></nav>
<h1><span class=chap_num>Chapter 18</span>HTTP and Forms</h1>
<blockquote>
<p><a class="p_ident" id="p_oMpq82ALLD" href="#p_oMpq82ALLD" tabindex="-1" role="presentation"></a>Communication must be stateless in nature [...] such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server.</p>
<footer>Roy Fielding, <cite>Architectural Styles and the Design of Network-based Software Architectures</cite></footer>
</blockquote><figure class="chapter framed"><img src="img/chapter_picture_18.jpg" alt="Picture of a web form on a medieval scroll"></figure>
<p><a class="p_ident" id="p_C6+RXvCvFu" href="#p_C6+RXvCvFu" tabindex="-1" role="presentation"></a>The <em>Hypertext Transfer Protocol</em>, already mentioned in <a href="13_browser.html#web">Chapter 13</a>, is the mechanism through which data is requested and provided on the World Wide Web. This chapter describes the protocol in more detail and explains the way browser JavaScript has access to it.</p>
<h2><a class="h_ident" id="h_vXdZCu/Tty" href="#h_vXdZCu/Tty" tabindex="-1" role="presentation"></a>The protocol</h2>
<p><a class="p_ident" id="p_uAGANEYkBZ" href="#p_uAGANEYkBZ" tabindex="-1" role="presentation"></a>If you type <em>eloquentjavascript.net/18_http.html</em> into your browser’s address bar, the browser first looks up the address of the server associated with <em>eloquentjavascript.net</em> and tries to open a TCP connection to it on port 80, the default port for HTTP traffic. If the server exists and accepts the connection, the browser might send something like this:</p>
<pre class="snippet cm-s-default" data-language="http" ><a class="c_ident" id="c_Y12YPXciUz" href="#c_Y12YPXciUz" tabindex="-1" role="presentation"></a>GET /18_http.html HTTP/1.1
Host: eloquentjavascript.net
User-Agent: Your browser's name</pre>
<p><a class="p_ident" id="p_cpaXDnG/vq" href="#p_cpaXDnG/vq" tabindex="-1" role="presentation"></a>Then the server responds, through that same connection.</p>
<pre class="snippet cm-s-default" data-language="http" ><a class="c_ident" id="c_Y84SZaL9nl" href="#c_Y84SZaL9nl" tabindex="-1" role="presentation"></a>HTTP/1.1 200 OK
Content-Length: 65585
Content-Type: text/html
Last-Modified: Mon, 08 Jan 2018 10:29:45 GMT
<!doctype html>
... the rest of the document</pre>
<p><a class="p_ident" id="p_W+0FSsrSY0" href="#p_W+0FSsrSY0" tabindex="-1" role="presentation"></a>The browser takes the part of the response after the blank line, its <em>body</em> (not to be confused with the HTML <code><body></code> tag), and displays it as an HTML document.</p>
<p><a class="p_ident" id="p_EF5P7+qf9n" href="#p_EF5P7+qf9n" tabindex="-1" role="presentation"></a>The information sent by the client is called the <em>request</em>. It starts with this line:</p>
<pre class="snippet cm-s-default" data-language="http" ><a class="c_ident" id="c_q82hekYuxl" href="#c_q82hekYuxl" tabindex="-1" role="presentation"></a>GET /18_http.html HTTP/1.1</pre>
<p><a class="p_ident" id="p_RhcvCQnL7N" href="#p_RhcvCQnL7N" tabindex="-1" role="presentation"></a>The first word is the <em>method</em> of the request. <code>GET</code> means that we want to <em>get</em> the specified resource. Other common methods are <code>DELETE</code> to delete a resource, <code>PUT</code> to create or replace it, and <code>POST</code> to send information to it. Note that the server is not obliged to carry out every request it gets. If you walk up to a random website and tell it to <code>DELETE</code> its main page, it’ll probably refuse.</p>
<p><a class="p_ident" id="p_dRtHLefq7L" href="#p_dRtHLefq7L" tabindex="-1" role="presentation"></a>The part after the method name is the path of the <em>resource</em> the request applies to. In the simplest case, a resource is simply a file on the server, but the protocol doesn’t require it to be. A resource may be anything that can be transferred <em>as if</em> it is a file. Many servers generate the responses they produce on the fly. For example, if you open <a href="https://github.com/marijnh"><em>https://github.com/marijnh</em></a>, the server looks in its database for a user named “marijnh”, and if it finds one, it will generate a profile page for that user.</p>
<p><a class="p_ident" id="p_P7s+ccxZW6" href="#p_P7s+ccxZW6" tabindex="-1" role="presentation"></a>After the resource path, the first line of the request mentions <code>HTTP/1.1</code> to indicate the version of the HTTP protocol it is using.</p>
<p><a class="p_ident" id="p_mQcW6s4Mx4" href="#p_mQcW6s4Mx4" tabindex="-1" role="presentation"></a>In practice, many sites use HTTP version 2, which supports the same concepts as version 1.1 but is a lot more complicated so that it can be faster. Browsers will automatically switch to the appropriate protocol version when talking to a given server, and the outcome of a request is the same regardless of which version is used. Because version 1.1 is more straightforward and easier to play around with, we’ll focus on that.</p>
<p><a class="p_ident" id="p_ADqYIHJxxD" href="#p_ADqYIHJxxD" tabindex="-1" role="presentation"></a>The server’s response will start with a version as well, followed by the status of the response, first as a three-digit status code and then as a human-readable string.</p>
<pre class="snippet cm-s-default" data-language="http" ><a class="c_ident" id="c_A6dkQ5Qg2b" href="#c_A6dkQ5Qg2b" tabindex="-1" role="presentation"></a>HTTP/1.1 200 OK</pre>
<p><a class="p_ident" id="p_I8BGMaErRo" href="#p_I8BGMaErRo" tabindex="-1" role="presentation"></a>Status codes starting with a 2 indicate that the request succeeded. Codes starting with 4 mean there was something wrong with the request. 404 is probably the most famous HTTP status code—it means that the resource could not be found. Codes that start with 5 mean an error happened on the server and the request is not to blame.</p>
<p id="headers"><a class="p_ident" id="p_CA64oLhdLd" href="#p_CA64oLhdLd" tabindex="-1" role="presentation"></a>The first line of a request or response may be followed by any number of <em>headers</em>. These are lines in the form <code>name: value</code> that specify extra information about the request or response. These headers were part of the example response:</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_1ObQMSreRj" href="#c_1ObQMSreRj" tabindex="-1" role="presentation"></a>Content-Length: 65585
Content-Type: text/html
Last-Modified: Thu, 04 Jan 2018 14:05:30 GMT</pre>
<p><a class="p_ident" id="p_04zcUGZ8sT" href="#p_04zcUGZ8sT" tabindex="-1" role="presentation"></a>This tells us the size and type of the response document. In this case, it is an HTML document of 65,585 bytes. It also tells us when that document was last modified.</p>
<p><a class="p_ident" id="p_CoUIJDjIMb" href="#p_CoUIJDjIMb" tabindex="-1" role="presentation"></a>For most headers, the client and server are free to decide whether to include them in a request or response. But a few are required. For example, the <code>Host</code> header, which specifies the hostname, should be included in a request because a server might be serving multiple hostnames on a single IP address, and without that header, the server won’t know which hostname the client is trying to talk to.</p>
<p><a class="p_ident" id="p_DeF17lBSIn" href="#p_DeF17lBSIn" tabindex="-1" role="presentation"></a>After the headers, both requests and responses may include a blank line followed by a body, which contains the data being sent. <code>GET</code> and <code>DELETE</code> requests don’t send along any data, but <code>PUT</code> and <code>POST</code> requests do. Similarly, some response types, such as error responses, do not require a body.</p>
<h2><a class="h_ident" id="h_G1xxLfiYeu" href="#h_G1xxLfiYeu" tabindex="-1" role="presentation"></a>Browsers and HTTP</h2>
<p><a class="p_ident" id="p_di/c79dO8s" href="#p_di/c79dO8s" tabindex="-1" role="presentation"></a>As we saw in the example, a browser will make a request when we enter a URL in its address bar. When the resulting HTML page references other files, such as images and JavaScript files, those are also retrieved.</p>
<p><a class="p_ident" id="p_H5hfE5XTVU" href="#p_H5hfE5XTVU" tabindex="-1" role="presentation"></a>A moderately complicated website can easily include anywhere from 10 to 200 resources. To be able to fetch those quickly, browsers will make several <code>GET</code> requests simultaneously, rather than waiting for the responses one at a time.</p>
<p><a class="p_ident" id="p_Aub9jfdnAA" href="#p_Aub9jfdnAA" tabindex="-1" role="presentation"></a>HTML pages may include <em>forms</em>, which allow the user to fill out information and send it to the server. This is an example of a form:</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_feixSy0wew" href="#c_feixSy0wew" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">form</span> <span class="cm-attribute">method</span>=<span class="cm-string">"GET"</span> <span class="cm-attribute">action</span>=<span class="cm-string">"example/message.html"</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>Name: <span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"name"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>Message:<span class="cm-tag cm-bracket"><</span><span class="cm-tag">br</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">textarea</span> <span class="cm-attribute">name</span>=<span class="cm-string">"message"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">type</span>=<span class="cm-string">"submit"</span><span class="cm-tag cm-bracket">></span>Send<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">form</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_wzIYNG3lpP" href="#p_wzIYNG3lpP" tabindex="-1" role="presentation"></a>This code describes a form with two fields: a small one asking for a name and a larger one to write a message in. When you click the Send button, the form is <em>submitted</em>, meaning that the content of its field is packed into an HTTP request and the browser navigates to the result of that request.</p>
<p><a class="p_ident" id="p_vktFCcfPRa" href="#p_vktFCcfPRa" tabindex="-1" role="presentation"></a>When the <code><form></code> element’s <code>method</code> attribute is <code>GET</code> (or is omitted), the information in the form is added to the end of the <code>action</code> URL as a <em>query string</em>. The browser might make a request to this URL:</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_1RUljJwVrY" href="#c_1RUljJwVrY" tabindex="-1" role="presentation"></a>GET /example/message.html?name=Jean&message=Yes%3F HTTP/1.1</pre>
<p><a class="p_ident" id="p_T5aHHLPL5V" href="#p_T5aHHLPL5V" tabindex="-1" role="presentation"></a>The question mark indicates the end of the path part of the URL and the start of the query. It is followed by pairs of names and values, corresponding to the <code>name</code> attribute on the form field elements and the content of those elements, respectively. An ampersand character (<code>&</code>) is used to separate the pairs.</p>
<p><a class="p_ident" id="p_4Eo/x5v9Qy" href="#p_4Eo/x5v9Qy" tabindex="-1" role="presentation"></a>The actual message encoded in the URL is “Yes?”, but the question mark is replaced by a strange code. Some characters in query strings must be escaped. The question mark, represented as <code>%3F</code>, is one of those. There seems to be an unwritten rule that every format needs its own way of escaping characters. This one, called <em>URL encoding</em>, uses a percent sign followed by two hexadecimal (base 16) digits that encode the character code. In this case, 3F, which is 63 in decimal notation, is the code of a question mark character. JavaScript provides the <code>encodeURIComponent</code> and <code>decodeURIComponent</code> functions to encode and decode this format.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_v2cBL8Tnwf" href="#c_v2cBL8Tnwf" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">encodeURIComponent</span>(<span class="cm-string">"Yes?"</span>));
<span class="cm-comment">// → Yes%3F</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">decodeURIComponent</span>(<span class="cm-string">"Yes%3F"</span>));
<span class="cm-comment">// → Yes?</span></pre>
<p><a class="p_ident" id="p_l15d9HkVlZ" href="#p_l15d9HkVlZ" tabindex="-1" role="presentation"></a>If we change the <code>method</code> attribute of the HTML form in the example we saw earlier to <code>POST</code>, the HTTP request made to submit the form will use the <code>POST</code> method and put the query string in the body of the request, rather than adding it to the URL.</p>
<pre class="snippet cm-s-default" data-language="http" ><a class="c_ident" id="c_5Xyh6tIq0d" href="#c_5Xyh6tIq0d" tabindex="-1" role="presentation"></a>POST /example/message.html HTTP/1.1
Content-length: 24
Content-type: application/x-www-form-urlencoded
name=Jean&message=Yes%3F</pre>
<p><a class="p_ident" id="p_DK/cEfFOLx" href="#p_DK/cEfFOLx" tabindex="-1" role="presentation"></a><code>GET</code> requests should be used for requests that do not have side
effects but simply ask for information. Requests that change something on the server, for example creating a new account or posting a message, should be expressed with other methods, such as <code>POST</code>. Client-side software such as a browser knows that it shouldn’t blindly make <code>POST</code> requests but will often implicitly make <code>GET</code> requests—for example to prefetch a resource it believes the user will soon need.</p>
<p><a class="p_ident" id="p_DhsgH7HhV5" href="#p_DhsgH7HhV5" tabindex="-1" role="presentation"></a>We’ll come back to forms and how to interact with them from JavaScript <a href="18_http.html#forms">later in the chapter</a>.</p>
<h2 id="fetch"><a class="h_ident" id="h_1Iqv5okrKE" href="#h_1Iqv5okrKE" tabindex="-1" role="presentation"></a>Fetch</h2>
<p><a class="p_ident" id="p_N4uvmrpYsh" href="#p_N4uvmrpYsh" tabindex="-1" role="presentation"></a>The interface through which browser JavaScript can make HTTP requests is called <code>fetch</code>. Since it is relatively new, it conveniently uses promises (which is rare for browser interfaces).</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_RHiMHW5ptB" href="#c_RHiMHW5ptB" tabindex="-1" role="presentation"></a><span class="cm-variable">fetch</span>(<span class="cm-string">"example/data.txt"</span>).<span class="cm-property">then</span>(<span class="cm-def">response</span> <span class="cm-operator">=></span> {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable-2">response</span>.<span class="cm-property">status</span>);
<span class="cm-comment">// → 200</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable-2">response</span>.<span class="cm-property">headers</span>.<span class="cm-property">get</span>(<span class="cm-string">"Content-Type"</span>));
<span class="cm-comment">// → text/plain</span>
});</pre>
<p><a class="p_ident" id="p_nEI47jB1j7" href="#p_nEI47jB1j7" tabindex="-1" role="presentation"></a>Calling <code>fetch</code> returns a promise that resolves to a <code>Response</code> object holding information about the server’s response, such as its status code and its headers. The headers are wrapped in a <code>Map</code>-like object that treats its keys (the header names) as case insensitive because header names are not supposed to be case sensitive. This means <code>headers.<wbr>get("Content-Type")</code> and <code>headers.<wbr>get("content-TYPE")</code> will return the same value.</p>
<p><a class="p_ident" id="p_9+aWsoAyy9" href="#p_9+aWsoAyy9" tabindex="-1" role="presentation"></a>Note that the promise returned by <code>fetch</code> resolves successfully even if the server responded with an error code. It <em>might</em> also be rejected if there is a network error or if the server that the request is addressed to can’t be found.</p>
<p><a class="p_ident" id="p_5r0Wgj3ZeL" href="#p_5r0Wgj3ZeL" tabindex="-1" role="presentation"></a>The first argument to <code>fetch</code> is the URL that should be requested. When that URL doesn’t start with a protocol name (such as <em>http:</em>), it is treated as <em>relative</em>, which means it is interpreted relative to the current document. When it starts with a slash (/), it replaces the current path, which is the part after the server name. When it does not, the part of the current path up to and including its last slash character is put in front of the relative URL.</p>
<p><a class="p_ident" id="p_I7dcmG9O8z" href="#p_I7dcmG9O8z" tabindex="-1" role="presentation"></a>To get at the actual content of a response, you can use its <code>text</code> method. Because the initial promise is resolved as soon as the response’s headers have been received and because reading the response body might take a while longer, this again returns a promise.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_p/pN7BXNbA" href="#c_p/pN7BXNbA" tabindex="-1" role="presentation"></a><span class="cm-variable">fetch</span>(<span class="cm-string">"example/data.txt"</span>)
.<span class="cm-property">then</span>(<span class="cm-def">resp</span> <span class="cm-operator">=></span> <span class="cm-variable-2">resp</span>.<span class="cm-property">text</span>())
.<span class="cm-property">then</span>(<span class="cm-def">text</span> <span class="cm-operator">=></span> <span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable-2">text</span>));
<span class="cm-comment">// → This is the content of data.txt</span></pre>
<p><a class="p_ident" id="p_yKDs0M+BWY" href="#p_yKDs0M+BWY" tabindex="-1" role="presentation"></a>A similar method, called <code>json</code>, returns a promise that resolves to the value you get when parsing the body as JSON or rejects if it’s not valid JSON.</p>
<p><a class="p_ident" id="p_zqk7Gjqi6s" href="#p_zqk7Gjqi6s" tabindex="-1" role="presentation"></a>By default, <code>fetch</code> uses the <code>GET</code> method to make its request and does not include a request body. You can configure it differently by passing an object with extra options as a second argument. For example, this request tries to delete <code>example/data.txt</code>:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_hrJqISfbr3" href="#c_hrJqISfbr3" tabindex="-1" role="presentation"></a><span class="cm-variable">fetch</span>(<span class="cm-string">"example/data.txt"</span>, {<span class="cm-property">method</span>: <span class="cm-string">"DELETE"</span>}).<span class="cm-property">then</span>(<span class="cm-def">resp</span> <span class="cm-operator">=></span> {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable-2">resp</span>.<span class="cm-property">status</span>);
<span class="cm-comment">// → 405</span>
});</pre>
<p><a class="p_ident" id="p_NyyktLENAG" href="#p_NyyktLENAG" tabindex="-1" role="presentation"></a>The 405 status code means “method not allowed”, an HTTP server’s way of saying “I can’t do that”.</p>
<p><a class="p_ident" id="p_60thNhmBur" href="#p_60thNhmBur" tabindex="-1" role="presentation"></a>To add a request body, you can include a <code>body</code> option. To set headers, there’s the <code>headers</code> option. For example, this request includes a <code>Range</code> header, which instructs the server to return only part of a response.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_ayu6SNFLBc" href="#c_ayu6SNFLBc" tabindex="-1" role="presentation"></a><span class="cm-variable">fetch</span>(<span class="cm-string">"example/data.txt"</span>, {<span class="cm-property">headers</span>: {<span class="cm-property">Range</span>: <span class="cm-string">"bytes=8-19"</span>}})
.<span class="cm-property">then</span>(<span class="cm-def">resp</span> <span class="cm-operator">=></span> <span class="cm-variable-2">resp</span>.<span class="cm-property">text</span>())
.<span class="cm-property">then</span>(<span class="cm-variable">console</span>.<span class="cm-property">log</span>);
<span class="cm-comment">// → the content</span></pre>
<p><a class="p_ident" id="p_bD3Fa3HIuA" href="#p_bD3Fa3HIuA" tabindex="-1" role="presentation"></a>The browser will automatically add some request headers, such as “Host” and those needed for the server to figure out the size of the body. But adding your own headers is often useful to include things such as authentication information or to tell the server which file format you’d like to receive.</p>
<h2 id="http_sandbox"><a class="h_ident" id="h_4h3DL+zoLY" href="#h_4h3DL+zoLY" tabindex="-1" role="presentation"></a>HTTP sandboxing</h2>
<p><a class="p_ident" id="p_JiU9W0PiCv" href="#p_JiU9W0PiCv" tabindex="-1" role="presentation"></a>Making HTTP requests in web page scripts once again raises concerns about security. The person who controls the script might not have the same interests as the person on whose computer it is running. More specifically, if I visit <em>themafia.org</em>, I do not want its scripts to be able to make a request to <em>mybank.com</em>, using identifying information from my browser, with instructions to transfer all my money to some random account.</p>
<p><a class="p_ident" id="p_XbYnzVu8E9" href="#p_XbYnzVu8E9" tabindex="-1" role="presentation"></a>For this reason, browsers protect us by disallowing scripts to make HTTP requests to other domains (names such as <em>themafia.org</em> and <em>mybank.com</em>).</p>
<p><a class="p_ident" id="p_g7fM23J7Wi" href="#p_g7fM23J7Wi" tabindex="-1" role="presentation"></a>This can be an annoying problem when building systems that want to access several domains for legitimate reasons. Fortunately, servers can include a header like this in their response to explicitly indicate to the browser that it is okay for the request to come from another domain:</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_kNUaXkbMWE" href="#c_kNUaXkbMWE" tabindex="-1" role="presentation"></a>Access-Control-Allow-Origin: *</pre>
<h2><a class="h_ident" id="h_OJmHENDG5y" href="#h_OJmHENDG5y" tabindex="-1" role="presentation"></a>Appreciating HTTP</h2>
<p><a class="p_ident" id="p_dVrq2xCOfJ" href="#p_dVrq2xCOfJ" tabindex="-1" role="presentation"></a>When building a system that requires communication between a JavaScript program running in the browser (client-side) and a program on a server (server-side), there are several different ways to model this communication.</p>
<p><a class="p_ident" id="p_xJpo9CMhYT" href="#p_xJpo9CMhYT" tabindex="-1" role="presentation"></a>A commonly used model is that of <em>remote procedure calls</em>. In this model, communication follows the patterns of normal function calls, except that the function is actually running on another machine. Calling it involves making a request to the server that includes the function’s name and arguments. The response to that request contains the returned value.</p>
<p><a class="p_ident" id="p_7z+OqsDVUu" href="#p_7z+OqsDVUu" tabindex="-1" role="presentation"></a>When thinking in terms of remote procedure calls, HTTP is just a vehicle for communication, and you will most likely write an abstraction layer that hides it entirely.</p>
<p><a class="p_ident" id="p_dOvEvBngFh" href="#p_dOvEvBngFh" tabindex="-1" role="presentation"></a>Another approach is to build your communication around the concept of resources and HTTP methods. Instead of a remote procedure called <code>addUser</code>, you use a <code>PUT</code> request to <code>/users/larry</code>. Instead of encoding that user’s properties in function arguments, you define a JSON document format (or use an existing format) that represents a user. The body of the <code>PUT</code> request to create a new resource is then such a document. A resource is fetched by making a <code>GET</code> request to the resource’s URL (for example, <code>/user/larry</code>), which again returns the document representing the resource.</p>
<p><a class="p_ident" id="p_YwC80f9YNp" href="#p_YwC80f9YNp" tabindex="-1" role="presentation"></a>This second approach makes it easier to use some of the features that HTTP provides, such as support for caching resources (keeping a copy on the client for fast access). The concepts used in HTTP, which are well designed, can provide a helpful set of principles to design your server interface around.</p>
<h2><a class="h_ident" id="h_oDqIFugKX4" href="#h_oDqIFugKX4" tabindex="-1" role="presentation"></a>Security and HTTPS</h2>
<p><a class="p_ident" id="p_VAyObUfHZm" href="#p_VAyObUfHZm" tabindex="-1" role="presentation"></a>Data traveling over the Internet tends to follow a long, dangerous road. To get to its destination, it must hop through anything from coffee shop Wi-Fi hotspots to networks controlled by various companies and states. At any point along its route it may be inspected or even modified.</p>
<p><a class="p_ident" id="p_FkVKmUiG/R" href="#p_FkVKmUiG/R" tabindex="-1" role="presentation"></a>If it is important that something remain secret, such as the password to your email account, or that it arrive at its destination unmodified, such as the account number you transfer money to via your bank’s website, plain HTTP is not good enough.</p>
<p><a class="p_ident" id="p_s1KEZa2j+E" href="#p_s1KEZa2j+E" tabindex="-1" role="presentation"></a>The secure HTTP protocol, used for URLs starting with <em>https://</em>, wraps HTTP traffic in a way that makes it harder to read and tamper with. Before exchanging data, the client verifies that the server is who it claims to be by asking it to prove that it has a cryptographic certificate issued by a certificate authority that the browser recognizes. Next, all data going over the connection is encrypted in a way that should prevent eavesdropping and tampering.</p>
<p><a class="p_ident" id="p_e4DTn5YT85" href="#p_e4DTn5YT85" tabindex="-1" role="presentation"></a>Thus, when it works right, HTTPS prevents other people from impersonating the website you are trying to talk to and from snooping on your communication. It is not perfect, and there have been various incidents where HTTPS failed because of forged or stolen certificates and broken software, but it is a <em>lot</em> safer than plain HTTP.</p>
<h2 id="forms"><a class="h_ident" id="h_H222GOgM6T" href="#h_H222GOgM6T" tabindex="-1" role="presentation"></a>Form fields</h2>
<p><a class="p_ident" id="p_TyplG8H3xg" href="#p_TyplG8H3xg" tabindex="-1" role="presentation"></a>Forms were originally designed for the pre-JavaScript Web to allow web sites to send user-submitted information in an HTTP request. This design assumes that interaction with the server always happens by navigating to a new page.</p>
<p><a class="p_ident" id="p_fnL4EDXYjc" href="#p_fnL4EDXYjc" tabindex="-1" role="presentation"></a>But their elements are part of the DOM like the rest of the page, and the DOM elements that represent form fields support a number of properties and events that are not present on other elements. These make it possible to inspect and control such input fields with JavaScript programs and do things such as adding new functionality to a form or using forms and fields as building blocks in a JavaScript application.</p>
<p><a class="p_ident" id="p_pfSLM800x5" href="#p_pfSLM800x5" tabindex="-1" role="presentation"></a>A web form consists of any number of input fields grouped in a <code><form></code> tag. HTML allows several different styles of fields, ranging from simple on/off checkboxes to drop-down menus and fields for text input. This book won’t try to comprehensively discuss all field types, but we’ll start with a rough overview.</p>
<p><a class="p_ident" id="p_Rhphckn33e" href="#p_Rhphckn33e" tabindex="-1" role="presentation"></a>A lot of field types use the <code><input></code> tag. This tag’s <code>type</code> attribute is used to select the field’s style. These are some commonly used <code><input></code> types:</p>
<table>
<tr><td><code>text</code></td><td>A single-line text field</td>
</tr>
<tr><td><code>password</code></td><td>Same as <code>text</code> but hides the text that is typed</td>
</tr>
<tr><td><code>checkbox</code></td><td>An on/off switch</td>
</tr>
<tr><td><code>radio</code></td><td>(Part of) a multiple-choice field</td>
</tr>
<tr><td><code>file</code></td><td>Allows the user to choose a file from their computer</td>
</tr>
</table>
<p><a class="p_ident" id="p_wq9TjeOZyz" href="#p_wq9TjeOZyz" tabindex="-1" role="presentation"></a>Form fields do not necessarily have to appear in a <code><form></code> tag. You can put them anywhere in a page. Such form-less fields cannot be submitted (only a form as a whole can), but when responding to input with JavaScript, we often don’t want to submit our fields normally anyway.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_BwDEUfcPYP" href="#c_BwDEUfcPYP" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"abc"</span><span class="cm-tag cm-bracket">></span> (text)<span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"password"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"abc"</span><span class="cm-tag cm-bracket">></span> (password)<span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"checkbox"</span> <span class="cm-attribute">checked</span><span class="cm-tag cm-bracket">></span> (checkbox)<span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"radio"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"A"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"choice"</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"radio"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"B"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"choice"</span> <span class="cm-attribute">checked</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"radio"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"C"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"choice"</span><span class="cm-tag cm-bracket">></span> (radio)<span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"file"</span><span class="cm-tag cm-bracket">></span> (file)<span class="cm-tag cm-bracket"></</span><span class="cm-tag">p</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_EMkwu3giRV" href="#p_EMkwu3giRV" tabindex="-1" role="presentation"></a>The JavaScript interface for such elements differs with the type of the element.</p>
<p><a class="p_ident" id="p_dU8xgBYYQy" href="#p_dU8xgBYYQy" tabindex="-1" role="presentation"></a>Multiline text fields have their own tag, <code><textarea></code>, mostly because using an attribute to specify a multiline starting value would be awkward. The <code><textarea></code> tag requires a matching <code></<wbr>textarea></code> closing tag and uses the text between those two, instead of the <code>value</code> attribute, as starting text.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_ta2qUMw3tQ" href="#c_ta2qUMw3tQ" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span>
one
two
three
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_ZYw2re7bQY" href="#p_ZYw2re7bQY" tabindex="-1" role="presentation"></a>Finally, the <code><select></code> tag is used to create a field that allows the user to select from a number of predefined options.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_ZxJgtmof49" href="#c_ZxJgtmof49" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">select</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>Pancakes<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>Pudding<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>Ice cream<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">select</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_RNW9gGQ0uZ" href="#p_RNW9gGQ0uZ" tabindex="-1" role="presentation"></a>Whenever the value of a form field changes, it will fire a <code>"change"</code> event.</p>
<h2><a class="h_ident" id="h_/n9VuL9o/U" href="#h_/n9VuL9o/U" tabindex="-1" role="presentation"></a>Focus</h2>
<p><a class="p_ident" id="p_sv9Kp9pqvi" href="#p_sv9Kp9pqvi" tabindex="-1" role="presentation"></a>Unlike most elements in HTML documents, form fields can get <em>keyboard focus</em>. When clicked or activated in some other way, they become the currently active element and the recipient of keyboard input.</p>
<p><a class="p_ident" id="p_Hyh25uQbKJ" href="#p_Hyh25uQbKJ" tabindex="-1" role="presentation"></a>Thus, you can type into a text field only when it is focused. Other fields respond differently to keyboard events. For example, a <code><select></code> menu tries to move to the option that contains the text the user typed and responds to the arrow keys by moving its selection up and down.</p>
<p><a class="p_ident" id="p_bTNSIbb+d4" href="#p_bTNSIbb+d4" tabindex="-1" role="presentation"></a>We can control focus from JavaScript with the <code>focus</code> and <code>blur</code> methods. The first moves focus to the DOM element it is called on, and the second removes focus. The value in <code>document.<wbr>activeElement</code> corresponds to the currently focused element.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_QrBgwnycJO" href="#c_QrBgwnycJO" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"input"</span>).<span class="cm-property">focus</span>();
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">document</span>.<span class="cm-property">activeElement</span>.<span class="cm-property">tagName</span>);
<span class="cm-comment">// → INPUT</span>
<span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"input"</span>).<span class="cm-property">blur</span>();
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">document</span>.<span class="cm-property">activeElement</span>.<span class="cm-property">tagName</span>);
<span class="cm-comment">// → BODY</span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_ymv/ML6eGQ" href="#p_ymv/ML6eGQ" tabindex="-1" role="presentation"></a>For some pages, the user is expected to want to interact with a form field immediately. JavaScript can be used to focus this field when the document is loaded, but HTML also provides the <code>autofocus</code> attribute, which produces the same effect while letting the browser know what we are trying to achieve. This gives the browser the option to disable the behavior when it is not appropriate, such as when the user has put the focus on something else.</p>
<p><a class="p_ident" id="p_IgspvfRub5" href="#p_IgspvfRub5" tabindex="-1" role="presentation"></a>Browsers traditionally also allow the user to move the focus through the document by pressing the <span class="keyname">tab</span> key. We can influence the order in which elements receive focus with the <code>tabindex</code> attribute. The following example document will let the focus jump from the text input to the OK button, rather than going through the help link first:</p>
<pre class="snippet cm-s-default" data-language="text/html" data-focus="true"><a class="c_ident" id="c_DXorT/vrbR" href="#c_DXorT/vrbR" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span> <span class="cm-attribute">tabindex</span>=<span class="cm-string">1</span><span class="cm-tag cm-bracket">></span> <span class="cm-tag cm-bracket"><</span><span class="cm-tag">a</span> <span class="cm-attribute">href</span>=<span class="cm-string">"."</span><span class="cm-tag cm-bracket">></span>(help)<span class="cm-tag cm-bracket"></</span><span class="cm-tag">a</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">onclick</span>=<span class="cm-string">"console.log('ok')"</span> <span class="cm-attribute">tabindex</span>=<span class="cm-string">2</span><span class="cm-tag cm-bracket">></span>OK<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_F/Js9FpFgt" href="#p_F/Js9FpFgt" tabindex="-1" role="presentation"></a>By default, most types of HTML elements cannot be focused. But you can add a <code>tabindex</code> attribute to any element that will make it focusable. A <code>tabindex</code> of -1 makes tabbing skip over an element, even if it is normally focusable.</p>
<h2><a class="h_ident" id="h_l2z9T1FDym" href="#h_l2z9T1FDym" tabindex="-1" role="presentation"></a>Disabled fields</h2>
<p><a class="p_ident" id="p_avmCql+rjT" href="#p_avmCql+rjT" tabindex="-1" role="presentation"></a>All form fields can be <em>disabled</em> through their <code>disabled</code> attribute. It is an attribute that can be specified without value—the fact that it is present at all disables the element.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_f++NW8087u" href="#c_f++NW8087u" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>I'm all right<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">disabled</span><span class="cm-tag cm-bracket">></span>I'm out<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_GR2MtLESGu" href="#p_GR2MtLESGu" tabindex="-1" role="presentation"></a>Disabled fields cannot be focused or changed, and browsers make them look gray and faded.</p>
<p><a class="p_ident" id="p_Q2URIcrW6H" href="#p_Q2URIcrW6H" tabindex="-1" role="presentation"></a>When a program is in the process of handling an action caused by some button or other control that might require communication with the server and thus take a while, it can be a good idea to disable the control until the action finishes. That way, when the user gets impatient and clicks it again, they don’t accidentally repeat their action.</p>
<h2><a class="h_ident" id="h_R8SZxHmDt0" href="#h_R8SZxHmDt0" tabindex="-1" role="presentation"></a>The form as a whole</h2>
<p><a class="p_ident" id="p_G8aitsjxoL" href="#p_G8aitsjxoL" tabindex="-1" role="presentation"></a>When a field is contained in a <code><form></code> element, its DOM element will have a <code>form</code> property linking back to the form’s DOM element. The <code><form></code> element, in turn, has a property called <code>elements</code> that contains an array-like collection of the fields inside it.</p>
<p><a class="p_ident" id="p_unq0zWRWC6" href="#p_unq0zWRWC6" tabindex="-1" role="presentation"></a>The <code>name</code> attribute of a form field determines the way its value will be identified when the form is submitted. It can also be used as a property name when accessing the form’s <code>elements</code> property, which acts both as an array-like object (accessible by number) and a map (accessible by name).</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_2pmbvR5Jhe" href="#c_2pmbvR5Jhe" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">form</span> <span class="cm-attribute">action</span>=<span class="cm-string">"example/submit.html"</span><span class="cm-tag cm-bracket">></span>
Name: <span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"name"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">br</span><span class="cm-tag cm-bracket">></span>
Password: <span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"password"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"password"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">br</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">type</span>=<span class="cm-string">"submit"</span><span class="cm-tag cm-bracket">></span>Log in<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">form</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">form</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"form"</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">form</span>.<span class="cm-property">elements</span>[<span class="cm-number">1</span>].<span class="cm-property">type</span>);
<span class="cm-comment">// → password</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">form</span>.<span class="cm-property">elements</span>.<span class="cm-property">password</span>.<span class="cm-property">type</span>);
<span class="cm-comment">// → password</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">form</span>.<span class="cm-property">elements</span>.<span class="cm-property">name</span>.<span class="cm-property">form</span> <span class="cm-operator">==</span> <span class="cm-variable">form</span>);
<span class="cm-comment">// → true</span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_DOQDGp4ZWr" href="#p_DOQDGp4ZWr" tabindex="-1" role="presentation"></a>A button with a <code>type</code> attribute of <code>submit</code> will, when pressed, cause the form to be submitted. Pressing <span class="keyname">enter</span> when a form field is focused has the same effect.</p>
<p><a class="p_ident" id="p_MVbboPCoBM" href="#p_MVbboPCoBM" tabindex="-1" role="presentation"></a>Submitting a form normally means that the browser navigates to the page indicated by the form’s <code>action</code> attribute, using either a <code>GET</code> or a <code>POST</code> request. But before that happens, a <code>"submit"</code> event is fired. You can handle this event with JavaScript and prevent this default behavior by calling <code>preventDefault</code> on the event object.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_Zv/K0ruWJS" href="#c_Zv/K0ruWJS" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">form</span> <span class="cm-attribute">action</span>=<span class="cm-string">"example/submit.html"</span><span class="cm-tag cm-bracket">></span>
Value: <span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"value"</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">type</span>=<span class="cm-string">"submit"</span><span class="cm-tag cm-bracket">></span>Save<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">form</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">form</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"form"</span>);
<span class="cm-variable">form</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"submit"</span>, <span class="cm-def">event</span> <span class="cm-operator">=></span> {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Saving value"</span>, <span class="cm-variable">form</span>.<span class="cm-property">elements</span>.<span class="cm-property">value</span>.<span class="cm-property">value</span>);
<span class="cm-variable-2">event</span>.<span class="cm-property">preventDefault</span>();
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_wqAnsOYW3V" href="#p_wqAnsOYW3V" tabindex="-1" role="presentation"></a>Intercepting <code>"submit"</code> events in JavaScript has various uses. We can write code to verify that the values the user entered make sense and immediately show an error message instead of submitting the form. Or we can disable the regular way of submitting the form entirely, as in the example, and have our program handle the input, possibly using <code>fetch</code> to send it to a server without reloading the page.</p>
<h2><a class="h_ident" id="h_+RaBROT23F" href="#h_+RaBROT23F" tabindex="-1" role="presentation"></a>Text fields</h2>
<p><a class="p_ident" id="p_NENXbP9XTb" href="#p_NENXbP9XTb" tabindex="-1" role="presentation"></a>Fields created by <code><textarea></code> tags, or <code><input></code> tags with a type of <code>text</code> or <code>password</code>, share a common interface. Their DOM elements have a <code>value</code> property that holds their current content as a string value. Setting this property to another string changes the field’s content.</p>
<p><a class="p_ident" id="p_xQSknx93fe" href="#p_xQSknx93fe" tabindex="-1" role="presentation"></a>The <code>selectionStart</code> and <code>selectionEnd</code> properties of text fields give us information about the cursor and selection in the text. When nothing is selected, these two properties hold the same number, indicating the position of the cursor. For example, 0 indicates the start of the text, and 10 indicates the cursor is after the 10<sup>th</sup> character. When part of the field is selected, the two properties will differ, giving us the start and end of the selected text. Like <code>value</code>, these properties may also be written to.</p>
<p><a class="p_ident" id="p_VlvYL2VLoi" href="#p_VlvYL2VLoi" tabindex="-1" role="presentation"></a>Imagine you are writing an article about Khasekhemwy but have some trouble spelling his name. The following code wires up a <code><textarea></code> tag with an event handler that, when you press F2, inserts the string “Khasekhemwy” for you.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_bpWFxEi3zn" href="#c_bpWFxEi3zn" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">textarea</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"textarea"</span>);
<span class="cm-variable">textarea</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"keydown"</span>, <span class="cm-def">event</span> <span class="cm-operator">=></span> {
<span class="cm-comment">// The key code for F2 happens to be 113</span>
<span class="cm-keyword">if</span> (<span class="cm-variable-2">event</span>.<span class="cm-property">keyCode</span> <span class="cm-operator">==</span> <span class="cm-number">113</span>) {
<span class="cm-variable">replaceSelection</span>(<span class="cm-variable">textarea</span>, <span class="cm-string">"Khasekhemwy"</span>);
<span class="cm-variable-2">event</span>.<span class="cm-property">preventDefault</span>();
}
});
<span class="cm-keyword">function</span> <span class="cm-def">replaceSelection</span>(<span class="cm-def">field</span>, <span class="cm-def">word</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">from</span> <span class="cm-operator">=</span> <span class="cm-variable-2">field</span>.<span class="cm-property">selectionStart</span>, <span class="cm-def">to</span> <span class="cm-operator">=</span> <span class="cm-variable-2">field</span>.<span class="cm-property">selectionEnd</span>;
<span class="cm-variable-2">field</span>.<span class="cm-property">value</span> <span class="cm-operator">=</span> <span class="cm-variable-2">field</span>.<span class="cm-property">value</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-variable-2">from</span>) <span class="cm-operator">+</span> <span class="cm-variable-2">word</span> <span class="cm-operator">+</span>
<span class="cm-variable-2">field</span>.<span class="cm-property">value</span>.<span class="cm-property">slice</span>(<span class="cm-variable-2">to</span>);
<span class="cm-comment">// Put the cursor after the word</span>
<span class="cm-variable-2">field</span>.<span class="cm-property">selectionStart</span> <span class="cm-operator">=</span> <span class="cm-variable-2">from</span> <span class="cm-operator">+</span> <span class="cm-variable-2">word</span>.<span class="cm-property">length</span>;
<span class="cm-variable-2">field</span>.<span class="cm-property">selectionEnd</span> <span class="cm-operator">=</span> <span class="cm-variable-2">from</span> <span class="cm-operator">+</span> <span class="cm-variable-2">word</span>.<span class="cm-property">length</span>;
}
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_XRaVO9Iigu" href="#p_XRaVO9Iigu" tabindex="-1" role="presentation"></a>The <code>replaceSelection</code> function replaces the currently selected part of a text field’s content with the given word and then moves the cursor after that word so that the user can continue typing.</p>
<p><a class="p_ident" id="p_7ehU5cu5aF" href="#p_7ehU5cu5aF" tabindex="-1" role="presentation"></a>The <code>"change"</code> event for a text
field does not fire every time something is typed. Rather, it fires when the field loses focus after its content was changed. To respond immediately to changes in a text field, you should register a handler for the <code>"input"</code> event instead, which fires for every time the user types a character, deletes text, or otherwise manipulates the field’s content.</p>
<p><a class="p_ident" id="p_rladqIVDE4" href="#p_rladqIVDE4" tabindex="-1" role="presentation"></a>The following example shows a text field and a counter displaying the current length of the text in the field:</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_FW2nBbCoKe" href="#c_FW2nBbCoKe" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"text"</span><span class="cm-tag cm-bracket">></span> length: <span class="cm-tag cm-bracket"><</span><span class="cm-tag">span</span> <span class="cm-attribute">id</span>=<span class="cm-string">"length"</span><span class="cm-tag cm-bracket">></span>0<span class="cm-tag cm-bracket"></</span><span class="cm-tag">span</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">text</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"input"</span>);
<span class="cm-keyword">let</span> <span class="cm-def">output</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"#length"</span>);
<span class="cm-variable">text</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"input"</span>, () <span class="cm-operator">=></span> {
<span class="cm-variable">output</span>.<span class="cm-property">textContent</span> <span class="cm-operator">=</span> <span class="cm-variable">text</span>.<span class="cm-property">value</span>.<span class="cm-property">length</span>;
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<h2><a class="h_ident" id="h_axUK+XNvTN" href="#h_axUK+XNvTN" tabindex="-1" role="presentation"></a>Checkboxes and radio buttons</h2>
<p><a class="p_ident" id="p_DFZwKUx9E+" href="#p_DFZwKUx9E+" tabindex="-1" role="presentation"></a>A checkbox field is a binary toggle. Its value can be extracted or changed through its <code>checked</code> property, which holds a Boolean value.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_QDNdcETI4b" href="#c_QDNdcETI4b" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"checkbox"</span> <span class="cm-attribute">id</span>=<span class="cm-string">"purple"</span><span class="cm-tag cm-bracket">></span> Make this page purple
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">checkbox</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"#purple"</span>);
<span class="cm-variable">checkbox</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-variable">document</span>.<span class="cm-property">body</span>.<span class="cm-property">style</span>.<span class="cm-property">background</span> <span class="cm-operator">=</span>
<span class="cm-variable">checkbox</span>.<span class="cm-property">checked</span> <span class="cm-operator">?</span> <span class="cm-string">"mediumpurple"</span> : <span class="cm-string">""</span>;
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_kQbNxPLuR2" href="#p_kQbNxPLuR2" tabindex="-1" role="presentation"></a>The <code><label></code> tag associates a piece of document with an input field. Clicking anywhere on the label will activate the field, which focuses it and toggles its value when it is a checkbox or radio button.</p>
<p><a class="p_ident" id="p_vNsiBxZlre" href="#p_vNsiBxZlre" tabindex="-1" role="presentation"></a>A radio button is similar to a checkbox, but it’s implicitly linked to other radio buttons with the same <code>name</code> attribute so that only one of them can be active at any time.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_tM2CEiReVh" href="#c_tM2CEiReVh" tabindex="-1" role="presentation"></a>Color:
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"radio"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"color"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"orange"</span><span class="cm-tag cm-bracket">></span> Orange
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"radio"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"color"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"lightgreen"</span><span class="cm-tag cm-bracket">></span> Green
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"radio"</span> <span class="cm-attribute">name</span>=<span class="cm-string">"color"</span> <span class="cm-attribute">value</span>=<span class="cm-string">"lightblue"</span><span class="cm-tag cm-bracket">></span> Blue
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">label</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">buttons</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelectorAll</span>(<span class="cm-string">"[name=color]"</span>);
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">button</span> <span class="cm-keyword">of</span> <span class="cm-variable">Array</span>.<span class="cm-property">from</span>(<span class="cm-variable">buttons</span>)) {
<span class="cm-variable">button</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-variable">document</span>.<span class="cm-property">body</span>.<span class="cm-property">style</span>.<span class="cm-property">background</span> <span class="cm-operator">=</span> <span class="cm-variable">button</span>.<span class="cm-property">value</span>;
});
}
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_OM3AMgKt0y" href="#p_OM3AMgKt0y" tabindex="-1" role="presentation"></a>The square brackets in the CSS query given to <code>querySelectorAll</code> are used to match attributes. It selects elements whose <code>name</code> attribute is <code>"color"</code>.</p>
<h2><a class="h_ident" id="h_eaB6RprDK3" href="#h_eaB6RprDK3" tabindex="-1" role="presentation"></a>Select fields</h2>
<p><a class="p_ident" id="p_C43QMBKrcK" href="#p_C43QMBKrcK" tabindex="-1" role="presentation"></a>Select fields are conceptually similar to radio buttons—they also allow the user to choose from a set of options. But where a radio button puts the layout of the options under our control, the appearance of a <code><select></code> tag is determined by the browser.</p>
<p><a class="p_ident" id="p_cSTgnCzv3c" href="#p_cSTgnCzv3c" tabindex="-1" role="presentation"></a>Select fields also have a variant that is more akin to a list of checkboxes, rather than radio boxes. When given the <code>multiple</code> attribute, a <code><select></code> tag will allow the user to select any number of options, rather than just a single option. This will, in most browsers, show up differently than a normal select field, which is typically drawn as a <em>drop-down</em> control that shows the options only when you open it.</p>
<p><a class="p_ident" id="p_D7R79xBFg4" href="#p_D7R79xBFg4" tabindex="-1" role="presentation"></a>Each <code><option></code> tag has a value. This value can be defined with a <code>value</code> attribute. When that is not given, the text inside the option will count as its value. The <code>value</code> property of a <code><select></code> element reflects the currently selected option. For a <code>multiple</code> field, though, this property doesn’t mean much since it will give the value of only <em>one</em> of the currently selected options.</p>
<p><a class="p_ident" id="p_cuEVUjcKsy" href="#p_cuEVUjcKsy" tabindex="-1" role="presentation"></a>The <code><option></code> tags for a <code><select></code> field can be accessed as an array-like object through the field’s <code>options</code> property. Each option has a property called <code>selected</code>, which indicates whether that option is currently selected. The property can also be written to select or deselect an option.</p>
<p><a class="p_ident" id="p_MaAZPlhgSY" href="#p_MaAZPlhgSY" tabindex="-1" role="presentation"></a>This example extracts the selected values from a <code>multiple</code> select field and uses them to compose a binary number from individual bits. Hold <span class="keyname">control</span> (or <span class="keyname">command</span> on a Mac) to select multiple options.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_Jh/nb6UYLR" href="#c_Jh/nb6UYLR" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">select</span> <span class="cm-attribute">multiple</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span> <span class="cm-attribute">value</span>=<span class="cm-string">"1"</span><span class="cm-tag cm-bracket">></span>0001<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span> <span class="cm-attribute">value</span>=<span class="cm-string">"2"</span><span class="cm-tag cm-bracket">></span>0010<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span> <span class="cm-attribute">value</span>=<span class="cm-string">"4"</span><span class="cm-tag cm-bracket">></span>0100<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">option</span> <span class="cm-attribute">value</span>=<span class="cm-string">"8"</span><span class="cm-tag cm-bracket">></span>1000<span class="cm-tag cm-bracket"></</span><span class="cm-tag">option</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">select</span><span class="cm-tag cm-bracket">></span> = <span class="cm-tag cm-bracket"><</span><span class="cm-tag">span</span> <span class="cm-attribute">id</span>=<span class="cm-string">"output"</span><span class="cm-tag cm-bracket">></span>0<span class="cm-tag cm-bracket"></</span><span class="cm-tag">span</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">select</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"select"</span>);
<span class="cm-keyword">let</span> <span class="cm-def">output</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"#output"</span>);
<span class="cm-variable">select</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-keyword">let</span> <span class="cm-def">number</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">option</span> <span class="cm-keyword">of</span> <span class="cm-variable">Array</span>.<span class="cm-property">from</span>(<span class="cm-variable">select</span>.<span class="cm-property">options</span>)) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">option</span>.<span class="cm-property">selected</span>) {
<span class="cm-variable-2">number</span> <span class="cm-operator">+=</span> <span class="cm-variable">Number</span>(<span class="cm-variable-2">option</span>.<span class="cm-property">value</span>);
}
}
<span class="cm-variable">output</span>.<span class="cm-property">textContent</span> <span class="cm-operator">=</span> <span class="cm-variable-2">number</span>;
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<h2><a class="h_ident" id="h_tK84z183/8" href="#h_tK84z183/8" tabindex="-1" role="presentation"></a>File fields</h2>
<p><a class="p_ident" id="p_12DuX873Jk" href="#p_12DuX873Jk" tabindex="-1" role="presentation"></a>File fields were originally designed as a way to upload files from the user’s machine through a form. In modern browsers, they also provide a way to read such files from JavaScript programs. The field acts as a kind of gatekeeper. The script cannot simply start reading private files from the user’s computer, but if the user selects a file in such a field, the browser interprets that action to mean that the script may read the file.</p>
<p><a class="p_ident" id="p_nfUpEs7Vxe" href="#p_nfUpEs7Vxe" tabindex="-1" role="presentation"></a>A file field usually looks like a button labeled with something like “choose file” or “browse”, with information about the chosen file next to it.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_Gg47yko2dF" href="#c_Gg47yko2dF" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"file"</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">input</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"input"</span>);
<span class="cm-variable">input</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-keyword">if</span> (<span class="cm-variable">input</span>.<span class="cm-property">files</span>.<span class="cm-property">length</span> <span class="cm-operator">></span> <span class="cm-number">0</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">file</span> <span class="cm-operator">=</span> <span class="cm-variable">input</span>.<span class="cm-property">files</span>[<span class="cm-number">0</span>];
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"You chose"</span>, <span class="cm-variable-2">file</span>.<span class="cm-property">name</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">file</span>.<span class="cm-property">type</span>) <span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"It has type"</span>, <span class="cm-variable-2">file</span>.<span class="cm-property">type</span>);
}
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_9WVMeVLeav" href="#p_9WVMeVLeav" tabindex="-1" role="presentation"></a>The <code>files</code> property of a file field element is an array-like object (again, not a real array) containing the files chosen in the field. It is initially empty. The reason there isn’t simply a <code>file</code> property is that file fields also support a <code>multiple</code> attribute, which makes it possible to select multiple files at the same time.</p>
<p><a class="p_ident" id="p_yUTGY9XA00" href="#p_yUTGY9XA00" tabindex="-1" role="presentation"></a>Objects in the <code>files</code> object have properties such as <code>name</code> (the filename), <code>size</code> (the file’s size in bytes, which are chunks of 8 bits), and <code>type</code> (the media type of the file, such as <code>text/plain</code> or <code>image/jpeg</code>).</p>
<p id="filereader"><a class="p_ident" id="p_BUCcjCybzf" href="#p_BUCcjCybzf" tabindex="-1" role="presentation"></a>What it does not have is a property that contains the content of the file. Getting at that is a little more involved. Since reading a file from disk can take time, the interface must be asynchronous to avoid freezing the document.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_NWBXf4dpgg" href="#c_NWBXf4dpgg" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">input</span> <span class="cm-attribute">type</span>=<span class="cm-string">"file"</span> <span class="cm-attribute">multiple</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">input</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"input"</span>);
<span class="cm-variable">input</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">file</span> <span class="cm-keyword">of</span> <span class="cm-variable">Array</span>.<span class="cm-property">from</span>(<span class="cm-variable">input</span>.<span class="cm-property">files</span>)) {
<span class="cm-keyword">let</span> <span class="cm-def">reader</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">FileReader</span>();
<span class="cm-variable-2">reader</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"load"</span>, () <span class="cm-operator">=></span> {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"File"</span>, <span class="cm-variable-2">file</span>.<span class="cm-property">name</span>, <span class="cm-string">"starts with"</span>,
<span class="cm-variable-2">reader</span>.<span class="cm-property">result</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-number">20</span>));
});
<span class="cm-variable-2">reader</span>.<span class="cm-property">readAsText</span>(<span class="cm-variable-2">file</span>);
}
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_WTVG7dhgkK" href="#p_WTVG7dhgkK" tabindex="-1" role="presentation"></a>Reading a file is done by creating a <code>FileReader</code> object, registering a <code>"load"</code> event handler for it, and calling its <code>readAsText</code> method, giving it the file we want to read. Once loading finishes, the reader’s <code>result</code> property contains the file’s content.</p>
<p><a class="p_ident" id="p_K4QhByVIWK" href="#p_K4QhByVIWK" tabindex="-1" role="presentation"></a><code>FileReader</code>s also fire an <code>"error"</code> event when reading the file fails for any reason. The error object itself will end up in the reader’s <code>error</code> property. This interface was designed before promises became part of the language. You could wrap it in a promise like this:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Kr3V9NFjD7" href="#c_Kr3V9NFjD7" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">readFileText</span>(<span class="cm-def">file</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">Promise</span>((<span class="cm-def">resolve</span>, <span class="cm-def">reject</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">let</span> <span class="cm-def">reader</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">FileReader</span>();
<span class="cm-variable-2">reader</span>.<span class="cm-property">addEventListener</span>(
<span class="cm-string">"load"</span>, () <span class="cm-operator">=></span> <span class="cm-variable-2">resolve</span>(<span class="cm-variable-2">reader</span>.<span class="cm-property">result</span>));
<span class="cm-variable-2">reader</span>.<span class="cm-property">addEventListener</span>(
<span class="cm-string">"error"</span>, () <span class="cm-operator">=></span> <span class="cm-variable-2">reject</span>(<span class="cm-variable-2">reader</span>.<span class="cm-property">error</span>));
<span class="cm-variable-2">reader</span>.<span class="cm-property">readAsText</span>(<span class="cm-variable-2">file</span>);
});
}</pre>
<h2><a class="h_ident" id="h_xMhbz7W4BY" href="#h_xMhbz7W4BY" tabindex="-1" role="presentation"></a>Storing data client-side</h2>
<p><a class="p_ident" id="p_JABB1DfeON" href="#p_JABB1DfeON" tabindex="-1" role="presentation"></a>Simple HTML pages with a bit of JavaScript can be a great format for “mini applications”—small helper programs that automate basic tasks. By connecting a few form fields with event handlers, you can do anything from converting between centimeters and inches to computing passwords from a master password and a website name.</p>
<p><a class="p_ident" id="p_ZDof7+yfRJ" href="#p_ZDof7+yfRJ" tabindex="-1" role="presentation"></a>When such an application needs to remember something between sessions, you cannot use JavaScript bindings—those are thrown away every time the page is closed. You could set up a server, connect it to the Internet, and have your application store something there. We will see how to do that in <a href="20_node.html">Chapter 20</a>. But that’s a lot of extra work and complexity. Sometimes it is enough to just keep the data in the browser.</p>
<p><a class="p_ident" id="p_tijRqdmE+T" href="#p_tijRqdmE+T" tabindex="-1" role="presentation"></a>The <code>localStorage</code> object can be used to store data in a way that survives page reloads. This object allows you to file string values under names.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_zS9vKuxYED" href="#c_zS9vKuxYED" tabindex="-1" role="presentation"></a><span class="cm-variable">localStorage</span>.<span class="cm-property">setItem</span>(<span class="cm-string">"username"</span>, <span class="cm-string">"marijn"</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">localStorage</span>.<span class="cm-property">getItem</span>(<span class="cm-string">"username"</span>));
<span class="cm-comment">// → marijn</span>
<span class="cm-variable">localStorage</span>.<span class="cm-property">removeItem</span>(<span class="cm-string">"username"</span>);</pre>
<p><a class="p_ident" id="p_6Jr54na1O5" href="#p_6Jr54na1O5" tabindex="-1" role="presentation"></a>A value in <code>localStorage</code> sticks around until it is overwritten, it is removed with <code>removeItem</code>, or the user clears their local data.</p>
<p><a class="p_ident" id="p_rQBn/5RRw1" href="#p_rQBn/5RRw1" tabindex="-1" role="presentation"></a>Sites from different domains get different storage compartments. That means data stored in <code>localStorage</code> by a given website can, in principle, be read (and overwritten) only by scripts on that same site.</p>
<p><a class="p_ident" id="p_QOv0pecyix" href="#p_QOv0pecyix" tabindex="-1" role="presentation"></a>Browsers do enforce a limit on the size of the data a site can store in <code>localStorage</code>. That restriction, along with the fact that filling up people’s hard drives with junk is not really profitable, prevents the feature from eating up too much space.</p>
<p><a class="p_ident" id="p_nOUdqdshUV" href="#p_nOUdqdshUV" tabindex="-1" role="presentation"></a>The following code implements a crude note-taking application. It keeps a set of named notes and allows the user to edit notes and create new ones.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_7EHyh6Vlvw" href="#c_7EHyh6Vlvw" tabindex="-1" role="presentation"></a>Notes: <span class="cm-tag cm-bracket"><</span><span class="cm-tag">select</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">select</span><span class="cm-tag cm-bracket">></span> <span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>Add<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"><</span><span class="cm-tag">br</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">textarea</span> <span class="cm-attribute">style</span>=<span class="cm-string">"width: 100%"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-keyword">let</span> <span class="cm-def">list</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"select"</span>);
<span class="cm-keyword">let</span> <span class="cm-def">note</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"textarea"</span>);
<span class="cm-keyword">let</span> <span class="cm-def">state</span>;
<span class="cm-keyword">function</span> <span class="cm-def">setState</span>(<span class="cm-def">newState</span>) {
<span class="cm-variable">list</span>.<span class="cm-property">textContent</span> <span class="cm-operator">=</span> <span class="cm-string">""</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">name</span> <span class="cm-keyword">of</span> <span class="cm-variable">Object</span>.<span class="cm-property">keys</span>(<span class="cm-variable-2">newState</span>.<span class="cm-property">notes</span>)) {
<span class="cm-keyword">let</span> <span class="cm-def">option</span> <span class="cm-operator">=</span> <span class="cm-variable">document</span>.<span class="cm-property">createElement</span>(<span class="cm-string">"option"</span>);
<span class="cm-variable-2">option</span>.<span class="cm-property">textContent</span> <span class="cm-operator">=</span> <span class="cm-variable-2">name</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable-2">newState</span>.<span class="cm-property">selected</span> <span class="cm-operator">==</span> <span class="cm-variable-2">name</span>) <span class="cm-variable-2">option</span>.<span class="cm-property">selected</span> <span class="cm-operator">=</span> <span class="cm-atom">true</span>;
<span class="cm-variable">list</span>.<span class="cm-property">appendChild</span>(<span class="cm-variable-2">option</span>);
}
<span class="cm-variable">note</span>.<span class="cm-property">value</span> <span class="cm-operator">=</span> <span class="cm-variable-2">newState</span>.<span class="cm-property">notes</span>[<span class="cm-variable-2">newState</span>.<span class="cm-property">selected</span>];
<span class="cm-variable">localStorage</span>.<span class="cm-property">setItem</span>(<span class="cm-string">"Notes"</span>, <span class="cm-variable">JSON</span>.<span class="cm-property">stringify</span>(<span class="cm-variable-2">newState</span>));
<span class="cm-variable">state</span> <span class="cm-operator">=</span> <span class="cm-variable-2">newState</span>;
}
<span class="cm-variable">setState</span>(<span class="cm-variable">JSON</span>.<span class="cm-property">parse</span>(<span class="cm-variable">localStorage</span>.<span class="cm-property">getItem</span>(<span class="cm-string">"Notes"</span>)) <span class="cm-operator">|</span><span class="cm-operator">|</span> {
<span class="cm-property">notes</span>: {<span class="cm-string cm-property">"shopping list"</span>: <span class="cm-string">"Carrots\nRaisins"</span>},
<span class="cm-property">selected</span>: <span class="cm-string">"shopping list"</span>
});
<span class="cm-variable">list</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-variable">setState</span>({<span class="cm-property">notes</span>: <span class="cm-variable">state</span>.<span class="cm-property">notes</span>, <span class="cm-property">selected</span>: <span class="cm-variable">list</span>.<span class="cm-property">value</span>});
});
<span class="cm-variable">note</span>.<span class="cm-property">addEventListener</span>(<span class="cm-string">"change"</span>, () <span class="cm-operator">=></span> {
<span class="cm-variable">setState</span>({
<span class="cm-property">notes</span>: <span class="cm-variable">Object</span>.<span class="cm-property">assign</span>({}, <span class="cm-variable">state</span>.<span class="cm-property">notes</span>,
{[<span class="cm-variable">state</span>.<span class="cm-property">selected</span>]: <span class="cm-variable">note</span>.<span class="cm-property">value</span>}),
<span class="cm-property">selected</span>: <span class="cm-variable">state</span>.<span class="cm-property">selected</span>
});
});
<span class="cm-variable">document</span>.<span class="cm-property">querySelector</span>(<span class="cm-string">"button"</span>)
.<span class="cm-property">addEventListener</span>(<span class="cm-string">"click"</span>, () <span class="cm-operator">=></span> {
<span class="cm-keyword">let</span> <span class="cm-def">name</span> <span class="cm-operator">=</span> <span class="cm-variable">prompt</span>(<span class="cm-string">"Note name"</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">name</span>) <span class="cm-variable">setState</span>({
<span class="cm-property">notes</span>: <span class="cm-variable">Object</span>.<span class="cm-property">assign</span>({}, <span class="cm-variable">state</span>.<span class="cm-property">notes</span>, {[<span class="cm-variable-2">name</span>]: <span class="cm-string">""</span>}),
<span class="cm-property">selected</span>: <span class="cm-variable-2">name</span>
});
});
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<p><a class="p_ident" id="p_KKRjPQnlpK" href="#p_KKRjPQnlpK" tabindex="-1" role="presentation"></a>The script gets its starting state from the <code>"Notes"</code> value stored in <code>localStorage</code> or, if that is missing, creates an example state that has only a shopping list in it. Reading a field that does not exist from <code>localStorage</code> will yield <code>null</code>. Passing <code>null</code> to <code>JSON.parse</code> will make it parse the string <code>"null"</code> and return <code>null</code>. Thus, the <code>||</code> operator can be used to provide a default value in a situation like this.</p>
<p><a class="p_ident" id="p_vsgpRLsWlg" href="#p_vsgpRLsWlg" tabindex="-1" role="presentation"></a>The <code>setState</code> method makes sure the DOM is showing a given state and stores the new state to <code>localStorage</code>. Event handlers call this function to move to a new state.</p>
<p><a class="p_ident" id="p_KLQOhbE5S6" href="#p_KLQOhbE5S6" tabindex="-1" role="presentation"></a>The use of <code>Object.assign</code> in the example is intended to create a new object that is a clone of the old <code>state.notes</code>, but with one property added or overwritten. <code>Object.assign</code> takes its first argument and adds all properties from any further arguments to it. Thus, giving it an empty object will cause it to fill a fresh object. The square
brackets notation in the third argument is used to create a property whose name is based on some dynamic value.</p>
<p><a class="p_ident" id="p_McB+3/vKwy" href="#p_McB+3/vKwy" tabindex="-1" role="presentation"></a>There is another object, similar to <code>localStorage</code>, called <code>sessionStorage</code>. The difference between the two is that the content of <code>sessionStorage</code> is forgotten at the end of each <em>session</em>, which for most browsers means whenever the browser is closed.</p>
<h2><a class="h_ident" id="h_ErccPg/l98" href="#h_ErccPg/l98" tabindex="-1" role="presentation"></a>Summary</h2>
<p><a class="p_ident" id="p_1249Ox6nXm" href="#p_1249Ox6nXm" tabindex="-1" role="presentation"></a>In this chapter, we discussed how the HTTP protocol works. A <em>client</em> sends a request, which contains a method (usually <code>GET</code>) and a path that identifies a resource. The <em>server</em> then decides what to do with the request and responds with a status code and a response body. Both requests and responses may contain headers that provide additional information.</p>
<p><a class="p_ident" id="p_taYkCAtnud" href="#p_taYkCAtnud" tabindex="-1" role="presentation"></a>The interface through which browser JavaScript can make HTTP requests is called <code>fetch</code>. Making a request looks like this:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_I5lSLBiG+b" href="#c_I5lSLBiG+b" tabindex="-1" role="presentation"></a><span class="cm-variable">fetch</span>(<span class="cm-string">"/18_http.html"</span>).<span class="cm-property">then</span>(<span class="cm-def">r</span> <span class="cm-operator">=></span> <span class="cm-variable-2">r</span>.<span class="cm-property">text</span>()).<span class="cm-property">then</span>(<span class="cm-def">text</span> <span class="cm-operator">=></span> {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string-2">`The page starts with ${</span><span class="cm-variable-2">text</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-number">15</span>)<span class="cm-string-2">}</span><span class="cm-string-2">`</span>);
});</pre>
<p><a class="p_ident" id="p_V30s3OVzdK" href="#p_V30s3OVzdK" tabindex="-1" role="presentation"></a>Browsers make <code>GET</code> requests to fetch the resources needed to display a web page. A page may also contain forms, which allow information entered by the user to be sent as a request for a new page when the form is submitted.</p>
<p><a class="p_ident" id="p_QjxVhJesQe" href="#p_QjxVhJesQe" tabindex="-1" role="presentation"></a>HTML can represent various types of form fields, such as text fields, checkboxes, multiple-choice fields, and file pickers.</p>
<p><a class="p_ident" id="p_RrO1r6Pyin" href="#p_RrO1r6Pyin" tabindex="-1" role="presentation"></a>Such fields can be inspected and manipulated with JavaScript. They fire the <code>"change"</code> event when changed, fire the <code>"input"</code> event when text is typed, and receive keyboard events when they have keyboard focus. Properties like <code>value</code> (for text and select fields) or <code>checked</code> (for checkboxes and radio buttons) are used to read or set the field’s content.</p>
<p><a class="p_ident" id="p_SD8tK1CyB9" href="#p_SD8tK1CyB9" tabindex="-1" role="presentation"></a>When a form is submitted, a <code>"submit"</code> event is fired on it. A JavaScript handler can call <code>preventDefault</code> on that event to disable the browser’s default behavior. Form field elements may also occur outside of a form tag.</p>
<p><a class="p_ident" id="p_4GN43j/R8o" href="#p_4GN43j/R8o" tabindex="-1" role="presentation"></a>When the user has selected a file from their local file system in a file picker field, the <code>FileReader</code> interface can be used to access the content of this file from a JavaScript program.</p>
<p><a class="p_ident" id="p_UfsY7mgHDE" href="#p_UfsY7mgHDE" tabindex="-1" role="presentation"></a>The <code>localStorage</code> and <code>sessionStorage</code> objects can be used to save information in a way that survives page reloads. The first object saves the data forever (or until the user decides to clear it), and the second saves it until the browser is closed.</p>
<h2><a class="h_ident" id="h_TcUD2vzyMe" href="#h_TcUD2vzyMe" tabindex="-1" role="presentation"></a>Exercises</h2>
<h3><a class="i_ident" id="i_uaWwL8WGXf" href="#i_uaWwL8WGXf" tabindex="-1" role="presentation"></a>Content negotiation</h3>
<p><a class="p_ident" id="p_4RSIQjkFSG" href="#p_4RSIQjkFSG" tabindex="-1" role="presentation"></a>One of the things HTTP can do is called <em>content negotiation</em>. The <code>Accept</code> request header is used to tell the server what type of document the client would like to get. Many servers ignore this header, but when a server knows of various ways to encode a resource, it can look at this header and send the one that the client prefers.</p>
<p><a class="p_ident" id="p_cYtib3gEMB" href="#p_cYtib3gEMB" tabindex="-1" role="presentation"></a>The URL <a href="https://eloquentjavascript.net/author"><em>https://eloquentjavascript.net/author</em></a> is configured to respond with either plaintext, HTML, or JSON, depending on what the client asks for. These formats are identified by the standardized <em>media types</em> <code>text/plain</code>, <code>text/html</code>, and <code>application/json</code>.</p>
<p><a class="p_ident" id="p_8+gmMBG1zE" href="#p_8+gmMBG1zE" tabindex="-1" role="presentation"></a>Send requests to fetch all three formats of this resource. Use the <code>headers</code> property in the options object passed to <code>fetch</code> to set the header named <code>Accept</code> to the desired media type.</p>
<p><a class="p_ident" id="p_DGQ35JK0dT" href="#p_DGQ35JK0dT" tabindex="-1" role="presentation"></a>Finally, try asking for the media type <code>application/<wbr>rainbows+unicorns</code> and see which status code that produces.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_HRKSrZS1tJ" href="#c_HRKSrZS1tJ" tabindex="-1" role="presentation"></a><span class="cm-comment">// Your code here.</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_QQMLShvZ/N" href="#p_QQMLShvZ/N" tabindex="-1" role="presentation"></a>Base your code on the <code>fetch</code> examples <a href="18_http.html#fetch">earlier in the chapter</a>.</p>
<p><a class="p_ident" id="p_U/l3HWMtEN" href="#p_U/l3HWMtEN" tabindex="-1" role="presentation"></a>Asking for a bogus media type will return a response with code 406, “Not acceptable”, which is the code a server should return when it can’t fulfill the <code>Accept</code> header.</p>
</div></div>
<h3><a class="i_ident" id="i_wTXvIH5Wds" href="#i_wTXvIH5Wds" tabindex="-1" role="presentation"></a>A JavaScript workbench</h3>
<p><a class="p_ident" id="p_b4iA8hbDyH" href="#p_b4iA8hbDyH" tabindex="-1" role="presentation"></a>Build an interface that allows people to type and run pieces of JavaScript code.</p>
<p><a class="p_ident" id="p_5ABzoaFbF8" href="#p_5ABzoaFbF8" tabindex="-1" role="presentation"></a>Put a button next to a <code><textarea></code> field that, when pressed, uses the <code>Function</code> constructor we saw in <a href="10_modules.html#eval">Chapter 10</a> to wrap the text in a function and call it. Convert the return value of the function, or any error it raises, to a string and display it below the text field.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_zdElSW9Q47" href="#c_zdElSW9Q47" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">textarea</span> <span class="cm-attribute">id</span>=<span class="cm-string">"code"</span><span class="cm-tag cm-bracket">></span>return "hi";<span class="cm-tag cm-bracket"></</span><span class="cm-tag">textarea</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">id</span>=<span class="cm-string">"button"</span><span class="cm-tag cm-bracket">></span>Run<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">pre</span> <span class="cm-attribute">id</span>=<span class="cm-string">"output"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">pre</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-comment">// Your code here.</span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_FntbF4i9OW" href="#p_FntbF4i9OW" tabindex="-1" role="presentation"></a>Use <code>document.<wbr>querySelector</code> or <code>document.<wbr>getElementById</code> to get access to the elements defined in your HTML. An event handler for <code>"click"</code> or <code>"mousedown"</code> events on the button can get the <code>value</code> property of the text field and call <code>Function</code> on it.</p>
<p><a class="p_ident" id="p_uLWfzgaSrI" href="#p_uLWfzgaSrI" tabindex="-1" role="presentation"></a>Make sure you wrap both the call to <code>Function</code> and the call to its result in a <code>try</code> block so you can catch the exceptions it produces. In this case, we really don’t know what type of exception we are looking for, so catch everything.</p>
<p><a class="p_ident" id="p_J8bbt63whH" href="#p_J8bbt63whH" tabindex="-1" role="presentation"></a>The <code>textContent</code> property of the output element can be used to fill it with a string message. Or, if you want to keep the old content around, create a new text node using <code>document.<wbr>createTextNode</code> and append it to the element. Remember to add a newline character to the end so that not all output appears on a single line.</p>
</div></div>
<h3><a class="i_ident" id="i_XyKQVmCbTN" href="#i_XyKQVmCbTN" tabindex="-1" role="presentation"></a>Conway’s Game of Life</h3>
<p><a class="p_ident" id="p_5s3eB2ZhzK" href="#p_5s3eB2ZhzK" tabindex="-1" role="presentation"></a>Conway’s Game of Life is a simple simulation that creates artificial “life” on a grid, each cell of which is either alive or not. Each generation (turn), the following rules are applied:</p>
<ul>
<li>
<p><a class="p_ident" id="p_D7IMqD7kgE" href="#p_D7IMqD7kgE" tabindex="-1" role="presentation"></a>Any live cell with fewer than two or more than three live neighbors dies.</p></li>
<li>
<p><a class="p_ident" id="p_ztkCIOYDVq" href="#p_ztkCIOYDVq" tabindex="-1" role="presentation"></a>Any live cell with two or three live neighbors lives on to the next generation.</p></li>
<li>
<p><a class="p_ident" id="p_y/DnAd+/CJ" href="#p_y/DnAd+/CJ" tabindex="-1" role="presentation"></a>Any dead cell with exactly three live neighbors becomes a live cell.</p></li></ul>
<p><a class="p_ident" id="p_iUPnWf2p1M" href="#p_iUPnWf2p1M" tabindex="-1" role="presentation"></a>A <em>neighbor</em> is defined as any adjacent cell, including diagonally adjacent ones.</p>
<p><a class="p_ident" id="p_9dLS2RK5SZ" href="#p_9dLS2RK5SZ" tabindex="-1" role="presentation"></a>Note that these rules are applied to the whole grid at once, not one square at a time. That means the counting of neighbors is based on the situation at the start of the generation, and changes happening to neighbor cells during this generation should not influence the new state of a given cell.</p>
<p><a class="p_ident" id="p_W0m8oVpi7M" href="#p_W0m8oVpi7M" tabindex="-1" role="presentation"></a>Implement this game using whichever data structure you find appropriate. Use <code>Math.random</code> to populate the grid with a random pattern initially. Display it as a grid of checkbox fields, with a button next to it to advance to the next generation. When the user checks or unchecks the checkboxes, their changes should be included when computing the next generation.</p>
<pre class="snippet cm-s-default" data-language="text/html" ><a class="c_ident" id="c_xF6LIoITNO" href="#c_xF6LIoITNO" tabindex="-1" role="presentation"></a><span class="cm-tag cm-bracket"><</span><span class="cm-tag">div</span> <span class="cm-attribute">id</span>=<span class="cm-string">"grid"</span><span class="cm-tag cm-bracket">></span><span class="cm-tag cm-bracket"></</span><span class="cm-tag">div</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">button</span> <span class="cm-attribute">id</span>=<span class="cm-string">"next"</span><span class="cm-tag cm-bracket">></span>Next generation<span class="cm-tag cm-bracket"></</span><span class="cm-tag">button</span><span class="cm-tag cm-bracket">></span>
<span class="cm-tag cm-bracket"><</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span>
<span class="cm-comment">// Your code here.</span>
<span class="cm-tag cm-bracket"></</span><span class="cm-tag">script</span><span class="cm-tag cm-bracket">></span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_Aww6OjjuYz" href="#p_Aww6OjjuYz" tabindex="-1" role="presentation"></a>To solve the problem of having the changes conceptually happen at the same time, try to see the computation of a generation as a pure
function, which takes one grid and produces a new grid that represents the next turn.</p>
<p><a class="p_ident" id="p_DBZ6s168gb" href="#p_DBZ6s168gb" tabindex="-1" role="presentation"></a>Representing the matrix can be done in the way shown in <a href="06_object.html#matrix">Chapter 6</a>. You can count live neighbors with two nested loops, looping over adjacent coordinates in both dimensions. Take care not to count cells outside of the field and to ignore the cell in the center, whose neighbors we are counting.</p>
<p><a class="p_ident" id="p_Jyqyj//gTI" href="#p_Jyqyj//gTI" tabindex="-1" role="presentation"></a>Ensuring that changes to checkboxes take effect on the next generation can be done in two ways. An event handler could notice these changes and update the current grid to reflect them, or you could generate a fresh grid from the values in the checkboxes before computing the next turn.</p>
<p><a class="p_ident" id="p_wu3Ty9I4d4" href="#p_wu3Ty9I4d4" tabindex="-1" role="presentation"></a>If you choose to go with event handlers, you might want to attach attributes that identify the position that each checkbox corresponds to so that it is easy to find out which cell to change.</p>
<p><a class="p_ident" id="p_XFp+gOIONt" href="#p_XFp+gOIONt" tabindex="-1" role="presentation"></a>To draw the grid of checkboxes, you can either use a <code><table></code> element (see <a href="14_dom.html#exercise_table">Chapter 14</a>) or simply put them all in the same element and put <code><br></code> (line break) elements between the rows.</p>
</div></div><nav><a href="17_canvas.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a> <a href="19_paint.html" title="next chapter">▶</a></nav>
</article>