-1

I have designed a form that incorporates dynamic functionality based on the selection made in a dropdown menu. When a user selects the 'roll' option from the dropdown, a set of input fields becomes visible, accompanied by a button. This button, labeled 'click to start inputting', serves as a trigger. Conversely, if the user chooses 'packingLeda' from the dropdown, the previously mentioned button disappears.

In the scenario where the 'roll' option is selected, I aim to introduce an additional set of input fields. This new set of fields should become visible only when the user interacts with the 'click to start inputting' button.

To ensure data integrity, I plan to implement validation checks on the input fields before allowing submission. Specifically, I want to restrict input to numerical values, allowing only floating-point numbers. This validation step will help maintain the accuracy of the data collected.

Ultimately, when the user submits the form, all the entered information across both sets of input fields should be collectively gathered and processed. This comprehensive submission process ensures that no data is overlooked and that the entire set of user-provided information is captured effectively.

The problem I'm having is when I click submit button everything disappears, the form handling does not work.

//// function below shows a button when an option is selected from dropdown list
$(function () {
    $('#add').hide();
    $('#itemname').change(function () {
        var text = $(this).children("option:selected").text();
        (text == "Roll" || text == "roll") ? $('#add').show() : $('#add').hide();
        //// ( text == "Roll" || text == "packing Leda") this means you can loop through many options
    });
});

//
////function below shows inputs to add roll weight
$("#add").click(function () {
    newRowAdd =
        '<div class="col-md-3 yyy"><div id="thisTest"><div class="form-group">' +
        ' <label for="example-text-input" id="message" class="form-control-label">Roll Weight</label>' +
        '<small class="text-danger"></small>' +
        '<button  class="btn d-flex btn-danger btn-sm" type="button" id="DeleteRow">Delete</button>' +
        '<input class="form-control" name="kgArray[]" id="kg" type="text" placeholder="type Kg">' +
        '</div></div></div>';
    $('#new').append(newRowAdd);
});

$("body").on("click", "#DeleteRow", function () {
    $(this).parents("#thisTest").remove();
});

$('#itemname').change(function () {
    var text = $(this).children("option:selected").text();
    (text == "Roll" || text == "roll") ? $('#add').show() : $(".yyy").remove();
    //// ( text == "Roll" || text == "packing Leda") this means you can loop through many options
});

//// function below shows all inputs button when an option is selected from dropdown list
$(function () {
    $('.show').hide();
    $('#itemname').change(function () {
        var text = $(this).children("option:selected").text();
        (text == "Roll" || text == "PackingLeda") ? $('.show').show() : $('.show').hide();
        //// ( text == "Roll" || text == "packing Leda") this means you can loop through many options
    });
});

