Post Dynamic Inputs that are Appended with jQuery - javascript

I have found multiple questions that are the same, these include:
dynamically inserted form inputs aren't posted
jQuery not posting all inputs of a form after the .append()
Most problems are caused by opening the form within a table / div or some other problem with the HTML. I don't believe I have either of these problems; I suspect my javascript needs to be tweaked.
I am using jQuery as so:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
When the add link is clicked a new table row is appended to tbody.newRow
When clicking .remove, you are asked for confirmation. Upon confirmation the row is removed.
The form is submitted via ajax when input.Value loses focus.
jQuery:
$(document).ready(function() {
$(".add").on('click', function() {
$("tbody.newRow").append(
'<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection">Remove</td></tr>'
);
});
$("tbody").on('click', '.remove', function() {
$(this).parent().append($(
'<div class="confirmation">YesNo</div>'
))
$(this).remove();
});
$("tbody").on('click', '.removeConfirm', function() {
$(this).parent().parent().parent().remove();
});
$("tbody").on('click', '.removeCancel', function() {
$(this).parent().parent().append(
'Remove');
$(this).parent().remove();
});
var formTwo = $('.ajaxTwo'); // contact form
// form submit event
$(".Value").blur(function() {
$.ajax({
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formTwo.serialize(), // serialize form data
success: function(data) {
url: 'functions.php'; // form action url
},
error: function(e) {
console.log(e)
}
});
});
});
The html form. The ajax works wonderfully with the existing row that is not added dynamically. The add row is located in the table footer looking pretty. The form is posted as an array.
<form class="ajaxTwo" method="post">
<table>
<tbody class="newRow">
<tr>
<td>
<input type="text" name="NewJobLeviesId[]" class="JobLeviesId" />
<input type="text" name="NewValue[]" class="Value" />
<input type="text" name="MasterId[]" class="Values" />
<input type="text" name="LUPChoiceId[]" class="Values" />
<input type="text" name="SortOrder[]" class="Values" />
</td>
<td class="removeSelection">
Remove
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
Add Row
</td>
</tr>
</tfoot>
</table>
</form>
Finally the php. Each row is inserted into my database table with a PDO prepared statement.
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
if(isset($_POST['NewJobLeviesId'])) {
for($i=0; $i<count($_POST['NewJobLeviesId']); $i++) {
$NewJobLeviesId = $_POST['NewJobLeviesId'][$i];
$NewValue = $_POST['NewValue'][$i];
$MasterId = $_POST['MasterId'][$i];
$LUPChoiceId = $_POST['LUPChoiceId'][$i];
$SortOrder = $_POST['SortOrder'][$i];
$sql = "INSERT INTO joblevies (JobLeviesId,Value,MasterId,LUPChoiceId,SortOrder) VALUES (:JobLeviesId,:Value,:MasterId,:LUPChoiceId,:SortOrder)";
$q = $db->prepare($sql);
$q->execute(array(':JobLeviesId'=>($NewJobLeviesId),':Value'=>($NewValue),':MasterId'=>($MasterId),':LUPChoiceId'=>($LUPChoiceId),':SortOrder'=>($SortOrder)));
}
}
}
Again, this works wonderfully well. Only the dynamically added inputs have a problem. What am I missing?

