fist i select any option from fist select menu, then press on add button to get new select menu at this time the fist selected option is switches to default, how to prevent it…
<body id = "body"> <button onclick="add()">Add</button> <select> <option selected disabled>Choose...</option> <option value="c1"> one </option> <option value="c13"> two </option> <option value="c11"> three </option> <option value="c12"> four </option> </select> </body> <script> let body = document.getElementById('body'); function add(){ body.innerHTML += `<select> <option selected disabled">Choose...</option> <option value="c1"> one </option> <option value="c13"> two </option> <option value="c11"> three </option> <option value="c12"> four </option> </select>`; } </script>
https://jsfiddle.net/zala_jaydipsinh/34b95dq2/1/
Advertisement
Answer
Try like this:
let body = document.getElementById('body'); function add() { body.insertAdjacentHTML(`beforeend`, `<select> <option selected disabled">Choose...</option> <option value="c1"> one </option> <option value="c13"> two </option> <option value="c11"> three </option> <option value="c12"> four </option> </select>`) }
<body id="body"> <button onclick="add()">Add</button> <select> <option selected disabled>Choose...</option> <option value="c1"> one </option> <option value="c13"> two </option> <option value="c11"> three </option> <option value="c12"> four </option> </select> </body>
insertAdjacentHTML() does this without overwriting the content of the body element.