Get All Form Elements with JavaScript - javascript

I'm trying to get all elements from Form using JavaScript. I have tried the below method but I am still unable to extract all elements.
Are there any suggestions anyone can provide to extract all Form elements information?
$(document).ready(function(){
// References:
var $form = $('#rForm');
var $subm = $('#submitForm');
var $impt = $form.find(':option, :input').not(':button, :submit, :reset, :hidden');
// Submit function:
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// On success, clear all inputs;
$impt.val('').attr('value','').removeAttr('checked').removeAttr('selected');
},'json');
return false;
});
});

Related

POST output into a modal from any form class on page

Sorry I am a beginner with jQuery and Javascript. I want to be able to get the results into my modal from any form on the page that has class ajax. My code is below but not working correctly. Currently it opens the post result in a new page and not in the modal. Can anyone shed any light on my code?
Many thanks
$(document).ready(function() {
$('.ajax').click(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('name').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(value);
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
This probably happens because your browser submits the form by default. It doesnt know youre doing AJAX stuff. To prevent this, use preventDefault().
In addition to that, jQuery has a built in function for serializing (1 and 2) form data.
$(document).ready(function() {
$('form.ajax').click(function(event) {
event.preventDefault(); // prevents opening the form action url
var $form = $(this),
url = $form.attr('action'),
type = $form.attr('method'),
data = $form.serialize();
// console.log(value); // value doesnt exist outside of your loop btw
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
Also, its not quite clear if you bind the click event handler to a form or a button, I guess the first one. You should change the handler to the following:
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {

Is it posiible to use onClick function on my form submit button?

I store multiple data in a table for enquiry basis.. which is successfully stored in my table. but now i also want to store those same data in Booking basis.
So i used onClick function for storing enquiry data. and now i want to store booking data in table from form submit button.
here is my form submit button code:
<button type="submit" class="booking-btn" onclick="btn_booking_hour();" id="btn_booking_hour">Book Now</button>
Here is my form action:
<?php echo form_open('booking/'.$product->id); ?>
And here my function:
function btn_booking_hour()
{
var date = $('#datehour').val();
var renter_id = $("#ownerid").val();
var guests_quantity = $('#no_of_guests').val();
var property_id = $('#property_id').val();
var selectedIds="";
var selectedObject = document.getElementsByClassName('hour_slots_available slot_activated');
for(var i=0;i<selectedObject.length;i++)
selectedIds+=selectedObject[i].id+",";
if(selectedIds == ""){
alert("Please select Hour-Slot(s) before Booking");
}
else{
$.ajax({
type: 'POST',
dataType:'json',
url:baseURL+'site/rentals/ajaxhourshow',
data:{'selectedHours':selectedIds,'property_id':property_id,'date':date,'guests_quantity':guests_quantity,'renter_id':renter_id},
success: function(responce){
var myJSON = JSON.stringify(responce);
var packet = $.parseJSON(myJSON);
var prd_id=packet.property_id;
var hour_slots=packet.hour_slots;
window.location.href = baseURL+'booking/'+prd_id;
}
});
}
}
Please suggest me how can i submit a form with data within their onClick function. Thanks..
Not sure if you are using a form, if you are using it you can can use onsubmit handler and return the action. In that case you wont need onclick handler in the button
<form onsubmit = "return btn_booking_hour()">
// Rest of code
</form>
You can also do like this
$('#form').on('submit',function(e){
e.preventDefault();
// rest of the code
})
you can use this code
function btn_booking_hour(){
// your other code
document.getElementById('formid').submit();
// formid = form id
}
or also use jquery
function btn_booking_hour(){
// your other code
$('#formid').submit();
// formid = form id
}
i got your point so you can also use it
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
rest of your code
});
});

submitting looping forms with jquery/ajax?

I have forms being created in a foreach loop with php.
Each form has a lpformnum that increases
<form lpformnum="1"><button class="update" /></form>
<form lpformnum="2"><button class="update" /></form>
<form lpformnum="3"><button class="update" /></form>
etc.
I am using jquery/ajax to prevent the default action of the forms so I can submit the forms via ajax.
<script>
$(document).ready(function(){
$('.alert').on('click', 'button[class=update]', function(e) {
e.preventDefault();
e.stopPropagation();
var checkValues = $("#update").val();
var checkCred = $("#ucredits").val();
var checkPost = $("textarea").text();
var checkType = $("i").text();
$.ajax({
type: "POST",
url: "update_social_cred.php",
data: { id: checkValues, credits: checkCred, text: checkPost, type: checkType },
success:function(result) {
alert (checkCred);
}
});
});
});
</script>
The problem is, every button submits the first form drawn on the page. How would I do this so each button is set to each form keeping in mind there are an unknown number of forms being drawn?
I suppose you should clarify what data you want to submit with find() method.
$('.alert').on('click', 'button[class=update]', function(e) {
e.preventDefault();
e.stopPropagation();
// find parent form of a button
var form = $(this).closest( "form" );
// I suppose these are unique fields.
var checkValues = $("#update").val();
var checkCred = $("#ucredits").val();
var checkPost = $("textarea").text();
// if they are not you should use classes instead:
// something like:
// var checkCred = form.find(".ucredits").val();
// find values in a `form` with `find` method
var checkType = form.find("i").text();
// pass your data to ajax.

Forms with Ajax send with multi-parameter and A href

within the form element I send data with a href. Using the JavaScript (as defined below), it works perfectly.
I want to send the forms now with Ajax, unfortunately it does not work. Do you have a solution for me. jQuery is included on the page.
Thank You!
function sendData(sFm, sID, sFn, sCl) {
var form = document.getElementById(sFm);
form.sid.value = sID;
form.fnc.value = sFn;
form.cl.value = sCl;
form.submit();
}
Send Data
My new Code:
function sendData(sFm, sID, sFn, sCl) {
var form = $("#"+sFm);
form.submit( function() {
var sid = $('input[name="sid"]').val(sID);
var fnc = $('input[name="fnc"]').val(sFn);
var cl = $('input[name="cl"]').val(sCl);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: {sid: sid, fnc: fnc, cl: cl}
}).done(function( e ) {
});
});
form.submit();
}
$("form").submit(function() { // for all forms, if you want specially one then use id or class selector
var url = $(this).attr('action'); // the script where you handle the form input.
var method = $(this).attr('method');
$.ajax({
type: method,
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // handle response here
}
});
return false; // avoid to execute the actual submit of the form.
});
:) , Thanks
Just because we don't want to submit all form by ajax so we can set a data-attribute to form tag to indicate, will it should be submit by ajax or normally ,, so ,,
$("form").submit(function() { ...
if($(this).attr('data-ajax') != "true") return true; // default hanlder
...
so If form is written like this :-
<form action="/dosomething" method="post" data-ajax="true"> </form> // will be sumit by ajax
<form action="/dosomething" method="post" data-ajax="false"> </form>
// will be sumit by default method

Why isn't my javascript function defined for this function?

This is very consistent, but firebug is showing that my saveForm function is not being defined form my 'button.save' event handler, but it works for my 'button.deleteForm' event handler:
function saveForm(form)
{
var $form = form;
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data)
{
// data is the server response.
// change this function to tell the
// user whether their submission
// is correct or what fields have
// bad data.
var response = JSON.parse(data);
return true;
}
});
return false; // avoid to execute the actual submit of the form.
}
// Do not use event handlers like .click(). This is the
// only viable solution for handling events on dynamically
// generated HTML elements. This handles the saving of data
// to the server.
$(document).on('click', 'button.save', function(e){
var $form = $(this).closest('form');
saveForm(form);
});
// This event handler is responsible for deleting data.
// For Joey's job: Please make sure that this calls save
// after the user hits delete. This will save the data in
// the database.
$(document).on('click', 'button.deleteForm', function(e){
// Get the form to update before deleting our embedded form
var $form = $(this).closest('form');
var str = $(this).attr('id');
// Get the table id in review to delete
var deleteForm = str + '_review';
$('table#' + deleteForm).remove();
// Get the collection form id to delete
var idArray = str.split('_');
idArray.pop();
divId = '#' + idArray.join('_');
$(divId).remove();
saveForm($form);
});
you missed $ in saveform
$(document).on('click', 'button.save', function(e){
var $form = $(this).closest('form');
saveForm($form);
//------^----here
});

Categories