function validateForm() {
    var x = document.forms["addtoInventory"]["kgArray"].value;
    if (x == "") {
        alert("empty row must be deleted before submitting");
        return false;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body">
    <form action="" method="post" name="addtoInventory" onsubmit="return validateForm()">
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="item-name" class="form-control-label">Item name</label>
                    <small class="text-danger"></small>
                    <select class="form-select" name="itemname" id="itemname">
                        <option value=""></option>
                        <option value="roll">Roll</option>
                        <option value="PackingLeda">PackingLeda</option>
                    </select>
                </div>
            </div>
            <div class="col-md-6 show">
                <div class="form-group">
                    <label for="item-price" class="form-control-label">Item Price</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="itemprice" type="text" value="" placeholder="How much did it cost?">
                </div>
            </div>
            <div class="col-md-6 show">
                <div class="form-group">
                    <label for="item-quantity" class="form-control-label">Item Quantity</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="itemquantity" type="text" value="" placeholder="How many did you bought?">
                </div>
            </div>
            <div class="col-md-12 show">
                <div class="form-group">
                    <label for="purchased-from" class="form-control-label">Purchased From</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="purchasedfrom" type="text" value="" placeholder="Where did you buy it from?">
                </div>
            </div>
            <div class="col-md-12 show">
                <div class="form-group">
                    <label for="about-item" class="form-control-label">About Item</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="aboutitem" type="text" value="" placeholder="Write briefly about item">
                </div>
            </div>
            <hr class="horizontal dark">
        </div>

        <div class="row" id="new"></div>
        <button class="btn btn-success ms-0" id="add" type="button">Click to start inputting</button>
        <button name="addI" class="btn d-flex btn-success btn-sm ms-auto">Submit</button>
    </form>
</div>
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
navigator
  • 9
  • 2
  • 1
    Please edit your question and fix the formatting. You also haven't mentioned what the problem is. You describe what you want, what is stopping you? Are you getting errors, and if so, what are they? Edit your question, describe what the problem is, where you're stuck, errors you're getting, etc. – Don't Panic Sep 01 '23 at 05:07
  • Thanks for your reply, the problem i'm having is when i click submit button everything disappears, the form handling does not work – navigator Sep 01 '23 at 15:57
  • "*when I click submit button everything disappears*" - there is no submit button in the code you've shown us? "*function below shows a button when an option is selected*" - it sounds like that code is supposed to only run when an option is selected, but in fact it runs automatically, every time, on page load. Your JS operates on an element with id `add` a lot, but that element is not in the code you've shown us. It is hard to help when we can't see your code. – Don't Panic Sep 02 '23 at 00:26
  • Also we can't run your PHP, and unless you think this is a PHP problem it is not relevant here. Can you substitute in whatever is rendered in the browser, so we can actually run your code? [Please try to create a minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). – Don't Panic Sep 02 '23 at 00:26
  • I apologize for not framing my question correctly; I'm still learning. The issue I'm facing is that I want the submit button to only become functional when all input fields are filled out.. I'll paste the complete code as a snippet thanks – navigator Sep 02 '23 at 13:20

1 Answers1

0

The short version is - you have a simple typo in your validateForm() function, which causes an error. If you check your browser devtools console you'll see that. Because it throws an error, it does not return false, which is what you are using to stop your form submitting when validation fails. So your form submits. You have no action specified for the form, so it just POSTs to the current page, which will look like the page just reloading (and all your inputted data disappearing).

The error on the console is:

Uncaught TypeError: Cannot read properties of undefined (reading 'value')

So that is telling you that document.forms["addtoInventory"]["kgArray"] does not exist. Checking the code, we can see why - the input name is kgArray[], not kgArray. Simply fixing that typo makes your code work for me.

Note there's another way for that input to not exist - if you don't click the "Click to start inputting" button. You should update your code to handle that case too.

Here's a snippet with that typo fixed. To be clear, I select "Roll", then click the "Click to start inputting" button, then click the "Submit" button. AFAICT it behaves as expected.

See below the snippet for some further suggestions.

// function below shows a button when an option is selected from dropdown list
$(function () {
    $('#add').hide();
    $('#itemname').change(function () {
        var text = $(this).children("option:selected").text();
        (text == "Roll" || text == "roll") ? $('#add').show() : $('#add').hide();
    });

});

// function below shows inputs to add roll weight
$("#add").click(function () {
    newRowAdd =
        '<div class="col-md-3 yyy"><div id="thisTest"><div class="form-group">' +
        ' <label for="example-text-input" id="message" class="form-control-label">Roll Weight</label>' +
        '<small class="text-danger"></small>' +
        '<button  class="btn d-flex btn-danger btn-sm" type="button" id="DeleteRow">Delete</button>' +
        '<input class="form-control" name="kgArray[]" id="kg" type="text" placeholder="type Kg">' +
        '</div></div></div>';
    $('#new').append(newRowAdd);
});

$("body").on("click", "#DeleteRow", function () {
    $(this).parents("#thisTest").remove();
});

$('#itemname').change(function () {
    var text = $(this).children("option:selected").text();
    (text == "Roll" || text == "roll") ? $('#add').show() : $(".yyy").remove();
});

// function below shows all inputs button when an option is selected from dropdown list
$(function () {
    $('.show').hide();
    $('#itemname').change(function () {
        var text = $(this).children("option:selected").text();
        (text == "Roll" || text == "PackingLeda") ? $('.show').show() : $('.show').hide();
    });
});

function validateForm() {
    var x = document.forms["addtoInventory"]["kgArray[]"].value;
    if (x == "") {
        alert("empty row must be deleted before submitting");
        return false;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="card-body">
    <form action="" method="post" name="addtoInventory" onsubmit="return validateForm()">
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="item-name" class="form-control-label">Item name</label>
                    <small class="text-danger"></small>
                    <select class="form-select" name="itemname" id="itemname">
                        <option value=""></option>
                        <option value="roll">Roll</option>
                        <option value="PackingLeda">PackingLeda</option>
                    </select>
                </div>
            </div>
            <div class="col-md-6 show">
                <div class="form-group">
                    <label for="item-price" class="form-control-label">Item Price</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="itemprice" type="text" value=""
                           placeholder="How much did it cost?">
                </div>
            </div>
            <div class="col-md-6 show">
                <div class="form-group">
                    <label for="item-quantity" class="form-control-label">Item Quantity</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="itemquantity" type="text" value=""
                           placeholder="How many did you bought?">
                </div>
            </div>
            <div class="col-md-12 show">
                <div class="form-group">
                    <label for="purchased-from" class="form-control-label">Purchased From</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="purchasedfrom" type="text" value=""
                           placeholder="Where did you buy it from?">
                </div>
            </div>

            <div class="col-md-12 show">
                <div class="form-group">
                    <label for="about-item" class="form-control-label">About Item</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="aboutitem" type="text" value=""
                           placeholder="Write briefly about item">
                </div>
            </div>
            <hr class="horizontal dark">
        </div>

        <div class="row" id="new"></div>
        <button class="btn btn-success ms-0" id="add" type="button">Click to start inputting</button>
        <button name="addI" class="btn d-flex btn-success btn-sm ms-auto">Submit</button>
    </form>
</div>

Some observations and suggestions:

  • There are 3 separate event handlers for #itemname changes. This is confusing, and you risk clashes. You can do whatever you need from one, keep it simple;

  • You have 2 separate $(function () { ... }); blocks. That's just jQuery shorthand for the old $(document).ready(function() { ... }); syntax. There's no need for 2, and again having more than 1 is just confusing and liable to cause clashes when you don't see something else that is happening on page load. Keep it simple, use 1;

  • It is considered good practice to separate your HTML from your JS. You've mostly done that, except for the inline onsubmit on the form. Remove that, add a event handler for that in your JS, along with your other event handlers;

  • validateForm() uses plain Javascript, the rest of the code uses jQuery. They'll all work, but IMO it makes reading and maintenance of the code harder, use one or the other consistently;

  • Minor thing but your delete button and JS are not relevant to your current problem, AFAICT, so no need to include it here. Keep it simple! :-)

Here's another snippet with those changes done:

$(function () {
    $('#add').hide();
    $('.show').hide();

    // function below shows a button when an option is selected from dropdown list
    $('#itemname').change(function () {
        var text = $(this).children("option:selected").text();
        if (text == "Roll" || text == "roll") {
            $('#add').show()
        } else {
            $('#add').hide();
            $(".yyy").remove()
        }

        if (text == "Roll" || text == "PackingLeda") {
            $('.show').show()
        } else {
            $('.show').hide();
        }
    });
});

// function below shows inputs to add roll weight
$("#add").click(function () {
    newRowAdd =
        '<div class="col-md-3 yyy"><div id="thisTest"><div class="form-group">' +
        ' <label for="example-text-input" id="message" class="form-control-label">Roll Weight</label>' +
        '<small class="text-danger"></small>' +
        '<button  class="btn d-flex btn-danger btn-sm" type="button" id="DeleteRow">Delete</button>' +
        '<input class="form-control" name="kgArray[]" id="kg" type="text" placeholder="type Kg">' +
        '</div></div></div>';
    $('#new').append(newRowAdd);
});

// Use an event handler instead of inline onsubmit
$('form').on('submit', function() {
    return validateForm();
});

function validateForm() {
    let x = $('form').find('input[name="kgArray[]"]').val();
    if (x == "") {
        alert("empty row must be deleted before submitting");
        return false;
    }
    return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body">
    <form action="" method="post" name="addtoInventory">
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="item-name" class="form-control-label">Item name</label>
                    <small class="text-danger"></small>
                    <select class="form-select" name="itemname" id="itemname">
                        <option value=""></option>
                        <option value="roll">Roll</option>
                        <option value="PackingLeda">PackingLeda</option>
                    </select>
                </div>
            </div>
            <div class="col-md-6 show">
                <div class="form-group">
                    <label for="item-price" class="form-control-label">Item Price</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="itemprice" type="text" value=""
                           placeholder="How much did it cost?">
                </div>
            </div>
            <div class="col-md-6 show">
                <div class="form-group">
                    <label for="item-quantity" class="form-control-label">Item Quantity</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="itemquantity" type="text" value=""
                           placeholder="How many did you bought?">
                </div>
            </div>
            <div class="col-md-12 show">
                <div class="form-group">
                    <label for="purchased-from" class="form-control-label">Purchased From</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="purchasedfrom" type="text" value=""
                           placeholder="Where did you buy it from?">
                </div>
            </div>

            <div class="col-md-12 show">
                <div class="form-group">
                    <label for="about-item" class="form-control-label">About Item</label>
                    <small class="text-danger"></small>
                    <input class="form-control" name="aboutitem" type="text" value=""
                           placeholder="Write briefly about item">
                </div>
            </div>
            <hr class="horizontal dark">
        </div>

        <div class="row" id="new"></div>
        <button class="btn btn-success ms-0" id="add" type="button">Click to start inputting</button>
        <button name="addI" class="btn d-flex btn-success btn-sm ms-auto">Submit</button>
    </form>
</div>
Don't Panic
  • 13,965
  • 5
  • 32
  • 51