Why does jquery to add input fields stops working when I add $.ajax for form processing?
I'm working on a bit of code that asks a user for text input. Additionally, the user has the option to click "Click to add" to create an additional text input field. I was able to get this functionality to work using the jQuery below. However, when I tried to add more jQuery to process the user input with PHP (this begins with the setting of var dataString
in the .js file below), I found that the initial "click to add" functionality stopped working.
I'm pretty stumped about why and any insight one could provide would be great.
This is my HTML:
<body>
<div id="form_inputs">
<a href="#" id="add">click to add</a>
<form method="POST">
<div id="input">
<p><input type="text" name="user_response[]" id="u_resp开发者_如何学编程onse" /></p>
</div>
</form>
<button id="submit">submit answers</button>
</div>
This is my current js file:
$(function() {
var count = $('#form_inputs p').length + 1;
$('#add').live('click', function(){
$('<p><input type="text" name="user_response[]" id="u_response" /><a href="#" id="remove">remove</a></p>').appendTo('#input');
count++;
return false;
});
$('#remove').live('click', function(){
if(count > 2)
{
$(this).parents('p').remove();
count--;
return false;
}
});
var dataString = $('input#user_response').val();
$.ajax ({
type: "POST";
url: "test3.php";
data: dataString;
success: function(){
$('#form_inputs').html('<div id="message"></div>');
$('#message').html('<h4>thanks for submitting</h4>');
}
})
});
Your ajax call isn't going to process the user inputs as it's being called in the ready function and needs to be tied to the submit button using a click event handler like you did with the remove and add. Also you are trying to select on name for the dataString (which also needs to be in that click event for the ajax call) so try the selector var dataString = $('input[name=user_response]').val();
Also the id's for the newly generated inputs need to be unique so use some sort of number to give it unique id (like the count variable). Same needs to happen with the remove buttons (try making it a class of remove instead of id and update your click event handler to use that).
$("#submit").live("click",function()
{
var inputs = $('input[name^=user_response]');
var dataString = [];
for(var i = 0; i < inputs.length; i++)
{
dataString.push($(inputs[i]).val());
}
$.ajax ({
type: "POST",
url: "test3.php",
data: {'user_response':dataString},
success: function(){
$('#form_inputs').html('<div id="message"></div>');
$('#message').html('<h4>thanks for submitting</h4>');
}
})
});
If it makes sense in what you want done you can either leave dataString as an array or make it a true string. But you will want to loop through each of the inputs or it will only give you back the first one (there are probably more efficient ways to loop through using jquery).
精彩评论