I'm using jquery to insert a hidden form into a page (once the page has already loaded). For some reason the code is not working. Here is a sample of the code:
$(function(){
$('body')
.append('<form id="mySearch"></form>'); //append a new form element with id mySearch to <body>
$('#mySearch')
.attr("action","mySearchPage.cfm") .attr("method","post") //set the form attributes
//add in all the needed input elements
.append('<input type="hidden" name="btnSearch" id="btnSearch" value="Search">')
.append('<input type="hidden" name="txtField1" id="txtField1" value="">')
.append('<input type="hidden" name="txtField2" id="txtField2" value="">')
.append('<input type="hidden" name="selType" id="selType" value="0">')
.append('<input type="hidden" name="selType2" id="selType2" value="2">')
});
The form is not being inserted into the body of the page. What am I doing wrong?
Update: I've found that when I use the code in a page on it's own it works correctly. When I try to integrate it into a large, already existing page it no longer works. Any ideas ab开发者_JAVA百科out what might cause the exact same code to fail?
try this:
$(document).ready(function(){
$('body')
.append('<form id="mySearch"></form>'); //append a new form element with id mySearch to <body>
$('#mySearch')
.attr("action","mySearchPage.cfm") .attr("method","post") //set the form attributes
//add in all the needed input elements
.append('<input type="hidden" name="btnSearch" id="btnSearch" value="Search">')
.append('<input type="hidden" name="txtField1" id="txtField1" value="">')
.append('<input type="hidden" name="txtField2" id="txtField2" value="">')
.append('<input type="hidden" name="selType" id="selType" value="0">')
.append('<input type="hidden" name="selType2" id="selType2" value="2">')
});
Anyway you should absolutely avoid this kind of approach to add dynamic content to the dom. The best technique is to create a single string containing all the necessary markup and inject it in one shot! Something like:
var HTML = '<form attributes><input><input>...</form>';
$("#container").html(HTML);
It works for me, perhaps you don't want hidden form fields?
http://jsfiddle.net/M5vWR/
See this one with visible form elements.
http://jsfiddle.net/M5vWR/2/
After all, it was just a syntax problem with an extra tag in the file that included the javascript :P The code works now!
精彩评论