Auto submit form information without page reload - javascript

I have a form with a bunch of number fields, all these fields serves the purpose to be added to each other through php. The only problem is that for the numbers to actually be submitted and make the php function work, I have to click the submit button which reloads the page. While this actually does work it is a bit annoying, that it has to reload and at the same time it removes the numbers from the actual form, so the user can't see where he/she has entered their numbers.
I know it is possible in some way to make it submit automatically, but is it possible to make the php function get the form information every time a user enters something, so that the new total sum would be automatically updated, thus not having to reload?
I have my php and html in the same script, but for the case of this question I have split them into two parts.
PHP part
<?php
$amount_s_bp = $_POST['amountSmallBP'];
$amount_m_bp = $_POST['amountMedBP'];
$amount_l_bp = $_POST['amountLargeBP'];
$amount_xl_bp = $_POST['amountXLBP'];
$amount_s_wp = $_POST['amountSmallWP'];
$amount_m_wp = $_POST['amountMedWP'];
$amount_l_wp = $_POST['amountLargeWP'];
$amount_xl_wp = $_POST['amountXLWP'];
$amount_s_bs = $_POST['amountSmallBS'];
$amount_m_bs = $_POST['amountMedBS'];
$amount_l_bs = $_POST['amountLargeBS'];
$amount_xl_bs = $_POST['amountXLBS'];
$amount_s_bt = $_POST['amountSmallBT'];
$amount_m_bt = $_POST['amountMedBT'];
$amount_l_bt = $_POST['amountLargeBT'];
$amount_xl_bt = $_POST['amountXLBT'];
$shirt_price = 150;
$amount_total = $amount_s_bp + $amount_m_bp + $amount_l_bp + $amount_xl_bp + $amount_s_wp + $amount_m_wp + $amount_l_wp + $amount_xl_wp + $amount_s_bs + $amount_m_bs + $amount_l_bs + $amount_xl_bs + $amount_s_bt + $amount_m_bt + $amount_l_bt + $amount_xl_bt;
$price_total = $amount_total * $shirt_price;
?>
Form part
As you can see I have a bunch of number inputs and then at the end I have a "total" area where the total sum should be displayed using <?php echo $price_total; ?> and <?php echo $amount_total; ?>.
<form action="index.php" method="post" id="orderForm" onsubmit="return checkCheckBoxes(this);">
<div class="row">
<div class="col-xs-6">
<div class="bpShirtDesign">
<span id="bpShirtOformT">Sort Polka</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBP" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBP" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBP" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBP" placeholder="Antal"/>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="wpShirtDesign">
<span id="bpShirtOformT">Hvid Polka</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallWP" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedWP" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeWP" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLWP" placeholder="Antal"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="bsShirtDesign">
<span id="bpShirtOformT">Bla Stribet</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBS" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBS" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBS" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBS" placeholder="Antal"/>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="btShirtDesign">
<span id="bpShirtOformT">Bla Tattersall</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBT" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBT" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBT" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBT" placeholder="Antal"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="bgTotals">
<input type="submit" value="Submit" id="submitValues">
<span id="totalAmount" class="h3">I alt antal = </span><?php echo $amount_total; ?><br>
<span id="totalPrice" class="h3">I alt pris = </span> <?php echo $price_total; ?><span> DKK</span>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</form>

You don't need a server-side script for this kind of processing. Just prevent that the form is submitted with:
<button type="button">Button</button>
Then, using javascript, retrieve the value of each form and perform calculations.
//Gets the value
var value = document.getElementById('myid')
//Repeat that last line until all values are retrieved
...
//Make your calculations
var result = value + value2 //... etc
//Display your result
document.getElementById('resultid').textContent = result;
Although, if you are going to sum a lot of elements, it might be better to give the same class to those elements, so you can do this:
var elements = document.getElementsByClassName('myclassname');
var sum = 0;
for (var i=0, max=elements.length; i < max; i++) {
sum = sum + parseInt(elements.item(i).textContent);
}
UPDATE
To add an event listener to every input you can iterate over every element or you could associate a listener to a parent element like this:
document.getElementById('myParentElement').addEventListener('input', function() {
return update();
}, false);
And you should throw all the code that retrieves the values from the inputs, perform the calculations and updates the DOM in the update() function, which will get called every time an input changes.

