Converting a text input to a select element with JavaScript

前端 未结 4 1186
梦如初夏
梦如初夏 2020-12-18 22:41

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 the

相关标签:
4条回答
  • 2020-12-18 22:54

    If you already have an dropdown/select list and you just want to add an item to it from a label/textbox then you can try this :

     if ($(textBoxID).val() != '') {
                    $(dropDownID)
                        .append($("<option></option>")
                            .attr('value', ($(textBoxID).val()))
                                .text($(textBoxID).val())).val($(textBoxID).val())
    }
    
    0 讨论(0)
  • 2020-12-18 22:55

    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>');
    
    0 讨论(0)
  • 2020-12-18 22:59

    You haven't set the field name. Add name='txtQuantity' to the select. Without a name attribute the value of the field will not get posted back to the server.

    Also rather than setting value='1' on the select (which isn't doing anything), add selected='selected' to the first option. The result is the same as by default the first option is selected.

    You are presumably ending up with the select after the submit button with the above code. However that has been covered in another answer.

    0 讨论(0)
  • 2020-12-18 23:10

    Remove the type and value attributes from the <select>, and add the name="txtQuantity" attribute that you left out.

    0 讨论(0)
提交回复
热议问题