The dynamically created dom elements don't have any of the events that you attach on $(document).ready(... because they didn't yet exist when you were attaching events. So the $('.Value').blur(... stuff is only attached to the first form, and not any future ones. So attach the event every time you create a new row, so maybe something like this:
First, delegate the binding action to its own function
function attachSubmitEvent() {
// form submit event
//remove old events first
$(".Value").off();
$(".Value").blur(function () {
var formTwo = $('.ajaxTwo'); // contact form
$.ajax({
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formTwo.serialize(), // serialize form data
success: function (data) {
url: 'functions.php'; // form action url
},
error: function (e) {
console.log(e)
}
});
});
}
then in your document.ready, call that function
attachSubmitEvent();
then, to make sure they are also attached to the new elements, call it again when creating new elements
$(".add").on('click', function () {
$("tbody.newRow").append('<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection">Remove</td></tr>');
attachSubmitEvent(); //now everyone has the event attached.
});

For your form submit event, try:
$("tbody").on('focusout', '.Value', function() {
...
});
You could also use blur in this event handler, but the documentation recommends using focusout for clarity (See 'Additional Notes' section of jQuery on() method documentation: http://api.jquery.com/on/)

Related

how to validate dynamic text box values in jquery

Thanks in advance.I have a popup window which has a dynamic text box fields.These textboxes will multiple according to the selected combo box values from the first form.The dynamic textboxes are displayed from jquery. Please anyone help me how to validate a dynamic text boxes on clicking the submit button. Actually I have to validate the textboxes before sending the mail. I have written a code which will validate only static textboxes. My code as below
<head>
<script>
$(document).ready(function () {
$(".myformid").click(function(){
var nameVal = $('.names').val();
var emailVal = $('.emails').val();
var phoneVal = $('.phones').val();
if(nameVal == "")
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Name</p>");
}
else if(emailVal == ""){
//alert("A textbox is required");
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the email Id</p>");
}
else if(!ValidateEmail(emailVal))
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Invalid Email Id</p>");
}
else if(phoneVal == "")
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Phone Number</p>");
}
else if(isNaN(phoneVal))
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Valid Phone Number</p>");
}
else if(emailVal !="" && phoneVal != "")
{
$('#errmsg').text(" ");
var username = $('#usernameId').val();
var length = $('#lengthId').val();
var nameArray = [];
var emailArray = [];
var phoneArray = [];
$('.names').each(function(){
nameArray.push(this.value);
});
var nameboxVal = nameArray.join(",");
//alert(nameboxVal);
$('.emails').each(function(){
emailArray.push(this.value);
});
var emailboxVal = emailArray.join(",");
//alert(emailboxVal);
$('.phones').each(function(){
phoneArray.push(this.value);
});
var phoneboxVal = phoneArray.join(",");
//alert(phoneboxVal);
$.ajax({
type: "POST",
url: "/invl_exams/popSubmit",
data: {user:username,name:nameboxVal,email:emailboxVal,phone:phoneboxVal,lengths:length},
success: function(result){
console.log(result);
$('#mailSuccess').text('Mail Send Successfully');
$('#mailSuccess').fadeOut(5000);
}
});
}
});
});
// Passing dynamic textboxes inside the dialog box
$(".create-user").change(function(){
var selVal = $(this).val();
$('#lengthId').val(selVal);
$("#textboxDiv").html('');
if(selVal > 0) {
for(var i = 1; i<= selVal; i++) {
var sno = i;
$("#textboxDiv").append('<tr><td>'+sno+'. </td><td>Name:<input type="text" name="names" class="names" value="" required="required" /></td><td> </td><td>Email:<input type="email" name="emails" class="emails" value="" required="required" /></td><td> </td><td>Phone:<input type="text" name="phones" class="phones" value="" required="required" minlength="10" maxlength="16"/><br/></td></tr>');
}
}
});
});
</script>
</head>
<body>
<div id="dialog" title="Enter details to send Mail">
<!--<form id="myformid" method="post" action="<?php //echo $this->webroot?>users/sendmail">-->
<div id="mailSuccess" style="color:#019002;font-weight:bold"></div>
<form id="myformid" method="post">
<table id="examtable">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<div id="textboxDiv"></div>
<input type="hidden" name="username" id="usernameId" value="<?php echo $this->Session->read('Auth.User.username'); ?>">
<input type="hidden" name="length" id="lengthId" value="">
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>
<!--<input type="submit" name="btnSubmit" value="Submit">-->
<input type="button" name="btnSubmit" value="Send Mail" id="popSubmit">
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
I don't think any validation is happening at all, whether the elements are static or dynamic.
$(".myformid").click(function(){
will not bind to anything because there are no elements with the class "myformid". The "." at the start of a selector indicates a class.
However you do have an element with an id "myformid". If you change your selector from . to # to indicate an id, then it will bind the event to the form. However, "click" is not the correct event to bind to a <form> element. You want to handle the form's "submit" event:
$("#myformid").submit(function(event){
Lastly, as it stands, your form will do a regular (non-ajax) postback as well as running your function, because the default behaviour of the submit event is not suppressed. Add this line as the first line of the above function:
event.preventDefault();
This will stop a regular postback from happening and allow your validation function to execute. At that point you should have a working solution, assuming the logic in your validation code is what you want.
If your validations are right you just need to attach event in way that dinamicly created elements will be supported too (jQuery on)
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
for example
from
$(".myformid").click(function(){/*Some action*/});
to
$("body").on('click', ".myformid", function(){/*Some action*/});
from
$(".create-user").change(function(){/*Some action*/});
to
$("body").on('change', ".create-user", function(){/*Some action*/});
Small advice: Try to avoid using $("body") selector you can see what is your good dom element witch is parent to your dynamically generated contend/elements.

jQuery Ajax Post keep adding username and password on the URL

I am using the Login Dialog as mentioned here on jQWidgets which I think is not the problem I am having and hence it shouldn't matter if someone has used it before or not for answering my question:
When testing the login functionality by putting login credentials, the username and password keep getting added on the URL of the page which I don't want. I am not sure why it's happening. Am I doing something wrong with the jQuery Ajax Post Webservice call?
Say for example, my home page URL of the webapp is : https://example.com/home.html
After entering loging credentials, it gets added to the URL for some reason like this:
https://example.com/home.html?username=myname&password=mypassword
Here is my HTML:
<!-- Login HTML Begins -->
<div id="wrap">
<div id="window" caption="Login">
<div>
<form >
<table>
<tr>
<td>Username:</td>
<td><input style="width: 150px;" type="text" name="user" id = "username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input style="width: 150px;" type="password" name="password" id = "password" /></td>
</tr>
<tr>
<td colspan="2" align="right" valign="bottom">
<input type="submit" id="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
</div>
<!-- Login HTML ends -->
Here is my Javascript Code:
<script type="text/javascript">
$(document).ready(function () {
$('#window').jqxWindow({ theme: "shinyblack", width: 250, height: 130, isModal: true });
$('#submit').jqxButton({ theme: "shinyblack" });
var loginUrl = "https://example.com:8443/Webservice/loginCheck"
$( "#submit" ).click(function() {
var userName = $("#username").val();
var passWord = $("#password").val();
var ajaxRequest = jQuery.ajax({
//beforeSend: TODO: show spinner!
data: {
username: userName,
passWord: passWord
},
dataType: "json",
method: "POST",
url: loginUrl
})
.done(function (data_, textStatus_, jqXHR_) {
// Validate the web service and retrieve the status.
if (typeof (data_) === "undefined" || data_ === null) { alert("Invalid data returned from LoginCheck Web Service"); return false; }
if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) { alert("Invalid Web Service Status for LoginCheck Webservice!"); return false; }
if (data_.webservice_status.status != "SUCCESS") { alert(data_.webservice_status.message);
return false; }
})
.fail(function (jqXHR_, textStatus_, errorThrown_) {
alert("Hitting the Fail function : Error in LoginCheck webservice: " + errorThrown_);
return false;
});
}
});
</script>
The default protocol used by forms are GET so you need to override it using POST protocol
so you need something like this:
<form action="url" method="post">
..
..
..
</form>
also the embedded click function you should prevent some default by putting this code :
$("#submit").click(function(e){
e.preventDefault();
<!-- your statement !>
...
})
also the butto type :
<button type="button" id="submit"></button>
or
<input type="button" id="submit">
The way you've set it up, you're submitting the form data in the traditional way rather than via AJAX.
One option is to add:
$('form').on('submit',function(event){
event.preventDefault();
});
(A common error is to try to prevent form submission in a click handler attached to the submit button. There are a number of ways to submit a form and the submit button is only one of them.)
Another option is to just remove the form element.
Your form may be sending a get request, because you haven't prevented the default functionality of a form button. Try adding these two lines to your click handler:
$( "#submit" ).click(function(event) {
event.preventDefault();
event.stopPropagation();
}

how to update a html-select without reload the page in php

I need to update one dropdwonlist without reload the page, I mean, I have a form where I add the elements that I need, then I have another form where I have the dropdownlist conected to my database but if I do not have the element I need to select, I have to add it from the other form, but the problem is that i need to reload the page in order to the dropdownlist show the new element then I loose the data I was typing.
I wish to know a way to update the dropdownlist without reload the page.
Im using php and mysqli my code is simple:
<form action="edit_col_exe.php" method="post">
<p><label>Add Element:</label>
<input autofocus type="text" name="elemnt" class="input" required />
</p>
<table>
<tr>
<td><input type="submit" name="Save" value="Save" /></td>
</tr>
</table>
</form>
Form2:
Select Element
query("select * from Elements order by Element asc") or die("fail");
echo "Select an option";
while($reg=$con ->fetch_assoc()){
echo "";
echo $reg['Element'];
}?>
I hope someone can help me!
regards!
Use Ajax (I prefer jQuery) and remove your form.
JS
function addElement(){
// get new name
var name = $("#newElementsName").val();
// create ajax call
$.ajax({
type: "POST",
url: "edit_col_exe.php", // URL to php script
data: { // post data for php script (I use the data from your form (including the typo))
elemnt: name,
save: 'Save'
},
success: function(data){
// this function will be called when php script run successful (HTTP-Status 2xx)
// Clear the input filed
$("#newElementsName").val('');
// Add new name to dropdown
$("#elements").append("<option>"+name+"</option>");
}
});
}
HTML
<div>
<p><label>Add Element:</label>
<input autofocus type="text" id="newElementsName" class="input" required />
</p>
<table>
<tr>
<td><button type="button" onclick="addElement()">Save</button></td>
</tr>
</table>
</div>
<div>
<select id="elements" size="1">
</select>
</div>
I solved my problem and I want to share with you my solution, its simple:
setInterval(function(){
$('#searchelement').load('addelements.php');
});
<p><label>Element</label>
<select id="searchelement" name="element" required />
</option>
</select></p>
So everytime I add an element at 'addelements.php', I can search the new element in the select list.

Reload a single DIV on a page using onClick

In my page there are several DIVs, which are supposed to show different news items depending on the user selection and a press of a submit button.
Am I able to refresh only a single DIV when the relevant submit button is clicked?
I tried <input type ="button"> instead of <input type="submit"> but that didn't work as expected. My code is below:
<div class="dloader"></div>
<div class="search">
<form action="" method="post">
Furniture:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php
if( isset($_POST['submit']) ){
$postItemHeader = htmlentities($_POST['val1']);
}?>
<script>
$(window).load(function() {
$(".dloader").fadeOut("slow");
})
</script>
Take One Button For Post Event
<input type="submit" id="add" name="add" />
If You want to pass the Text Data, so a text value from the Text to fetch the particular data
<div id="result">Result should appear here</div>
Use Javascript To POst The Text Data To Back End
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#add').val,
success: function(data, status) {
$("#result").html(data)
}
});
});
});
What you need is AJAX. (read the documentation). A simple example is here.
The HTML
<div id="target_div"></div> <!-- Here is where you gonna place your new content -->
<input type='button' id='trigger' onClick="get_new_data()" value="Get new Content"> <!-- When this button is pressed get new content -->
The Javascript
function get_new_data()
{
$.ajax(
{
type: POST,
url: "you-url-here.php",
dataType:"HTML", // May be HTML or JSON as your wish
success: function(data)
{
$('div#target_div').html(data) // The server's response is now placed inside your target div
},
error: function()
{
alert("Failed to get data.");
}
}); // Ajax close
return false; // So the button click does not refresh the page
} // Function end

