11import { Controller } from '@hotwired/stimulus'
22
33export default class extends Controller {
4- static targets = [ "country" , "state" ]
4+ static targets = [ "country" , "state" , "stateName" , "stateWrapper" , "stateNameWrapper" ]
55
66 loadStates ( ) {
77 const countryId = this . countryTarget . value
@@ -13,22 +13,47 @@ export default class extends Controller {
1313 } )
1414 }
1515
16- updateStateOptions ( data ) {
16+ updateStateOptions ( states ) {
17+ if ( states . length === 0 ) {
18+ // Show state name text input if no states to choose from.
19+ this . toggleStateFields ( false )
20+ } else {
21+ // Show state select dropdown.
22+ this . toggleStateFields ( true )
23+ this . populateStateSelect ( states )
24+ }
25+ }
26+
27+ toggleStateFields ( showSelect ) {
28+ const stateWrapper = this . stateWrapperTarget
29+ const stateNameWrapper = this . stateNameWrapperTarget
1730 const stateSelect = this . stateTarget
31+ const stateName = this . stateNameTarget
1832
19- stateSelect . innerHTML = ""
2033
21- if ( data . length === 0 ) {
22- stateSelect . disabled = true
23- } else {
34+ if ( showSelect ) {
35+ // Show state select dropdown.
2436 stateSelect . disabled = false
25-
26- data . forEach ( ( state ) => {
27- const option = document . createElement ( "option" )
28- option . value = state . id
29- option . innerText = state . name
30- stateSelect . appendChild ( option )
31- } )
37+ stateName . value = ""
38+ stateWrapper . classList . remove ( 'hidden' )
39+ stateNameWrapper . classList . add ( 'hidden' )
40+ } else {
41+ // Show state name text input if no states to choose from.
42+ stateSelect . disabled = true
43+ stateWrapper . classList . add ( "hidden" )
44+ stateNameWrapper . classList . remove ( "hidden" )
3245 }
3346 }
47+
48+ populateStateSelect ( states ) {
49+ const stateSelect = this . stateTarget
50+ stateSelect . innerHTML = ""
51+
52+ states . forEach ( ( state ) => {
53+ const option = document . createElement ( "option" )
54+ option . value = state . id
55+ option . innerText = state . name
56+ stateSelect . appendChild ( option )
57+ } )
58+ }
3459}
0 commit comments