Home > Software engineering >  Hide and show element and stay with the same option selected
Hide and show element and stay with the same option selected

Time:04-15

i have this code

:javascript
showFormulaInput = function() {
let checkBox = document.getElementById("enable_custom_formula");
let select = document.getElementById('select_formula_id')

if (checkBox.checked == true){
    $('#front_dashboard_custom_formula').show()
    $('#front_dashboard_formula_formula_id').hide()
    select.value = ''
} else {
    $('#front_dashboard_custom_formula').hide()
    $('#front_dashboard_formula_formula_id').show()
    select.value('the same before')
}
}

$(document).ready(function() {
  showFormulaInput();
});

if checkbox is checked i need to show my front_dashboard_custom_formula div and hide front_dashboard_formula_formula_id and set select null if checkbox is not checked i need to hide front_dashboard_custom_formula div and show front_dashboard_formula_formula_id div and stay with the same id selected before

CodePudding user response:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
<input type="checkbox">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
    $("input[type=checkbox]").on("click", function(e){
        console.log(this.checked ? "show" : "hide")
    })
</script>
</body>
</html>

CodePudding user response:

What a weirdly worded question. Here's an answer.

<div id="div1" style="display: none">front_dashboard_custom_formula</div>
<div id="div2">front_dashboard_formula_formula_id</div>

<input type="checkbox" />
<select>
    <option value="option1">option1</option>
    <option value="option2">option2</option>
</select>

<script>
    const div1 = document.querySelector('#div1');
    const div2 = document.querySelector('#div2');
    const checkbox = document.querySelector('input');
    const select = document.querySelector('select');

    const show = (element) => (element.style.display = 'none');
    const hide = (element) => (element.style.display = 'block');

    const handleCheckboxChange = () => {
        if (checkbox.checked) {
            show(div1);
            hide(div2);
            return;
        }

        show(div2);
        hide(div1);
    };

    checkbox.addEventListener('change', handleCheckboxChange);
</script>

CodePudding user response:

if u want to keep option selected just add this

select.attr('selected',true);

i hope it was useful !

  • Related