html - How to add a element to HTML5 code with JavaScript -
i've got problem javascript code. beginner in programming ask me. script must do? after clicking submit button must write on site value of 2 form fields. html code:
<!doctype html> <html lang="pl_pl"> <head> <title>kidgifter</title> <meta charset="utf-8" /> <link rel="stylesheet" href="css/style.css" /> <script src="js/scripts.js"></script> </head> <body> <div id="list_help"> <img id="smile_help" src="img/smile.png"> <div id="info-form"> <p id="l_h_title">hejka!</p> <p id="l_h_text">tutaj możesz stworzyć swoją liste prezentów udostępnić ją na facebooku lub twitterze. niech twoi znajomi bliscy wiedzą co chcesz dostać!</p> <p id="l_h_formtitle">najpierw wprowadź nazwę prezentu:</p> <form> <input type="text" id="formtitle"> <p id="l_h_formdesc">a teraz możesz krótko go opisać:</p> <textarea id="formdescription" maxlength="230"></textarea> <input type="submit" value="+ dodaj" id="sub" /> </form> </div> </div> </body> </html>
and javascript code :
window.onload = function(){ var f1 = document.getelementbyid("f1"); var f2 = document.getelementbyid("f2"); var submit = document.getelementbyid("sub"); var body = document.getelementsbytagname("body"); submit.onclick = function() { html = ""; html += "<div class='gift'>"; html += "<div class='gifttext'>"; html += "<p class='gifttitle'>" + f1.value + "</p>"; html += "<p class='giftdescription'>" + f2.value + "</p>"; html += "</div>"; html += "</div>"; body.appendchild(html); return false; } }
thank ! :)
you must create dom element, put rest of html in dom element , use dom element .appendchild()
this. appendchild()
doesn't take string, takes dom element. also, body
variable wasn't correct. here's fixed version:
window.onload = function () { var f1 = document.getelementbyid("f1"); var f2 = document.getelementbyid("f2"); var submit = document.getelementbyid("sub"); submit.onclick = function () { var html = "<div class='gifttext'>"; html += "<p class='gifttitle'>" + f1.value + "</p>"; html += "<p class='giftdescription'>" + f2.value + "</p>"; html += "</div>"; var div = document.createelement("div"); div.classname = "gift"; div.innerhtml = html; document.body.appendchild(div); return false; } }
itemized changes:
- declare
html
variable local variable it's not implicit global. - remove outer div html string.
- create outer div
document.createelement("div")
. - assign desired class name div.
- assign html
.innerhtml
property of div created. - append div
document.body
object. - remove code obtaining
body
variable (it wrong ,document.body
exists shortcut reference body object).
Comments
Post a Comment