Để nhập giá trị hộp văn bản một cách linh hoạt, thêm danh sách thả xuống bằng cách sử dụng jquery?

lập trình


CHÀO ,
Để nhập giá trị văn bản hộp văn bản, thêm động danh sách thả xuống bằng cách sử dụng jquery

Giải pháp 1

CHÀO,

Thực hiện các bước sau.

— Tìm hiểu văn bản từ hộp văn bản bằng cách sử dụng jquery.. như $(‘#txtBox’).text()

— Sau đó tạo thẻ Html của danh sách tùy chọn. Bạn cần tạo hàm jquery phổ biến lấy giá trị hộp văn bản và sẽ tạo phần tử sau. Các giá trị thả xuống sẽ được hiển thị dưới dạng danh sách tùy chọn. Vì vậy bạn có thể tạo thẻ html như sau.

DisplayTextBoxValue

Đảm bảo thẻ nào thả xuống sẽ hiển thị cho các giá trị bằng công cụ dành cho nhà phát triển trình duyệt. Phụ thuộc vào sự thay đổi ở thẻ trên.

— Sau khi tạo phần tử này, bạn chỉ cần thêm nó vào danh sách tùy chọn DropDown bằng cách sử dụng jquery.

— SDK

Giải pháp 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>

コメント

タイトルとURLをコピーしました