简体   繁体   中英

Form won't submit when generated with Javascript

I'm generating a login form in javascript. The form displays perfectly and the HTML looks fine in Google Dev Tools but the form won't submit when I click the submit button.

Heres's the generated form code:

var loginBox = '<div id="loginBox">';
loginBox    += '<h1>Login</h1>';
loginBox    += 'Please use the form to login below<br /><br />';
loginBox    += '<form action="home.php" method="post">';
loginBox    += '<div class="input">';
loginBox    += '<label for="username">Username</label>';
loginBox    += '<input type="text" name="username" />';
loginBox    += '</div>';
loginBox    += '<div class="input">';
loginBox    += '<label for="userpass">Password</label>';
loginBox    += '<input type="password" name="password" />';
loginBox    += '</div>';
loginBox    += '<div class="clear"></div>';
loginBox    += '<div class="input">';
loginBox    += '<input type="submit" class="submit button" value="Submit" />';
loginBox    += '</div>';
loginBox    += '</form>';
loginBox    += '</div>';

Any ideas on why this wouldn't work? I know I could probably write some Javascript to submit the form when the submit button is pressed but I don't see why that should be necessary. Thanks

The bigger question is why are you creating a login box with Javascript?

I think that it is cleaner to refactor it and have the form live inside a hidden div, and use JavaScript to show/hide it as required. This would get around some brower's issues with dynamically adding a form using element.innerHTML.

If that is not an option then you may have to change your JS to add it using the DOM. This is quite verbose and not very easy to read.

I added it to this page and it seemed to work. Do you have any client validation scripts that might intercept the form submit event?

My code:

$(loginBox).appendTo("body");

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