Stop 2 Instances of an Ajax form on the same page interfering with each other

I've the following form twice on my homepage:
<form id="get-consultation-form" action="javascript:alert('success!');" >
<h3 class="sub-heading">Book a Consultation</h3>
<div id="message"></div>
<div id="fields">
<input type="text" maxlength="" name="Consultation[name]" placeholder="NAME" />
<input type="text" maxlength="" name="Consultation[number]" placeholder="NUMBER" />
<input type="text" maxlength="" name="Consultation[email]" placeholder="EMAIL" />
<button type="submit" class="btn">Submit</button>
</div>
</form>
The form uses jQuery/Ajax/PHP to forward the data via email:
$(document).ready(function() {
$("#get-consultation-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "http://novicecoder.co.uk/priestley/consultation-process.php",
data: str,
success: function(msg) {
$(document).ajaxComplete(function(event, request, settings) {
NProgress.set(0.0);
if (msg === 'OK') {
result = '<div class="thanks" id="thanks">Thank you, we will contact you <span>shortly.</span></div>';
$(this).find("#fields").hide();
NProgress.set(0.5);
$("#message").hide();
$("#message").html(result).slideDown(100);
$("#message").html(result);
}
else
{
result = msg;
$("#message").hide();
$("#message").html(result).slideDown(200);
$("#message").html(result);
}
NProgress.set(1.0);
});
}
});
return false;
});
});
The first form is working perfectly, however as you'll see in my working example, the 2nd is not:
My website
Any ideas why this is happening????
IDs are unique.
Try to change form elements to diferent ids.
Or instead use classes.
If you use classes you can use $('.messages-class').closest() inside the form submit() for only interact in the current form.
You can't have an element with the same ID on a page twice. Replace your #get-consultation-form ID with a class, that should solve your issue. This also applies to the elements within the form like #fields and #message.

Categories