简体   繁体   中英

How to add form in a component of select type?

I have to make a user registration form. After completing the form and pressing the button submit, the values from the form need to be added in a component of <p id="data></p> . Can someone help me here? It's working only for the drop-down list.

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form > Name: <input type="text" id="name" name="name" id="mySelect"> <br> Male <input type="radio" id="male" name="male" id="mySelect"><br> Female <input type="radio" id="female" name="female" id="mySelect"><br> Country: <br> <select name="country" size="4" id="mySelect"> <option value="c1">c1</option> <option value="c2">c2</option> <option value="c3">c3</option> <option value="c4">c4</option> <option value="c5">c5</option> </select> <br> <br> </form> <button type="button" onclick="myFunction()">Submit</button> <p id="data"></p> <script> function myFunction() { var x = document.getElementById("mySelect"); var txt = ""; var i; for (i = 0; i < x.length; i++) { txt = txt + x.options[i].text + "<br>"; } document.getElementById("data").innerHTML = txt; } </script> </body> </html>

Here is couple things you should change:

  • DO NOT use same id for different elements on page: it causes issues like you experienced;
  • you duplicated id attribute for every form element - don't do that please, attributes shouldn't be duplicated for single element;
  • please read documentation - getElementById returns single element which match or null;
  • use getElementsByClassName instead giving the same classname to every form element, like "sys-form-element"; in this case getElementsByClassName("sys-form-element") returns collection of matched elements which includes every form field which you could parse then with your "myFunction" - just update it to discover element type and hadle texts, radios and selects differently;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM