Home > Mobile >  Display input field depending on select selection
Display input field depending on select selection

Time:01-18

I would like that when I select the select "reject", that an input field opens immediately and if I select something else select something else, this input field is closed again.

<div >
    <label for="order_status">status:</label>
    <select  name="order_status" id="order_status">
        <option value="">select</option>
        <option value="accepted">accepted</option>
        <option value="reject" id="rejectID">reject</option>
    </select>
</div>

<div id="showDiv" style="display: none">
    <input type="text" name="reject_commit">
</div>


<script>
    $(function () {
        $("select[name='order_status']").click(function () {

            if ($("#rejectID").is("reject")) {
                $("#showDiv").show();
            } else {
                $("#showDiv").hide();
            }
        });
    });
</script>

CodePudding user response:

You can do it like this, check the value of your select id, not just the id of the reject option

$(function () {
        $("select[name='order_status']").change(function () {
            if ($("#order_status").val()=="reject") {
              $("#showDiv").css("display","inline");
            } else {
              $("#showDiv").css("display","none");
            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    <label for="order_status">status:</label>
    <select  name="order_status" id="order_status">
        <option value="">select</option>
        <option value="accepted">accepted</option>
        <option value="reject" id="rejectID">reject</option>
    </select>
</div>

<div id="showDiv" style="display: none">
    <input type="text" name="reject_commit">
</div>

CodePudding user response:

If you have id attribute use a id selector, then checks select's (this keyword) value. Dont use click but change handler:

$("#order_status").change(function () {
    if (this.value === "reject") {
       $("#showDiv").show();
    } else {
       $("#showDiv").hide();
    }
});
  • Related