Add to cart without refreshing using JavaScript - javascript

When I press the add to cart button, data should be inserted into the database and should be displayed immediately above the form without redirecting to the query page. In this code the first form is working correctly, but the next two forms which are duplicates of the first form are not working. The problem is that the next two forms, when submitted, get redirected to the query page. The index page code is:
<html>
<head>
<title>fetch</title>
</head>
<body>
<ul></ul>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<span id="result1"></span>
<script type="text/javascript" src="http://localhost/json/jquery.js"></script>
<script type="text/javascript" src="http://localhost/json/my_script.js"></script>
<script type="text/javascript" src="http://localhost/json/my_script2.js"></script>
</body>
</html>
The query code is:
<?php
include_once('http://loaclhost/json/conn.php');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO users VALUES('$name','$age')"))
echo "successfully";
else
echo "failed";
The JavaScript code is:
$("#sub").click(function(){
$.post($("#myform").attr("action"),$("#myform :input").serializeArray(), function(info){$("#result1").html(info); });
clearinput();
});
$("#myform").submit(function(){
return false;
});
function clearinput()
{
$("#myform :input").each(function(){
$(this).val('');
});
}

You are submitting form by id : $("#myform").submit(function(){}
and the issue here is that you have given same ids for all the three forms here, make sure that each form will have different id.
also Button ids should be unique

As #asim has mentioned duplicated ids are the problem.try following code.
working js fiddle.http://jsfiddle.net/gw84j7hg/. (Using id selecters)
Updated fiddle using class selecters http://jsfiddle.net/gw84j7hg/2/
Form Code.
<form action="userInfo.php" method="post" id="myform" class="formSelecterClass">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform2"
class="formSelecterClass" >
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub1">save</button>
</form>
<form action="userInfo.php" method="post" id="myform3"
class="formSelecterClass">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub2">save</button>
</form>
<span id="result1"></span>
JS Code
$(".formSubmitButtonClass").click(function(){
$.post($(".formSelecterClass").attr("action"),$(".formSelecterClass :input").serializeArray(), function(info){$("#result1").html(info); });
clearinput();
});
$(".formSelecterClass").submit(function(){
return false;
});
function clearinput()
{
$(".formSelecterClass :input").each(function(){
$(this).val('');
});
}

ID on single HTML files can not repeated. If repeated, the first ID will work out and rest IDs will be invalid. That's why $("#myform") will only apply to the first form.

Related

How to get all form fields except hidden and submit button in a dropdown

<form class="myform" id="myform">
First name:<br>
<input type="text" id="input_1" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" id="input_2 "name="lastname" value="Mouse">
<br><br>
Agree:<br>
<input type="radio" id="input_3 "name="agree" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
How can i get all form fields by name in a select/dropdown and return the id on selection?
You can use querySelectorAll on your form, and then just generator the dictionary you would need for your selector:
let selector_vals = {};
let input_select = $("#input_select");
$("#myform input:not([type=submit])").each(function(idx, elem) {
selector_vals[elem.name] = "#" + elem.id;
input_select.append(new Option(elem.name,"#" + elem.id));
});
console.log(selector_vals);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Form Items<br/>
<select id="input_select"></select>
<form class="myform" id="myform">
First name:<br>
<input type="text" id="input_1" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" id="input_2 "name="lastname" value="Mouse">
<br><br>
Agree:<br>
<input type="radio" id="input_3 "name="agree" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
Use the following commands -
For getting specific input fields of a form -
var p = $('input[type=text]')
Then on your dropdown element with ID as '#select' use -
$('#select').append($('<option></option>').val(p).html(p));
where 'p' is nothing but all the elements you got from jquery selector above.
Though I can not really help you more here. Please post the code and reframe your question.

how to get values from a form and put them into global variables

for example
this is our form
<form action="test1" method="GET" name="frm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit" >
</form>
and here I want to put the content of the values from the form and put them into global variables I've tried this code. But it doesn't display the content of "a"
<script>
var a=document.frm.lname.value;
console.log(a);
</script>
you access the form value and it returns the correct value.
your input fields are empty and your get an empty result.
assign an initial value to your form fields and you will get them.
<form action="test1" method="GET" name="frm">
First name: <input type="text" name="fname" value="sdfsd"><br>
Last name: <input type="text" name="lname" value="sdfsd"><br>
<input type="submit" value="Submit" >
</form>
if you want to get the value your user entered, run your
var a=document.frm.lname.value;
after an event like onsubmit event of your form
Look at the example below which logs the value of last name after a user clicks on submit button
var a=document.frm.lname;
function aFunction(){
console.log(a.value);
}
<form action="#" method="GET" name="frm" onsubmit="aFunction()" >
First name: <input type="text" name="fname" ><br>
Last name: <input type="text" name="lname" ><br>
<input type="submit" value="Submit" >
</form>

Add multiple fields to form

I would like to add a function that generates multiple fields to my form.
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
How can I do this?
https://jsfiddle.net/374cxt5s/
Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.
I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.
CodePen Example
http://codepen.io/anon/pen/yeVRgw
The Basic HTML Setup
So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1
<form action="form_sent.php" method="POST">
<input type="hidden" name="contacts" id="contacts" value="1">
<div class="form-contacts-container">
<div class="form-contact" id="form-contact-1">
<input type="text" name="name-1" id="name-1" placeholder="Name">
<input type="text" name="email-1" id="email-1" placeholder="E-mail">
<input type="text" name="phone-1" id="phone-1" placeholder="Phone">
</div>
<!-- We'll be adding additional inputs here -->
</div>
<div class="form-contacts-add">
<input type="button" value="Add More Fields" id="add-fields">
</div>
<div class="form-contacts-submit">
<input type="submit" name="submit" id="submit" value="Submit">
</div>
</form>
The JavaScript
This assumes you are using jQuery, so ensure that this is in your <head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.
<script type="text/javascript">
var total = 1; // Our default for how many contacts we have
$( document ).on( 'click', '#add-fields', function() {
var addBlockId = total = total + 1;
var addBlock = document.createElement('div');
$(addBlock).addClass('form-contact');
$(addBlock).attr('id','form-contact-' + addBlockId);
var inputName = document.createElement('input');
$(inputName).attr('type','text');
$(inputName).attr('name','name-' + addBlockId);
$(inputName).attr('id','name-' + addBlockId);
$(inputName).attr('placeholder','Name');
$(inputName).appendTo($(addBlock));
var inputEmail = document.createElement('input');
$(inputEmail).attr('type','text');
$(inputEmail).attr('name','email-' + addBlockId);
$(inputEmail).attr('id','email-' + addBlockId);
$(inputEmail).attr('placeholder','E-mail');
$(inputEmail).appendTo($(addBlock));
var inputPhone = document.createElement('input');
$(inputPhone).attr('type','text');
$(inputPhone).attr('name','phone-' + addBlockId);
$(inputPhone).attr('id','phone-' + addBlockId);
$(inputPhone).attr('placeholder','Phone');
$(inputPhone).appendTo($(addBlock));
$(addBlock).appendTo($('.form-contacts-container'));
$('#contacts').val(total);
});
</script>
Processing your Form
The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:
$total = $_POST['contacts'];
$contacts = array();
for( $i = 1; $i < $total; $i++ ) {
$this_contact = $array(
'Name' => $_POST['name-' . $i],
'Email' => $_POST['email-' . $i],
'Phone' => $_POST['phone-' . $i]
);
array_push($contacts, $this_contact);
}
var_dump( $contacts );
try something like this :
(function() {
var button=document.getElementById("add-user");
button.addEventListener('click', function(event) {
event.preventDefault();
var cln = document.getElementsByClassName("user")[0].cloneNode(true);
document.getElementById("users").insertBefore(cln,this);
return false;
});
})();
<form id="users" action="form_sent.php" method="post">
<div class="user">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id='add-user'>Add more fields</button><br><br>
<input type="submit">
</form>
https://jsfiddle.net/9955n4fo/
It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html
<form action="form_sent.php" method="post">
<div id="fields">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
and then your javascript can be completed as so
$(function() {
$('button').click(function() { addFields(); });
});
function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
<input name='phone' type='text' placeholder='Phone'><br>
<input name='email' type='text' placeholder='E-Mail'><br><br>";
$('#fields').append(html);
}
You need to implement jQuery to change the HTMLs DOM.
So, you add this in your <head></head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
You need to modify your HTML like this:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>
Then you need to use this jQuery code:
<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>
This is the end!! :)
Try This :
Jquery append() function seems to sort out your answer
HTML Code should be as follow :
<form action="form_sent.php" method="post">
<div class = 'xyz'>
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
you JS should be as follow :
$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});
This is how I would solve it.
HTML:
<form action="form_sent.php" method="post">
<div id="inputHolder">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id="addMoreFields">Add more fields</button><br><br>
<input type="submit">
</form>
JS:
$( document ).ready(function() {
$("#addMoreFields").click(function(event) {
event.preventDefault();
$("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
$("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
$("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
});
});
https://jsfiddle.net/r71odb7t/
First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.
$(function() {
var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
$('form > button').on('click', function(e) {
e.preventDefault();
$(this).before(inputs.clone());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>

How to submit form using JavaScript and redirect to a URL?

How to submit form using JavaScript and redirect to a URL ?
<form name="f1" method="get" action="aaa.php">
name : <input type="text" name="value_1" value=""/><br>
age: <input type="text" name="value_2" value=""/>
<input type="submit" name="submit" value="send"/>
</form>
please see image in this link:
http://image.ohozaa.com/i/4d0/zCzQIH.jpg
after press submit button , i want to redirect page to www.example.com/aaa/robert/21
How can i do that ?
Try this with html code
<form name="f1" method="get" action="aaa.php">
name : <input type="text" id="value_1" name="value_1" value=""/><br>
age: <input type="text" id="value_2" name="value_2" value=""/>
<input type="button" name="submit" onclick="checkredirect()" value="send"/>
And javascript
<script type="text/javascript">
function checkredirect(){
var value_1 = $('#value_1').val();
var value_2 = $('#value_2').val();
window.location = 'http://www.example.com/'+value_1+'/'+value_2;
return false;
}
</script>
Don't forget to add jQuery library
Maybe something like this:
HTML:
<form id="f1" class="js-redirect" method="get" action="aaa.php">
name : <input type="text" name="value_1" id="value_1" value=""/><br>
age: <input type="text" name="value_2" id="value_2" value=""/>
<input type="submit" name="submit" value="send"/>
</form>
N.B.: name attribute in form tags is deprecated, use id attribute. Input, select and textarea tags should have ids as well.
JS:
$('.js-redirect').on('submit', function() {
var newUrl = this.action.replace('.php', '/' + $('#value_1').val() + '/' + $('#value_2').val());
this.action = newUrl;
})
set header in php file
$dynamic = $_GET['value_1'];
$id =$_GET['value_2'];
header('location:www.example.com/aaa/'.$dynamic.'/'.$id);
Try this function on click button
function myFunction() {
document.getElementById("myForm").submit();
}

How can i make a simple form to calculate quantity x's a fixed rate?

Ok, I have a good understanding of how javascript works, but not how to implement it. I have a simple form that needs to calculate on the fly the price of x number of tickets at 75.00 each. Let's say form id is quantity & total, with 75.00 being a rate. What would be the script to execute this and where should I add it.
The pertinent HTML is this:
<form id="docContainer" enctype="multipart/form-data" method="POST" action=""
novalidate="novalidate" data-form="preview">
<label id="item4_label_0" ># of Tickets</label>
<input type="text" id="quantity" maxlength="254" data-hint="" name="quantity" required/>
<label id="item13_label_0">Price Per Ticket</label>
<input name="item_price" type="text" id="item_price" placeholder="75.00"
maxlength="254" readonly data-hint="75.00"/>
<label id="item14_label_0" >Total</label>
<input name="total_price" type="text" id="total_price" maxlength="254" readonly/>
<input type="submit" class="fb-button-special" id="fb-submit-button" value="Submit" />
</form>
Your inputs don't have ids so I've used their names. This is how you would do it with jQuery. I've forgotten how to write old school javascript, perhaps someone else can add to this.
<script src="jquery.js"></script>
<script>
$(function(){
$('input[name="quantity"]').on('change keyup', function(){
$('input[name="total_price"]').val($(this).val() * $('input[name="item_price"]').val());
});
});
</script>
goes before
</body>
Edit: Added the necessary stuff for jQuery, but this can be done with regular js.
<html>
<head>
<script>
window.onload = function() {
var calculSumToString = function calculSumToString() {
totalField.value = (qtyField.value * itemPriceField.value).toFixed(2) + " $";
};
var totalField = document.getElementById('total_price');
var qtyField = document.getElementById('quantity');
var itemPriceField = document.getElementById('item_price');
qtyField.onkeyup = calculSumToString;
itemPriceField.onkeyup = calculSumToString;
};
</script>
</head>
<body>
<form id="docContainer" enctype="multipart/form-data" method="POST" action=""
novalidate="novalidate" data-form="preview">
<label id="item4_label_0" ># of Tickets</label>
<input type="text" id="quantity" maxlength="254" data-hint="" name="quantity" required/>
<label id="item13_label_0">Price Per Ticket</label>
<input name="item_price" type="text" id="item_price" value="75.00"
maxlength="254" readonly data-hint="75.00"/>
<label id="item14_label_0" >Total</label>
<input name="total_price" type="text" id="total_price" maxlength="254" readonly/>
<input type="submit" class="fb-button-special" id="fb-submit-button" value="Submit" />
</form>
</body>
</html>

Categories

Resources