4
4
< meta charset ="utf-8 ">
5
5
< script >
6
6
// TODO: create a handler
7
- window . addEventListener ( "load" , function ( ) {
8
- // TODO: register the handler
9
- } ) ;
7
+ function setSearchEngine ( ) {
8
+
9
+ let actions = {
10
+ "google" :"https://www.google.com/search" ,
11
+ "duckDuckGo" :"https://duckduckgo.com/" ,
12
+ "bing" :"https://www.bing.com/search" ,
13
+ "ask" :"https://www.ask.com/web"
14
+ } ;
15
+
16
+ let form = document . getElementById ( 'searchForm' ) ;
17
+ let searchTerm = document . querySelector ( "input[name=q]" ) . value ;
18
+
19
+ if ( searchTerm . trim ( ) === "" ) {
20
+ event . preventDefault ( ) ;
21
+ alert ( "Please enter a search term" ) ;
22
+ return ;
23
+ }
24
+
25
+ let selecetedEngine = document . querySelector ( 'input[name=engine]:checked' ) ;
26
+
27
+ if ( selectedEngine === null ) {
28
+ event . preventDefault ( ) ;
29
+ alert ( 'Invalid search engine selection' ) ;
30
+ return ;
31
+ }
32
+
33
+ let action = actions [ selecetedEngine . value ] ;
34
+
35
+ if ( action === undefined ) {
36
+ event . preventDefault ( ) ;
37
+ alert ( 'Invalid search engine selection' ) ;
38
+ return ;
39
+ }
40
+
41
+ form . setAttribute ( 'action' , action ) ;
42
+ }
43
+
44
+ window . addEventListener ( 'load' , function ( ) {
45
+ // TODO: register the handler
46
+ let form = document . getElementById ( 'searchForm' ) ;
47
+ form . addEventListener ( 'submit' , setSearchEngine ) ;
48
+
49
+ } ) ;
50
+
51
+
52
+
10
53
</ script >
11
54
</ head >
12
55
13
56
< body >
14
57
15
- < form id ="searchForm ">
16
- <!-- TODO: add form elements -->
58
+ < form id ='searchForm '>
59
+ <!-- TODO: add form elements -->
60
+ < input type ="text " name ="q ">
61
+ < label > Google< input type ="radio " name ="engine " value ="google "> </ label >
62
+ < label > DuckDuckGo< input type ="radio " name ="engine " value ="duckDuckgo "> </ label >
63
+ < label > Bing< input type ="radio " name ="engine " value ="bing "> </ label >
64
+ < label > Ask< input type ="radio " name ="engine " value ="ask "> </ label >
65
+
66
+ < button type ='submit '> Go!</ button >
17
67
</ form >
18
68
19
- </ body >
69
+ </ body >
0 commit comments