Converting a text input to a select with JavaScript


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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>
  6.  
  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>');
  16.  
  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>

URL: http://www.apphp.com/index.php?snippet=javascript-converting-text-input-to-select

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.