问题
I've been searching or a solution to my problem, but none of the aswers I find are useful.
I try to make an automatic form that submits itself when the page loads.
$(document).getElementById('ticketCount').submit(function(){
$.ajax({
method:$(this).attr('method'),
url:$(this).attr('action'),
data:$(this).serialize()
})
.done(function(data){
$('#ticketCount').html(data);
})
.error(function(data){
console.log(data);
});
});
My console tells me that: "Uncaught TypeError: undefined is not a function". I don't think I made a mistake (I know this is case-sensitive), and I already used $(document).ready(), $(document).keyup(function{}) somewhere else in the same .js file, so I don't think the problem comes from $(document)..
I can't ind where my mistake is...
Thanks for your answers!
回答1:
.getElementById() -> this is javascript syntax to get the DOM element having a particular unique Id.
in jQuery it is deferent. You nead to have a selector for that DOM element
Many selectors are there. Here you nead ID SELECTOR. that is: #id
so you need to write like:
$('#ticketCount').submit(function(){
.............................
If you want to submit automatically when the page load use:
window.onload = function(){
$('#ticketCount').trigger("submit");
};
回答2:
You've got 3 mistakes.
First: $(document)
is not a DOM element, so .getElementById
is undefined. Instead use the jQuery selector.
Second: .submit
requires a user to press the submit button. Instead let's use $(document).ready
Change
$(document).getElementById('ticketCount').submit(function(){
into
$(document).ready(function(){
Third: The jQuery ajax function doesn't have a property called method
. Instead it has the type
instead
Change
method:$(this).attr('method'),
into
type:$(this).attr('method'),
回答3:
use setTimeout
setTimeout(function(){
var elem = document.getElementById('ticketCount');
var $elem = $(elem);
$.ajax({
type:$elem.attr('method'),
url:$elem.attr('action'),
data:$elem.serialize()
})
.done(function(data){
$elem.html(data);
})
.error(function(data){
console.log(data);
});
},500);
回答4:
$("#ticketCount").submit(function(){
change the code
$(document).getElementById('ticketCount').submit(function(){
to
$("#ticketCount").submit(function(){
来源:https://stackoverflow.com/questions/23341103/jquery-document-getelementbyidid-submitfunction-unedifined-not-a-f