0

I have an existing form field like this:

<input id="register-city" type="text" name="city" class="input-block " aria-describedby="register-city-desc" aria-required="true" required="" value=""> 

I want to change the field to select option without changing the HTML code.

How can I accomplish this with JavaScript by injecting the register-city id?

So when the user opens the page, the input field will change to option like:

<option>US</option>
<option>UK</option>
Ultimater
  • 4,647
  • 2
  • 29
  • 43

2 Answers2

1

You can use "opt groups" if you want a single input like this -

Rendering a hierarchy of "OPTION"s in a "SELECT" tag

Or you can make a hierarchical dependency like -

var cities1 = "<option>city1</option><option>city2</option>";
var cities2 = "<option>city3</option><option>city4</option>";

$('#register-city').replaceWith('<select id="register-city"></select>');
var selectCountry = $('select#register-country');
$(selectCountry).on('change', function() {
  if ($('#register-country').val() == 'US') {
    $('#register-city').html(cities1);
  } else if (selectCountry.val() == 'UK') {
    $('#register-city').html(cities2);
  } else {
    $('#register-city').html('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="register-country">
  <option></option>
  <option>US</option>
  <option>UK</option>
</select>

<input id="register-city" type="text" name="city" class="input-block " aria-describedby="register-city-desc" aria-required="true" required="" value="" />
Community
  • 1
  • 1
Jeremy
  • 2,970
  • 1
  • 26
  • 50
0

I don't know why you would want to do something like this but if you can use jquery.

$('#register-city').remove();
$('body').append($('<select name="city"><option value="US">US</option><option value="UK">UK</option></select>'));

https://jsfiddle.net/3h9us5u8/1/

Chaitanya Kale
  • 243
  • 1
  • 7
  • Doesnt work using jQuery, any idea using normal javascript? – Rizky Ariestiyansyah Jul 12 '16 at 04:06
  • var registerCity = document.getElementById("register-city"); registerCity.parentNode.removeChild(registerCity); – Chaitanya Kale Jul 12 '16 at 04:09
  • it will remove the field – Rizky Ariestiyansyah Jul 12 '16 at 04:14
  • Sorry hit enter too soon `var registerCity = document.getElementById("register-city"); registerCity.parentNode.removeChild(registerCity); cityUsa = document.createElement("option"); cityUsa.text = "US" cityUsa.value = "US" cityUk = document.createElement("option"); cityUk.text = "UK" cityUk.value = "UK" select = document.createElement("select") select.options.add(cityUsa); select.options.add(cityUk); document. getElementsByTagName("body").appendChild(select); ` – Chaitanya Kale Jul 12 '16 at 04:15