Converting a Text Input to a Select with JavaScript

Sometimes you need the page dynamically changes a texbox with a dropdown box. On the example below we show you how to perform this work. The first way demonstrates how to do this with remove() and append() jQuery methods and the second shows how to perform the same work with replaceWith() method.

[View All Snippets]
Show Plain Text »
  1. <div id="buy-buttons">
  2.   <label>Quantity:</label>
  3.   <input name="txtQuantity" id="txtQuantity" type="text" value="1" />
  4.   <input type="submit" name="btnAddToCart" value="Add To Cart" id="btnAddToCart" />
  5. </div>
  7. <script>
  8. // First way:
  9. $("#txtQuantity").remove();
  10. $("#buy-buttons").append('<select name="txtQuantity" id="txtQuantity"></select>');
  11. $("#txtQuantity").append('<option value="1" selected="selected">1</option>' +
  12.     '<option value="2">2</option>' +
  13.     '<option value="3">3</option>' +
  14.     '<option value="4">4</option>' +
  15.     '<option value="5">5</option>');
  17. // Second way:
  18. $("#txtQuantity")
  19.     .replaceWith('<select name="txtQuantity" id="txtQuantity">' +
  20.         '<option value="1">1</option>' +
  21.         '<option value="2">2</option>' +
  22.         '<option value="3">3</option>' +
  23.         '<option value="4">4</option>' +
  24.         '<option value="5">5</option>' +
  25.         '</select>');
  26. </script>
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory

Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.