使用jquery动态输入文本框值添加下拉列表?

[ad_1]

你好 ,
使用jquery动态添加下拉列表输入文本框文本值

解决方案1

你好,

执行以下步骤。

— 使用jquery从文本框中找出文本..如$(‘#txtBox’).text()

— 然后创建选项列表的Html标签。 您需要创建通用的 jquery 函数,该函数采用文本框值并将创建以下元素。 下拉值显示为选项列表。 因此,您可以按如下方式创建 html 标签。

显示文本框值

使用浏览器开发人员工具确保下拉的标签显示值。 取决于上面标签的更改。

— 创建此元素后,您只需使用 jquery 将其附加到 DropDown 选项列表。

— 软件开发工具包

解决方案2

<script type="text/javascript">
        var controlIdCounter = 1;
        function AddMoreVariant(controlIdCounter) {
            if (controlIdCounter === undefined || controlIdCounter === null) {
                //                controlIdCounter = 1; 
                var sapCode = $("#txtSAPCODE").val();
                var Variant_UnitID = $("#<%= ddlvariantUnit.ClientID %> option:selected").val();
                var Variant_Unit_Name = $("#<%= ddlvariantUnit.ClientID %> option:selected").text();
                var Variant_SizeID = $("#<%= ddlvariant_weight.ClientID %> option:selected").val();
                var Variant_Weight = $("#<%= ddlvariant_weight.ClientID %> option:selected").text();
                var Variant_MRP = $("#<%= VariantMRP.ClientID %>").val();
                var Variant_SellingPrice = $("#<%= variantSelling_Price.ClientID %>").val();
            }
            else {
                var sapCode = $("#txtSAPCODE").val();
                var Variant_UnitID = $("#ddlvariantUnit" + controlIdCounter + " option:selected").val();
                var Variant_Unit_Name = $("#ddlvariantUnit" + controlIdCounter + " option:selected").text();
                var Variant_SizeID = $("#ddlvariant_weight" + controlIdCounter + " option:selected").val();
                var Variant_Weight = $("#ddlvariant_weight" + controlIdCounter + " option:selected").text();
                var Variant_MRP = $("#VariantMRP" + controlIdCounter).val();
                var Variant_SellingPrice = $("#variantSelling_Price" + controlIdCounter).val();
            }
            if (sapCode !== "" && Variant_UnitID !== "" && Variant_SizeID !== "" && Variant_MRP !== "" && Variant_SellingPrice !== "") {
                var data = {
                    sapCode: sapCode,
                    Variant_UnitID: Variant_UnitID,
                    Variant_Unit_Name: Variant_Unit_Name,
                    Variant_SizeID: Variant_SizeID,
                    Variant_Weight: Variant_Weight,
                    Variant_MRP: Variant_MRP,
                    Variant_SellingPrice: Variant_SellingPrice
                };

                $.ajax({
                    type: "POST",
                    url: "AddNewProduct.aspx/AddMoreVariant",
                    data: JSON.stringify({ variant: data }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (response.d === "Success") {
                            console.log("Data has been inserted");
                            $("#checkbox" + controlIdCounter).removeAttr("style").prop("checked", true).prop("disabled", true).css({
                                "width": "48px",
                                "height": "37px"
                            });
                            $("#checkbox").removeAttr("style").prop("checked", true).prop("disabled", true).css({
                                "width": "48px",
                                "height": "37px"
                            });
                            //$("#checkbox" + controlIdCounter).show().prop('checked', true);
                        } else if (response.d === "Fail") {
                            Swal.fire('Error', 'This variant is already available!', 'error');
                        } else {
                            Swal.fire('Error', 'Failed to insert data. Please try again.', 'error');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("Error inserting data: " + error);
                    }
                });
            } else {
                Swal.fire('Error', 'Please fill in all fields for this variant.', 'error');
            }
        }
        //Insert Functionality into DB row wise
        function AppendVariant() {
            if ($("#txtSAPCODE").val() === "") {
                Swal.fire('Error', 'Please fill SapCode!', 'error');
                return false;
            }
            var sapCode = $("#txtSAPCODE").val().trim();
            var VUnit = $("#ddlvariantUnit option:selected").val().trim();
            var Vweight = $("#ddlvariant_weight option:selected").val().trim();
            var VMrp = parseFloat($("#VariantMRP").val().trim());
            var VsellingPrice = parseFloat($("#variantSelling_Price").val().trim());
            if (sapCode.length !== 7) {
                Swal.fire('Error', 'SAP Code should be exactly 7 digits!', 'error');
                return false;
            }
            if (VUnit === "" && Vweight === "" && VMrp === "" && VsellingPrice === "") {
                Swal.fire('Error', 'Please fill in all variant fields before appending more variants!', 'error');
                return false;
            }
            if (isNaN(VsellingPrice) || isNaN(VMrp)) {
                Swal.fire('Error', 'Please enter valid numeric values for Selling Price and MRP!', 'error');
                return false;
            }

            if (VsellingPrice > VMrp) {
                Swal.fire('Error', 'Selling Price should not be greater than MRP!', 'error');
                return false;
            }

            if (parseFloat($("#variantSelling_Price").val()) > parseFloat($("#VariantMRP").val())) {
                Swal.fire('Error', 'Selling Price should not be greater than MRP!', 'error');
                return false;
            }

            var newRow = $("<tr>");
            newRow.append("<td>Unit</td>");
            newRow.append('<td><select class="form-control arrows AppendddlvariantUnit" id="ddlvariantUnit' + controlIdCounter + '" style="width: 150px; top: 0px; left: 0px;"></select></td>');
            newRow.append("<td>Weight</td>");
            newRow.append('<td style="padding-left: 60px;"><select class="form-control arrows Appendddlvariant_weight" id="ddlvariant_weight' + controlIdCounter + '" style="width: 150px;"></select></td>');
            newRow.append("<td>MRP</td>");
            newRow.append('<td><input type="text" class="form-control" id="VariantMRP' + controlIdCounter + '" style="width: 150px;" onkeypress="return ValidateCharector(event)"></td>');
            newRow.append("<td>Selling Price</td>");
            newRow.append('<td style="padding-left: 25px;"><input type="text" class="form-control" id="variantSelling_Price' + controlIdCounter + '" style="width: 150px;" onblur="ValidatePrice();" onkeypress="return ValidateCharector(event)"></td>');
            newRow.append('<td><input type="button" value="Save" class="AddButton" onclick="AddMoreVariant(' + controlIdCounter + ');" /></td>');
            newRow.append('<td><input type="button" value="Remove" id="Remove" class="Reset" onclick="RemoveVariantfromDb(' + controlIdCounter + ');" /></td>');
            //newRow.append('<td><input type="button" value="Remove" class="Reset" onclick="RemoveVariantfromDb(' + controlIdCounter + ');" /></td>');
            newRow.append('<td><input type="checkbox" id="checkbox' + controlIdCounter + '" style="display: none; width:30px"  /></td>');
            //            newRow.append('<td><input type="button" value="Remove" id="Remove" class="Reset" onclick="removeRowVariant(this);RemoveVariantfromDb(' + controlIdCounter + ');" /></td>');
            $("#tableBody").append(newRow);
            if (parseFloat($("#variantSelling_Price" + controlIdCounter).val()) > parseFloat($("#VariantMRP" + controlIdCounter).val())) {
                Swal.fire('Error', 'Selling Price should not be greater than MRP!', 'error');
                return false;
            }
            if ($("#ddlvariantUnit" + controlIdCounter).val() === "" &&
           $("#ddlvariant_weight" + controlIdCounter).val() === "" &&
           $("#VariantMRP" + controlIdCounter).val() === "" &&
           $("#variantSelling_Price" + controlIdCounter).val() === "") {
                Swal.fire('Error', 'Please fill in all variant fields before appending more variants!', 'error');
                return false;
            }
           


            // AJAX call to fetch dropdown data
            $.ajax({
                url: 'AddNewProduct.aspx/GetDropdownData',
                method: 'POST',
                contentType: 'application/json',
                success: function (data) {
                    var dropdownData = data.d;
                    var unitDropdown = $("#ddlvariantUnit" + controlIdCounter);
                    $.each(dropdownData.units, function (index, item) {
                        unitDropdown.append($('<option>', {
                            value: item.UnitID1,
                            text: item.UnitName1
                        }));
                    });

                    var weightDropdown = $("#ddlvariant_weight" + controlIdCounter);

                    // Function to populate weights based on the selected unit
                    function populateWeights(unitId) {
                        $.ajax({
                            type: "POST",
                            url: "AddNewProduct.aspx/GetWeightsByUnitId",
                            data: JSON.stringify({ unitId: unitId }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                // Clear existing options
                                weightDropdown.empty();
                                // Populate weight dropdown with the fetched weights
                                $.each(response.d, function (index, item) {
                                    weightDropdown.append($('<option>', {
                                        value: item.SizeID,
                                        text: item.Wiegit
                                    }));
                                });
                            },
                            error: function () {
                                alert('Failed to fetch dropdown data!');
                            }
                        });
                    }

                    unitDropdown.change(function () {
                        // Get the selected unit ID
                        var unitId = $(this).val();
                        // Populate weights based on the selected unit
                        populateWeights(unitId);
                    });

                    controlIdCounter++;
                },
                error: function () {
                    alert('Failed to fetch dropdown data!');
                }
            });
        }

        //Remove
               function RemoveVariantfromDb(controlIdCounter) {
            var confirmation = confirm("Are you sure you want to remove this Variant?");
            if (!confirmation) {
                return;
            }

            var sapCode = $("#txtSAPCODE").val();
            var variantId, Weight, MRP, sellingPrice;

            // Check controlIdCounter to determine where to get values from
            if (controlIdCounter === undefined || controlIdCounter === null) {
                variantId = parseInt($("#<%= ddlvariantUnit.ClientID %> option:selected").val());
                Weight = parseInt($("#<%= ddlvariant_weight.ClientID %> option:selected").val());
                MRP = parseFloat($("#<%= ddlvariant_weight.ClientID %> option:selected").val());
                sellingPrice = parseFloat($("#<%= ddlvariant_weight.ClientID %> option:selected").val());
            } else {
                variantId = parseInt($("#ddlvariantUnit" + controlIdCounter).val());
                Weight = parseInt($("#ddlvariant_weight" + controlIdCounter).val());
                MRP = parseFloat($("#VariantMRP" + controlIdCounter).val());
                sellingPrice = parseFloat($("#variantSelling_Price" + controlIdCounter).val());
            }

            // Check if all variants values are available
            if (sapCode && !isNaN(variantId) && !isNaN(Weight) && !isNaN(MRP) && !isNaN(sellingPrice)) {
                $.ajax({
                    type: "POST",
                    url: "AddNewProduct.aspx/RemoveVariantFromDB",
                    data: JSON.stringify({
                        sapcode: sapCode,
                        variantId: variantId,
                        Weight: Weight,
                        MRP: MRP,
                        sellingPrice: sellingPrice
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        debugger;
                        if (response.d === "Success") {
                            $("#checkbox" + controlIdCounter).hide();
                            $("#tableBody").find("tr[data-controlid='" + controlIdCounter + "']").remove();
                            console.log("Data has been removed" + controlIdCounter);
                        }
                        else {
                            $("#checkbox" + controlIdCounter).hide();
                            $("#tableBody" + controlIdCounter).remove();
                            $("#tableBody").find("tr[data-controlid='" + controlIdCounter + "']").remove();
                            //$("#tableBody" + controlIdCounter).remove();
                            console.log("Data Not Inserted" + controlIdCounter);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("Error removing data: " + error);
                    }
                });
            } else {
                console.error("Variant data is incomplete or not found");
            }
        }
        
    </script>

[ad_2]

コメント

标题和URL已复制