I am sorry for the weird title of the question.
I am trying to process a form using jQuery ajax which contain a file.
This is what I am trying to use..
<script>
var file_data = $('#qfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);//
var data = $(this).serialize();
// Here is the problem. I sucessfully sent the file alone but I want to
//send all the form input values using serialize() and add formData too
</script>
I want to send the file and also all the input serialize()
Here is my ajax part...
<script>
$.ajax({
type : 'POST',
url : 'ajax/ajax-reg.php',
data : form_data,
processData: false,
contentType: false,
</script>
I want to send all the form input values using serialize() and add formData too
In this case serialize() won't help you, but there is a better way. Simply provide the form DOMElement to the FormData() constructor. Then all the data from the form fields (including the images) will be placed in to the FormData object. Try this:
var form_data = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url: 'ajax/ajax-reg.php',
data: form_data,
processData: false,
contentType: false,
success: function() {
// handle response here...
}
});
Using jQuery, you also can try something like this:
var postData = new FormData($('form')[0]);
postData.append("In", $("input[name=In]").val()); // usual input
postData.append("Txt", $("textarea[name=Txt]").text()); // textarea
postData.append("File", $("input[name=File]")[0].files[0]); // file
$.post('ajax/ajax-reg.php', postData);
I use jquery (but this can be easily done via vanilla javascript too) to create a hidden text input after the file input. I then set the name of the new text input as the id of the file input it's associated with and set it's value (when a file is selected) to the filename. You can then use $('form').serializeArray(); and return the name:value pairs of the hidden inputs that correspond to the file inputs.
$(document).ready(function(){
// Dynamically create hidden text inputs for the file inputs' data
// (create dynamically to avoid having re-write your entire html file)
$('input:file').each( function(){
$(this).after('<input type="text" readonly name="' + $(this).attr("id").replace("_", " ") + '" hidden value=""/>');
});
// When the user selects a file to be uploaded...
$('input:file').change( function(){
// If a file is selected set the text input value as the filename
if($(this).get(0).files.length !== 0){
$(this).next('input:text').val($(this).get(0).files[0].name);
}
});
$("form").submit( function(e){
e.preventDefault();
//Clear previous data from results div
$('#results').text("");
// Serialize the form data
var x = $('form').serializeArray();
// Iterate through the array results and append
// the data to the results div
$.each(x, function(i, field) {
var result = '<span class="left">' + field.name + ' : </span>';
result += '<span class="right">' + field.value + '</span><br>';
$('#results').append(result);
});
});
});
form {
display: inline-block;
left: 0;
width: auto;
max-width: 40%;
margin-left: 0;
padding: 0;
}
div.left, div.right, span.left, span.right {
display:block;
position: relative;
width: 40%;
}
.rad { font-size: 14px; }
.left { float: left; }
.right { float: right; }
#results {
display: inline-block;
position: relative;
width: auto;
min-width: 40%;
line-height: 23px;
}
#results .left {
color: green;
text-align: right;
}
#results .right {
color: blue;
text-align: left;
margin-right: 20px;
}
.clearfix { clear: both; }
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<div class="left">
<label class="right" for="name">Name:</label><br>
<label class="right" for="gender">Gender:</label><br>
<label class="right" for="file1">1st Pic:</label><br>
<label class="right" for="file2">2nd Pic:</label><br>
<label class="right" for="file3">3rd Pic:</label><br>
<label class="right" for="file4">4th Pic:</label><br>
</div>
<div class="right">
<input class="left" type="text" name="Name" ><br>
<select class="left" name="Gender">
<option selected></option>
<option>Unspecified</option>
<option>Female</option>
<option>Male</option>
</select><br>
<input class="left" type="file" accept="image/*" id="File_1"><br>
<input class="left" type="file" accept="image/*" id="File_2"><br>
<input class="left" type="file" accept="image/*" id="File_3"><br>
<input class="left" type="file" accept="image/*" id="File_4"><br>
</div>
</form>
<div id="results" class="right"></div>
<div class="clearfix"></div>
<input form="myForm" type="submit" id="submit" value="Serialize Form" />
<input form="myForm" type="reset" value="Reset Form" onClick="this.form.reset()" />
</body>
Related
I'm trying to validate my form, but I can't seem to capture my form values! At a loss as to where to go now. I've tried a combination of jQuery and Javascript. Here's a snippet of my code.
HTML:
<form action="#" name="application-form" method="post" enctype="multipart/form-data">
<ul>
<li class="input-row">
<label for="app-resume">Resume</label>
<input type="file" id="app-resume" name="resume" />
</li>
<li class="input-row">
<label for="app-name">Full Name</label>
<input type="text" id="app-name" name="fname" />
</li>
<li class="input-row">
<label for="app-pnum">Phone Number</label>
<input type="number" id="app-pnum" name="pnum" />
</li>
<li class="input-row">
<label for="app-email">Email</label>
<input type="email" id="app-email" name="email" />
</li>
<li class="input-row">
<label for="app-info">Additional Information</label>
<textarea type="text" id="app-info" name="info"></textarea>
</li>
</ul>
<div class="btn-mssg-container">
<button type="submit" name="sbt-btn" id="sbt-btn">apply</button>
<p id="sbt-mssg" class="hidden">Thank you for applying.</p>
</div>
</form>
JS:
var myForm = document.forms["application-form"];
myForm.onsubmit = processForm;
function processForm(){
console.log(myForm.fname.value);
}
I've also tried:
function processForm(){
var inName = $("#app-name").val();
console.log(inName);
}
I'm getting nothing! Someone please put me out of my misery.
The first attempt at getting form values is called HTMLFormControlsCollection
1. Reference the form:
var FoRm = document.forms.FormID_or_NAME
OR
var FoRm = document.forms["FormID_or_NAME"]
OR
var FoRm = document.forms[0]
The last one using index number zero in bracket notation will work if the target <form> is the first on the page or the only <form> on the page.
2. Collect all of the form's form controls into an array-like object:
var formControlS = FoRm.elements
Step 2. was the crucial step that you were missing.
3. Now you can reference and get values from any form control under that specific <form>:
var foRmC = formControlS.FormControlID_or_NAME.value
OR
var foRmC = formControlS["FormControlID_or_NAME"].value
OR
var foRmC = formControlS[0].value
Details are commented in Demo
This localStorage feature cannot work in a Stack Snippet due to security measures. If you want to review a fully functional demo, then visit Plunk
Demo
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
justify-content: space-around;
flex-wrap: nowrap;
}
iframe {
display: inline-table;
max-width: 40%;
height: 100vh
}
#app0 {
max-width: 60%;
margin: 0 0 5px 15px;
}
label {
display: inline-block
}
/* Area code - Central Office code */
[type=number] {
width: 5ch
}
/* The last 4 digits - Station code */
label [type=number]:last-of-type {
width: 6ch
}
[type=email] {
width: 26ch
}
.hidden {
opacity: 0
}
#msg {
height: 60px;
overflow-x: hidden;
overflow-y: scroll;
border: 3px inset grey;
padding: 10px;
display: block;
}
</style>
</head>
<body>
<main id='main'>
<!-- On submit, form sends to a real test server
|| The target attribute value is the name of
|| iframe#display. Whenver data is tested thru
|| this server, it will send a response later.
-->
<form action="https://httpbin.org/post" id="app0" method="post" enctype="multipart/form-data" target='display'>
<fieldset id='set0'>
<label for="file0">Resume</label>
<input type="file" id="file0" name="resume">
<br>
<br>
<label for="name0">Full Name</label>
<input type="text" id="name0" name="name">
<br>
<br>
<label>Phone Number
<input type="number" id="area0" name="phone" min='100' max='999'>
<input type="number" id="cent0" name="phone" min='100' max='999'>
<input type="number" id="stat0" name="phone" min='0000' max='9999'>
</label>
<br>
<br>
<label for="mail0">Email</label>
<input type="email" id="mail0" name="mail">
<br>
<br>
<label for="info0">Additional Information</label>
<br>
<textarea id="info0" name="info" cols='28'></textarea>
<br>
</fieldset>
<fieldset id="set1">
<button id='btn' type="button" class=''>Process</button>
<button id='sub' type='submit' class='hidden'>Transfer</button>
</fieldset>
<output id="msg"></output>
</form>
<iframe name='display' src='about:blank' width='60%'></iframe>
</main>
<script>
/* The interface used to refer to form controls
|| is called HTMLFormControlsCollection
*/ // Reference the form
var xApp = document.forms.app0;
/*\\\\\\\\\\/IMPORTANT\//////////
This is the part that was in error
In order to refer to any form controls
of the referenced form, you must
collect them in an array-like object
using the .elements proerty //////*/
var xCon = xApp.elements;
// Then from the .elements reference by id
// A click event on a button--processForm
// is called
xCon.btn.onclick = processForm;
/* This function will gather all form values
|| into an array.
|| Then it stores that array in localStorage
|| Displays the data then hides the "Process"
|| button and reveals the "Transfer" button
*/
function processForm(e) {
var qty = xCon.length;
var data = [];
for (let i = 0; i < qty; i++) {
var formControl = xCon[i].value;
if (formControl !== null || formControl !== undefined || formControl !== "") {
data.push(formControl);
}
}
localStorage.setItem("data", JSON.stringify(data));
var stored = JSON.parse(localStorage.getItem("data"));
appX();
xApp.onsubmit = appX;
function appX(e) {
xCon.msg.value = stored;
xCon.btn.classList.toggle('hidden');
xCon.sub.classList.toggle('hidden');
}
}
/* Once the "Transfer" button is clicked, the
|| data is sent to the test server and the
|| test server responds back. The response is
|| captured and displayed in the iframe to the
|| right
*/
</script>
</body>
</html>
I am trying to make a calculator program in php code.
I made it using html and javascript, but I've been told to use php code for the logical part.
Is there any way we can take more than one input from a textbox, in a php form ?
Yes, you can easily use multiple inputs in a form, by giving them different names and accessing them through $_REQUEST['input_name'].
In this example, what I am doing is taking the selected checkboxes from the popup and putting them into the text input field in the main form as a comma-separated list.
HTML
<input type="text" id="entry-r1" placeholder="place" tabindex="1">
<a class="show-lookup button" href="#" id="popup-r1" tabindex="2"><i class="fa fa-search"></i></a>
<div class="overlay"> </div>
<div class="lookup-multiselect" id="lookup-r1">
<a class="button close-button right">x</a>
<form action="" id="form-r1" name="form-r1" method="post">
<input class="checkall" id="checkall" type="checkbox">
<label for="checkall" class="narrow">Select all</label>
<p class="category" id="checkboxes-r1"><strong>Select...</strong><br>
<input class="js-popup-focus" type="checkbox" name="place" id="antwerp" value="Antwerp" tabindex="3"> <label for="antwerp">Antwerp</label><br>
<input type="checkbox" name="place" id="berlin" value="Berlin" tabindex="3"> <label for="berlin">Berlin</label><br>
<input type="checkbox" name="place" id="cairo" value="Cairo" tabindex="3"> <label for="cairo">Cairo</label><br>
<input type="checkbox" name="place" id="duss" value="Düsseldorf" tabindex="3"> <label for="duss">Düsseldorf</label><br>
</p>
</form>
Use selected
</div>
CSS
.overlay {
display: none;
position: fixed;
text-align: center;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.7;
background: #333;
}
.lookup-popup, .lookup-multiselect {
padding: 0.5em;
display: none;
z-index: 99999;
background-color: #fff;
position: absolute;
top: 5em;
left: 25%;
width: 20%;
}
jQuery
$(document).ready(function ()
{
/* get id of form to work with */
$('.show-lookup').click(function()
{
var pairedId = $(this).attr('id').split('-');
var lookupToDisplay = '#lookup-' + pairedId[1];
$('.overlay').show();
$(lookupToDisplay).show();
$('.js-popup-focus').focus();
});
/* put value selected in lookup into field in main form */
$('.lookup-popup input').on('change', function()
{
var fieldname = $(this).attr('name');
var pairedId = $(this).parent().attr('id').split('-');
var selOption = $('input[name='+fieldname+']:checked').val();
$("#entry-"+pairedId[1]).val(selOption);
});
/* for checkbox version, append selected values to field in main form */
$('.lookup-multiselect input').on('change', function()
{
var pairedId = $(this).parent().attr('id').split('-');
//event.preventDefault();
var selOptions = $(".category input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
//console.log(selOptions);
var selectedString = selOptions.toString();
$("#entry-"+pairedId[1]).val(selOptions);
});
$('.close-button').click(function()
{
$(this).parent().hide();
var pairedId = $(this).parent().attr('id').split('-');
$('.overlay').hide();
$("#entry-"+pairedId[1]).focus();
});
});
I want to send form data using ajax done by serialize method but input type text and email is serialized in array but input type file not serialize in array
<form role="form" action="javascript:;" id="myform" enctype = "multipart/form-data" method = "post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="email">Photo:</label>
<input type="file" name="userPhoto" id="userPhoto" class="form-control" />
</div>
<button type="submit" class="btn btn-default submit_add" id="enter">Submit</button>
</form>
And Ajax Code
$('.submit_add').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
console.log(data); return false;
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: data,
dataType: 'json',
success: function(data) {
if (data.success == true ) {
window.location.href = '/';
} else {
alert('Error : There is something wrong.');
}
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err);
}
})
});
Console response
name=manish+prajapati&email=kumar%40manish.com
You should try this:
var data = new FormData($("#myform")[0]);
and set:
processData: false,
contentType: false,
See more here: http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
I use jquery (but this can be easily done via vanilla javascript too) to create a hidden text input after the file input. I then set the name of the new text input as the id of the file input it's associated with and set it's value (when a file is selected) to the filename. You can then use $('form').serializeArray(); and return the name:value pairs of the hidden inputs that correspond to the file inputs.
/* The javascript/jquery */
$(document).ready(function(){
// Dynamically create hidden text inputs for the file inputs' data
// (create dynamically to avoid having re-write your entire html file)
$('input:file').each( function(){
$(this).after('<input type="text" readonly name="' + $(this).attr("id").replace("_", " ") + '" hidden value=""/>');
});
// When the user selects a file to be uploaded...
$('input:file').change( function(){
// If a file is selected set the text input value as the filename
if($(this).get(0).files.length !== 0){
$(this).next('input:text').val($(this).get(0).files[0].name);
}
});
$("form").submit( function(e){
e.preventDefault();
//Clear previous data from results div
$('#results').text("");
// Serialize the form data
var x = $('form').serializeArray();
// Iterate through the array results and append
// the data to the results div
$.each(x, function(i, field) {
var result = '<span class="left">' + field.name + ' : </span>';
result += '<span class="right">' + field.value + '</span><br>';
$('#results').append(result);
});
});
});
/* The .css */
form {
display: inline-block;
left: 0;
width: auto;
max-width: 40%;
margin-left: 0;
padding: 0;
}
div.left, div.right, span.left, span.right {
display:block;
position: relative;
width: 40%;
}
.rad { font-size: 14px; }
.left { float: left; }
.right { float: right; }
#results {
display: inline-block;
position: relative;
width: auto;
min-width: 40%;
line-height: 23px;
}
#results .left {
color: green;
text-align: right;
}
#results .right {
color: blue;
text-align: left;
margin-right: 20px;
}
.clearfix { clear: both; }
<!-- The HTML -->
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<div class="left">
<label class="right" for="name">Name:</label><br>
<label class="right" for="gender">Gender:</label><br>
<label class="right" for="file1">1st Pic:</label><br>
<label class="right" for="file2">2nd Pic:</label><br>
<label class="right" for="file3">3rd Pic:</label><br>
<label class="right" for="file4">4th Pic:</label><br>
</div>
<div class="right">
<input class="left" type="text" name="Name" ><br>
<select class="left" name="Gender">
<option selected></option>
<option>Unspecified</option>
<option>Female</option>
<option>Male</option>
</select><br>
<input class="left" type="file" accept="image/*" id="File_1"><br>
<input class="left" type="file" accept="image/*" id="File_2"><br>
<input class="left" type="file" accept="image/*" id="File_3"><br>
<input class="left" type="file" accept="image/*" id="File_4"><br>
</div>
</form>
<div id="results" class="right"></div>
<div class="clearfix"></div>
<input form="myForm" type="submit" id="submit" value="Serialize Form" />
<input form="myForm" type="reset" value="Reset Form" onClick="this.form.reset()" />
</body>
I want to change background of checkbox without using jQuery (if is that possible of course), because I'm not familiar with that library.
HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" class="cbox" />
</form>
JS:
function checkbox(){
var checkbox = document.getElementByClass('cbox');
if(document.getElementById('cbox').checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}
You are mixing class names and ID's. Try this.
HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" id="cbox" />
</form>
JS:
function checkbox(){
var checkbox = document.getElementById('cbox');
if(checkbox.checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}
How about a pure CSS solution without any need to use images: http://jsfiddle.net/7qcE9/1/.
HTML:
<form name="checkBox">
<input type="checkbox" id = "checkbox1" />
<label for = "checkbox1"></label>
</form>
CSS:
form > input[type = "checkbox"] {
display: none;
}
form > label {
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #000;
border-radius: 3px;
font-size: 20px;
text-align: center;
cursor: pointer;
}
form > input[type = "checkbox"]:checked + label:before {
content:'\2714';
}
You can pass a reference to the checkbox using this in the inline handler as follows:
html
<form name="checkBox">
<input onchange="checkbox(this)" type="checkbox" class="cbox" />
</form>
js
function checkbox(elm){ // elm now refers to the checkbox
if(elm.checked === true){
elm.style.background = "url('uncheck.png')";
}else{
elm.style.background = "url('check.png')";
}
}
So that you can use the function for n number of elements.
I currently have the following functionality (see link: http://jsfiddle.net/eUDRV/3/) and instead of appending the selected values back to the original list, I'd like to return them to the spot that they were previously in. My values are in alphabetical order. I know that I need to index the spot of each value but I'm not quite sure how to accomplish this. Any help would be appreciated, thanks.
Here's my HTML code:
<section class="container">
<div>
<select id="leftValues" size="5" multiple></select>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" size="4" multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div>
<input type="text" id="txtRight" />
</div>
</div>
Javascript code:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$("#rightValues").append(selectedItem);
});
$("#rightValues").change(function () {
var selectedItem = $("#rightValues option:selected");
$("#txtRight").val(selectedItem.text());
});
CSS code:
SELECT, INPUT[type="text"] {
width: 160px;
box-sizing: border-box;
}
SECTION {
padding: 8px;
background-color: #f0f0f0;
overflow: auto;
}
SECTION > DIV {
float: left;
padding: 4px;
}
SECTION > DIV + DIV {
width: 40px;
text-align: center;
}
You could assign each option within your select a value attribute that corresponds to the text and then in your code:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
You could have it look up the value of the selected item, compare it with anything in the list and place it in the appropriate index in that list and do the same for the code which moves it back into the right hand list.
You could also strip the innerHTML value of the option instead if you didn't want to add the value attribute.