DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chara has posted 50 posts at DZone. View Full User Profile

Converting a text input to a select with JavaScript

  • submit to reddit
<div id="buy-buttons">
  <input name="txtQuantity" id="txtQuantity" type="text" value="1" />
  <input type="submit" name="btnAddToCart" value="Add To Cart" id="btnAddToCart" />
// First way:
$("#buy-buttons").append('<select name="txtQuantity" id="txtQuantity"></select>');
$("#txtQuantity").append('<option value="1" selected="selected">1</option>' +
    '<option value="2">2</option>' +
    '<option value="3">3</option>' +
    '<option value="4">4</option>' +
    '<option value="5">5</option>');
// Second way:
    .replaceWith('<select name="txtQuantity" id="txtQuantity">' +
        '<option value="1">1</option>' +
        '<option value="2">2</option>' +
        '<option value="3">3</option>' +
        '<option value="4">4</option>' +
        '<option value="5">5</option>' +

 Sometimes you need the page dimanically 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.