Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - Converting a text input to a select element with JavaScript

I'm doing some front end development on a hosted e-commerce platform. The system sends a text input for the customer to choose the quantity of items they want to add to their cart, but I would prefer a select. I don't have access to the markup the system spits out in this regard, so I'd like to use JavaScript to change the text input to a select element.

I used jQuery to remove the select and duplicate the input element with a select with the right choices, but when I try to add something to my cart, only one item is added, regardless of the choice in the select.

Here's the native markup:

<div id="buy-buttons">
  <label>Quantity:</label>
  <input name="txtQuantity" type="text" value="1" id="txtQuantity" class="ProductDetailsQuantityTextBox">
  <input type="submit" name="btnAddToCart" value="Add To Cart" id="btnAddToCart" class="ProductDetailsAddToCartButton ThemeButton AddToCartThemeButton ProductDetailsAddToCartThemeButton">
</div>

Here's the jQuery I'm running to update my markup.

 $("#txtQuantity").remove();
 $("#buy-buttons").append('<select id="txtQuantity" type="text" value="1" class="ProductDetailsQuantityTextBox"></select>');
 $("#txtQuantity").append('<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>');

Does anyone know why this isn't working? Shouldn't the select be submitting the information to through the form in the same way as the text input?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use replaceWith instead of remove and append. Also the type attribute on the <select> is unnecessary and the <option> nodes should be within the <select>. Here's the docs on replaceWith - http://api.jquery.com/replaceWith/.

$("#txtQuantity")
    .replaceWith('<select id="txtQuantity" name="txtQuantity" class="ProductDetailsQuantityTextBox">' +
          '<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>' +
        '</select>');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...