user1742919 user1742919 - 7 months ago 17
HTML Question

Whats Wrong in this Code to generate SelectBoxes Dynamically?

<html>

<head>

<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
function myf() {
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');

var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
</script>


</head>

<body >

<form id="msj_form" >

<button id="add" value="add" onclick="myf()">ADD</button>



</form>

</body>

</html>


While Clicking on ADD button the selbox is generating but its disappering immediatly..whats wrong in my code

While Clicking on ADD button the selbox is generating but its disappering immediatly..whats wrong in my code

Answer

Because after your function is called the form is submitted, so what you will need to do is prevent form submission.

Try this:

<html>
<head>
</head>
<body>
  <form  id="msj_form" >
    <button id="add" value="add">ADD</button>
  </form>
  <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
  <script>
    function myf(e) {
      e.preventDefault(); // <-- make sure to add this
      alert("coming dude");
      var numbersString = "1,2,3,4,5,6";
      var data = numbersString.split(',');

      var s = $("<select id=\"selectId\" name=\"selectName\" />");
      for(var val in data) {
        $("<option />", {value: val, text: data[val]}).appendTo(s);
      }
      s.appendTo("#msj_form");
    }
    $('#add').on('click',myf);
  </script>
</body>
</html>

If you'd like to learn more about preventDefault(), see here - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Comments