Web Pro Dragons

Internal Dev Library

Dynamic Pull of State

				
					<script>
	document.addEventListener("DOMContentLoaded", function () {

		const countrySelect = document.querySelector("#country2_19642");
		const stateSelect   = document.querySelector("#state2_19642");

		if (!countrySelect || !stateSelect) return;

		async function loadStates(countryName) {

			stateSelect.innerHTML = "<option>Loading...</option>";

			try {
				const response = await fetch("https://countriesnow.space/api/v0.1/countries/states", {
					method: "POST",
					headers: { "Content-Type": "application/json" },
					body: JSON.stringify({ country: countryName })
				});

				const result = await response.json();

				// Clear options
				stateSelect.innerHTML = "";

				// Add placeholder
				stateSelect.innerHTML = `<option value="">- select state -</option>`;

				if (result?.data?.states) {
						result.data.states.forEach(s => {
						const opt = document.createElement("option");
						opt.value = s.name.toLowerCase().replace(/\s+/g, "-");
						opt.textContent = s.name;
						stateSelect.appendChild(opt);
						});
						}

						} catch (e) {
						stateSelect.innerHTML = "<option>Error loading states</option>";
						}
						}

						countrySelect.addEventListener("change", function () {
						let selectedCountry = this.options[this.selectedIndex].text.trim();
						if (selectedCountry) {
						loadStates(selectedCountry);
						}
						});

						});
</script>