First things first, you have the id "amount" on all of your inputs. This will not work, an id can only be used once per page. So, figure out a convention to make these id's unique. Like id='field1-id' or something. Also, remove the action and method attributes from your form tag. They'll be unneeded at this point.
Then you can use jQuery and an AJAX call to do what you are looking for. Something like:
$("#submitValues").bind('click', function(e){
var formData[];
$("#orderForm").each('input[^="-id"]', function(){
formData.push($(this).val());
});
$.ajax({
url: 'index.php',
data: formData
}).success(function(response){
$("totalAmount").val(response.returnedTotalAmount);
$("totalPrice").val(response.returnedTotalPrice);
}).fail(function(response){
/* do something else */
});
e.preventDefault();
});
Mind you this code is untested, and very hastily written but it should give you the general idea of how to accomplish what you're after.

Related

How to compute surface-area using javascript?

I have the following 3 inputs: Length, Width, Height.
Using javascript I need to compute the area of a cube, but before that I can't event get the fucntion to work when I press the button "CALCULEAZA". How can I make the "calculeaza" function work?
<div class="col-sm-4">
<div class="row">
<h3>Calculator de Folie</h3>
<form>
Lungime:<br>
<input type="text" name="firstname" id="lungime"><br>
Latime:<br>
<input type="text" name="lastname" id="latime"><br>
Inaltime:<br>
<input type="text" name="lastname" id="inaltime"><br>
<button id="submit" onclick="calculeaza()" style="margin- top:5%;">CALCULEAZA</button>
</form>
</div>
<div class="row container fluid">
<h1 id="value-zone"><span id="value">100</span>m2</h1>
</div>
</div>
<div class="col-sm-4">
<h3>Seminte Demetra CR</h3>
</div>
</div>
</div>
<script>
$(document).ready(function() {
document.getElementById('value-zone').hidden = true;
});
function calculeaza(){
var x = parseFloat(document.getElementById('lungime').value);
var y = x/2;
console.log("aaaaaa");
document.getElementById('value-zone').hidden = false;
}
</script>
I also know that using scripts in the same file is not ok, but I am going to modify it after I undertand how it works. It is my first JS 'thing' I do. Thank you in advance!
Use e.preventDefault() to not redirect on click of submit button. Otherwise the code is running fine.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
<div class="row">
<h3>Calculator de Folie</h3>
<form>
Lungime:<br>
<input type="text" name="firstname" id="lungime"><br>
Latime:<br>
<input type="text" name="lastname" id="latime"><br>
Inaltime:<br>
<input type="text" name="lastname" id="inaltime"><br>
<button id="submit" onclick="calculeaza()" style="margin- top:5%;">CALCULEAZA</button>
</form>
</div>
<div class="row container fluid">
<h1 id="value-zone"><span id="value">100</span>m2</h1>
</div>
</div>
<div class="col-sm-4">
<h3>Seminte Demetra CR</h3>
</div>
</div>
</div>
<script>
$(document).ready(function() {
document.getElementById('value-zone').hidden = true;
});
function calculeaza(){
var x = parseFloat(document.getElementById('lungime').value);
var y = x/2;
console.log("aaaaaa");
document.getElementById('value-zone').hidden = false;
}
$("#submit").click((e)=>{e.preventDefault()})
</script>
change your button to:
<button id="submit" type="button" onclick="calculeaza()" style="margin- top:5%;">CALCULEAZA
by default, the button is of type SUBMIT, which will submit the form. You can use javascript to disable the function or simply make a minor change to your button.
Perhaps something like this:
<div class="col-sm-4">
<div class="row">
<h3>Calculator de Folie</h3>
<div class="form-group">
<label class="col-form-label" for="length">length</label>
<input type="number" class="form-control" id="length">
</div>
<div class="form-group">
<label class="col-form-label" for="width">width</label>
<input type="number" class="form-control" id="width">
</div>
<div class="form-group">
<label class="col-form-label" for="height">height</label>
<input type="number" class="form-control" id="height">
</div>
<button onclick="calculeaza()" style="margin-top:5%;">CALCULEAZA</button>
</div>
<div class="row container fluid">
<h1 id="value-zone"><span id="value">100</span>m2</h1>
</div>
</div>
<script>
document.getElementById('value-zone').hidden = true;
// calculates the surface area of a cuboid and updates #value with the answer
function calculeaza() {
var l = parseFloat(document.getElementById('length').value);
var w = parseFloat(document.getElementById('width').value);
var h = parseFloat(document.getElementById('height').value);
if (!isNaN(l) && !isNaN(w) && !isNaN(h)) {
document.getElementById('value-zone').hidden = false;
document.getElementById('value').innerHTML = 2*(l*w + w*h + l*h);
}
}
</script>
Removed the <form> and used bootstrap's "form-groups" instead. No jquery needed for this since it seems you use document.getElementById anyways.

Appending user input with jQuery

I have the following HTML structure, which cannot be changed.
I need to append the user typed info to a <ul> list with jQuery.
I have tried it using the following code but id does nothing. What would be the correct way to do it?
$(document).ready(function() {
$(".btn btn-outline-primary").click(function() {
let toAdd = $("input[#title]").val();
$("<li>" + toAdd + "</li>").appendTo("<ul>");
});
});
<body>
<div class="container">
<div class="row">
<div class="col-6">
<h2>Add Show</h2>
<form>
<div class="form-group">
<label for="title">Show Title</label>
<input type="text" class="form-control" id="title" placeholder="enter title" />
</div>
<div class="form-group">
<label for="rating">Show rating </label>
<input type="number" min="0" max="10" value="5" class="form-control" id="rating" />
</div>
<button type="submit" class="btn btn-outline-primary">Add show</button>
</form>
</div>
<div class="col-6">
<h2> Show List</h2>
<ul>
</ul>
<button class="btn btn-outline-secondary"> Delete List</button>
</div>
</div>
</div>
</body>
</html>
A bunch of bugs to fix:
Separating selectors with space means that the document is searched for the first selector with a descendant of the second selector - you don't want that here, keep the class names together (or just select the btn-outline-primary alone, since there's only one of them)
You need to preventDefault() to keep the form from submitting and replacing the page
The existing ul in the HTML should be selected if you want to append to it - '<ul>' isn't a valid selector.
The #title should just be selected as #title (ids can't be repeated in HTML, after all):
$(".btn-outline-primary").click(function(e) {
e.preventDefault();
let toAdd = $("#title").val();
$("<li>" + toAdd + "</li>").appendTo("ul");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-6">
<h2>Add Show</h2>
<form>
<div class="form-group">
<label for="title">Show Title</label>
<input type="text" class="form-control" id="title" placeholder="enter title" />
</div>
<div class="form-group">
<label for="rating">Show rating </label>
<input type="number" min="0" max="10" value="5" class="form-control" id="rating" />
</div>
<button class="btn btn-outline-primary">Add show</button>
</form>
</div>
<div class="col-6">
<h2> Show List</h2>
<ul>
</ul>
<button class="btn btn-outline-secondary"> Delete List</button>
</div>
</div>
</div>
$(document).ready(function(){
$('form').submit(function(e) {
e.preventDefault();
let toAdd = $("#title").val();
$("<li>" +toAdd+ "</li>").appendTo(jQuery("ul"));
});
});
First override the submit.
Value should be fetched properly. using #title
Append to proper element
You have wrong selectors in your code (for btn and title), plus i'd change also the append code.
Also, you have a submit button inside a form, clicking it will cause the submit.
Try this:
$(document).ready(function(){
$("form").submit(function(e){
//prevent form submit;
e.preventDefault();
//append input text value to UL
$("ul").append("<li>" + $("#title").val() + "</li>");
});
});
Click here to test if in JsFiddle

how to get value of these inputs using javascript or jquery

I was wondering if it possible to find an input by it's closest element?
real code:
<form method="post" action="">
<div class="rocket-form">
<fieldset>
<legend>Person Contacts</legend>
</fieldset>
<div class="rocket-label-element no-height">
<dt id="id-label"> </dt>
<dd id="id-element">
<input type="hidden" name="id" value="" readonly="readonly" id="id">
</dd>
</div>
<div class="rocket-label-element no-height"><dt id="vendor_id-label"> </dt>
<dd id="vendor_id-element">
<input type="hidden" name="vendor_id" value="" readonly="readonly" id="vendor_id">
</dd>
</div>
<div class="rocket-label-element">
<div id="firstname-label">
<label for="firstname" class="rocket-label optional">First name</label>
</div>
<div class="rocket-element">
<input type="text" name="firstname" id="firstname" value="any first name" maxlength="64" readonly="readonly">
</div>
</div>
<div class="rocket-label-element">
<div id="lastname-label">
<label for="lastname" class="rocket-label optional">Last name</label>
</div>
<div class="rocket-element">
<input type="text" name="lastname" id="lastname" value="any last name" maxlength="64" readonly="readonly">
</div>
</div>
<div class="rocket-label-element">
<div id="phone-label">
<label for="phone" class="rocket-label optional">Phone</label>
</div>
<div class="rocket-element">
<input type="text" name="phone" id="phone" value="0123456789" maxlength="32" readonly="readonly">
</div>
</div>
<div class="rocket-label-element">
<div id="email-label">
<label for="email" class="rocket-label optional">Email</label>
</div>
<div class="rocket-element">
<input type="text" name="email" id="email" value="name#someMail.com" maxlength="128" readonly="readonly">
</div>
</div>
</div>
</form>
I have this form, and I want to get the value of the inputs in variables..
I tried to use "vendor_id" in order to use closest() or next() or prev() but no luck..
so, any help?
You can use
var vendorId = $("#vendor_id").val();
to get the value of vendor_id.
Be sure to include the # which identifies it as an id.
If you want to get the values of all the inputs, you can use:
$("input, select, textarea").each(function(){
// Get value of inputs
});
If you have more than one form, you may use:
var formData = $(".rocket-form").closest("form").serialize();
Remember you will need to include jQuery with a script tag and you should wrap your code like so:
$(function() {
console.log( "ready!" );
});
This ensures the page is ready before your JavaScript executes.
you can try this
var form = $("#vendor_id").closest("form").get();
$("form :input").each(function(){
var input = $(this);
var AllInputValues= $(input).val();
alert (AllInputValues);
});
EDIT
var theVendform = $("#vendor_id").parent().closest("form").get();
alert(theVendform["0"][3].defaultValue);
alert(theVendform["0"][4].defaultValue);
alert(theVendform["0"][5].defaultValue);
alert(theVendform["0"][6].defaultValue);
Not sure if I completely understand what you are asking but what about
$('#vendor_id-element input').val()
You a class in all your inputs where you want to get value, and do de following js
Array.prototype.slice.apply(document.querySelector('.your-input-class')).forEach(function(el){
Console.log(el.value);
});
try this
var inputs = $('form').find('input');
//inputs is the array of your inputs and values can be accessed by:
var value1 = $(inputs[0]).val();
//or you can use for loop or forEach
for (var i = 0; i < inputs.length; i++) {
var currentValue = $(inputs[i]).val();
alert(currentValue);
}

Multi forms datas into array via Javascript

I have some forms like this:
<div class="well">
<form>
<span class="remove pull-right"><i class="fa fa-times pointer"></i></span>
<div class="form-group" style="margin:0">
<label for="image-link">Image Link</label>
<input type="text" name="image-link" value="" class="form-control" >
</div>
<div class="form-group" style="margin:0">
<label for="content">Content</label>
<textarea class="form-control" name="content" rows="10"></textarea>
</div>
<div class="form-group" style="margin:0">
<label for="author">Author</label>
<input type="text" name="author" value="" class="form-control" >
</div>
</form>
</div>
....
<div class="well">
<form>
<span class="remove pull-right"><i class="fa fa-times pointer"></i></span>
<div class="form-group" style="margin:0">
<label for="image-link">Image Link</label>
<input type="text" name="image-link" value="" class="form-control" >
</div>
<div class="form-group" style="margin:0">
<label for="content">Content</label>
<textarea class="form-control" name="content" rows="10"></textarea>
</div>
<div class="form-group" style="margin:0">
<label for="author">Author</label>
<input type="text" name="author" value="" class="form-control" >
</div>
</form>
</div>
The forms will be added more and more when I click the add button, so will have multi forms.
I want to submit multi datas into an json arrayjust looks like this:
"quotes":[
{"image":"image_link","content":"content","author:"author"}
{"image":"image_link","content":"content","author:"author"}
...
{"image":"image_link","content":"content","author:"author"}
]
which is an array will contain all of the forms' datas. And the amount of forms is not fixed. It will be changed when I click add button.
So how can I do that automatically.
Thank you so much!
You can iterate through all the form elements on the page by calling the following function:
function generateArrayData() {
var forms = document.querySelectorAll(".well form");
var quotes = [];
for(var i = 0; i < forms.length; i++) {
var form = forms[i];
quotes.push({
image: form.querySelector("input[name='image-link']").value,
content: form.querySelector("textarea").value,
author: form.querySelector("input[name='author']").value
})
}
return quotes;
}
The way this works is that querySelectorAll loads all of the form elements on the page within a div with the class .well. We then iterate through the elements from the previous query and use querySelector to pull out each individual element we'd like to extract.

Trying to get the total to generate from quantity and price

I've been working on this for a little longer then needed, but I can't find what is going wrong here. I think I've looked at it way too long. I need to get the items to add up after quantity is add to the form.
Here is my HTML
<div class="row-fluid container-cart">
<div class="span4">
<div class="thumbnail">
<img src="http://myurl.com/image.jpg" />
<div class="caption">
<h3 class="">Title</h3>
<p class="">Description</p>
<div class="row-fluid">
<div class="span6">
<p class="lead">
<span id="item-price">100</span>
<span class="price-integer">
<input type="hidden" value="100">
</span>
</p>
</div>
<div class="span6">
<span>Quantity</span>
<input type="text" name="" id="quantity" class="stored quantity" autocomplete="off" value="">
</div>
<div class="span6">
<input type="text" name="base-total" id="base-total" class="stored readonly base-total" value="" readonly>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="span6">
Total:
<span class="total-cart">
<input type="text" name="total-cart" id="total-cart" class="stored readonly" value="" disabled="disabled">
</span>
</div>
Here is my JS
$('.quantity').on('keyup', function() {
var sum = 0;
$(".container-cart").each(function(i,o){
total = parseInt($(o).find(".quantity input").val(), 10) * parseInt($(o).find(".price-integer input").val(), 10);
if(!isNaN(total) /*&& total.length!=0**/) {
$(o).find(".base-total").val(total);
sum += total;
}
});
$("#total-cart").val(sum);
});
Looks like you typed a wrong selector, it's the .quantity input, the .quantity is an input, so it won't have any children, maybe you want to mean the input.quantity which means finding the input having class quantity.
Demo.

Categories

Resources