I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";
Related
I have 2 image upload forms, when one is uploaded it should show a preview of the uploaded image. However, when I upload an image in one of the input forms, both forms display a preview of the last uploaded image. How do I make the preview only appear on the uploaded form?
Here's my code :
<div class="container">
<form action="save.php" method="post" enctype="multipart/form-data">
<!-- rows -->
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview1" class="img-thumbnail1">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img1" class="file1" id="file1">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image1" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview2" class="img-thumbnail2">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img2" class="file2" id="file2">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image2" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="btn_save" class="btn btn-success">Save</button>
</form>
</div>
<script>
$(document).on("click", "#select_image1", function() {
var file = $(this).parents().find(".file1");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName1 = e.target.files[0].name;
$("#file1").val(fileName1);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview1").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(e.target.files[0]);
});
// 2
$(document).on("click", "#select_image2", function() {
var file2 = $(this).parents().find(".file2");
file2.trigger("click");
});
$('input[type="file"]').change(function(el) {
var fileName2 = el.target.files[0].name;
$("#file2").val(fileName2);
var reader2 = new FileReader();
reader2.onload = function(el) {
// get loaded data and render thumbnail.
document.getElementById("preview2").src = el.target.result;
};
// read the image file as a data URL.
reader2.readAsDataURL(el.target.files[0]);
});
</script>
I've tried changing the script code, but it doesn't work. Please help. Thank you.
I am having a form in which I am saving 2 files and a field. The problem I am facing is every time I click the submit button the form is getting submitted. Although The text field is resetting, the file still consists the value of previous record. How to reset the file here once the form is submitted.
HTML
<form id="formOrder" autocomplete="off" method="POST" enctype="multipart/form-data">
<div class="row row-sm">
<div class="col-lg-8">
<div class="row row-sm">
<div class="col-lg-6">
<div class="input-group mb-4">
<input aria-label="Invoice ID" id="invoiceId" name="invoiceId" class="form-control" placeholder="Invoice ID" type="text">
<span class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div>
<div class="input-group mb-3">
<div class="input-group file-browser">
<input id="imageLabel" type="text" class="form-control browse-file" placeholder="Select Order Image" readonly>
<label class="input-group-btn">
<span class="btn btn-default">
Browse <input type="file" name="image[]" id="orderImage" style="display: none;" multiple>
</span>
</label>
</div>
<div class="orderImagePreview">
</div>
</div>
</div>
</div>
</div>
<div class="form-group mb-0 mt-3 justify-content-end">
<div>
<input type="submit" id="_add" name="_add" class="btn btn-primary btn-size" value="Add"/>
</div>
</div>
</form>
JQUERY
// BUTTON CLICK SUBMISSION
$(document).ready(function(e){
$("#_add").click(function(){
$("#formOrder").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../order/add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#formOrder')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
$('.orderImagePreview').empty();
document.getElementById('#orderImage').value= null; //TO MAKE THE IMAGE LABEL EMPTY
}else{
$('.statusMsg').html(alert(response.message));
}
$('#formOrder').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
});
// Multiple images preview in browser
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#orderImage').on('change', function() {
imagesPreview(this, 'div.orderImagePreview');
$( 'div.orderImagePreview' ).empty();
});
});
$('#orderImage').on("change", function(){
var input = document.getElementById ("imageLabel");
var imageCount = $(this)[0].files.length;
if(imageCount > 0){
input.placeholder = imageCount+" Image Attached";
}else{
input.placeholder = "Select Order Image";
}
});
Where I am making the mistake? The debugging should be to reset the form with file or the method of form submission? Thanks in Advance.
$("#_add").click(function(){
$("#formOrder").on('submit', function(e){
Just create a submit handler when the document loads.
Don't add it when the button is clicked.
I am trying to make a form for editing a product but if I upload a image the image can not be found by my PHP code it throws this error:
Notice: Undefined index: image in C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 10
Notice: Undefined index: image in
C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 11
Upload failed
This is my Code:
$db = new Database;
$product = mysqli_fetch_array($db->db_query("SELECT * FROM product WHERE ID = '" . $_GET['id'] . "'"));
$image = mysqli_fetch_array($db->db_query("SELECT name,src FROM images WHERE id =".$product['image-id']));
$category = $db->db_query("SELECT * FROM category");
$productcat = mysqli_fetch_array($db->db_query("SELECT `cat-id` FROM `category-product` WHERE `prod-id` = ".$product['ID']));
if(isset($_POST['submit'])){
$uploaddir = '/../../../src/images/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
}
?>
<!--page content-->
<div class="col-9">
<div style="background-color:#c6c8ca !important; color:black" class="jumbotron">
<div class="container">
<form class="well form-horizontal" action="producteditor.php?id=<?= $_GET['id'] ?>" method="post"
id="producteditor_form">
<fieldset>
<!-- Upload image input-->
<input id="upload" name="image" type="file" onchange="readURL(this);"
class="form-control border-0" accept="image/*" hidden>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i
class="fa fa-cloud-upload mr-2 text-muted"></i><small
class="text-uppercase font-weight-bold text-muted"> Kies
bestand</small></label>
</div>
<!-- Uploaded image area-->
<div class="image-area mt-4"><img id="imageResult"
src="../../../<?=$image['src']?>" alt="<?=$image['name']?>"
class="img-fluid rounded shadow-sm mx-auto d-block">
</div>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="text-center">
<button class="btn btn-lg btn-success form-spacing-top"
name="submit">Opslaan</button>
</div>
</div>
</fieldset>
</form>
</div>
</div><!-- /.container -->
</div>
</div>
<div class="col"></div>
</div>
</div>
<script>
/* ==========================================
SHOW UPLOADED IMAGE
* ========================================== */
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function() {
$('#upload').on('change', function() {
readURL(input);
fetch(url, {
method: 'POST',
body: readURL(input)
});
});
});
/* ==========================================
SHOW UPLOADED IMAGE NAME
* ========================================== */
var input = document.getElementById('upload');
var infoArea = document.getElementById('upload-label');
input.addEventListener('change', showFileName);
function showFileName(event) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
</script>
Your <form> needs to have the enctype='multipart/form-data' attribute.
See: What does enctype='multipart/form-data' mean?
I am trying to call a function in my javascript file from an onclick event in html. This code works perfectly in Google Chrome but does not work in Safari as it redirects to the same page and empties the form, without redirecting to the home page of my website.
Here is my HTML code:
<!-- Login or subscribe form-->
<div class="py-5">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card text-white p-5 bg-primary signUpBoxStyle">
<div class="card-body">
<h1 class="mb-4">Effettua il login o iscriviti</h1>
<form>
<div class="form-group"> <label>Indirizzo email</label>
<input type="email" class="form-control" placeholder="Inserisci email" id="email"> </div>
<div class="form-group"> <label>Password</label>
<input type="password" class="form-control" placeholder="Password" id="password"> </div>
<input type="button" class="btn btn-light text-primary btn-sm" value="Accedi" onclick="loginFunction()">
<input type="button" class="btn btn-light text-primary btn-sm" value="Crea un Account" onclick="signupFunction()"> </form>
</div>
</div>
</div>
</div>
</div>
</div>
And this is my JavaScript
function loginFunction() {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
})
};
You might need to tell the browser not to carry out the default behavior of that element via preventDefault(). This SO answer give a little more detail.
Having an if statement to check the attribute is not that scalable but it may be possible that you pass the function call as a parameter.
let buttons = document.querySelectorAll('input[type=button]')
buttons.forEach(button => {
button.addEventListener('click', e => {
let func = e.target.getAttribute('data-call')
if (func === 'login') {
loginFunction()
} else if (func === 'signup') {
signupFunction()
}
})
})
let loginFunction = () => {
console.log('loginFunction')
}
let signupFunction = () => {
console.log('signupFunction')
}
<form>
<input type="button" value="Accedi" data-call="login">
<input type="button" value="Crea un Account" data-call="signup">
</form>
I'm using Ajax to add (and remove) multiple fields in a form, and then submitting them to mongoose to save them. Unfortunatelly I'm able to retrieve and save only 1 array, missing completely the dinamically added ones.
HTML: Here's a form with a form-group visible, where I inizialise the array using name attributes,and a form-group template that I dinamically populate with Ajax
<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}">
<section class="panel">
<div class="panel-body">
<div class="form-group" data-option-index="1">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="options[0][optionType]">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionValue]">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionPrice]">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="form-group hide" id="optionTemplate">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="optionType">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionValue">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionPrice">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<footer class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</footer>
</section>
</form>
AJAX: I use this to add rows or remove them, each with 3 inputs. Before submitting the form I use .serialize() to get the arrays by their names
$(document).ready(function() {
var optionIndex = $(".form-group[data-option-index]").length;
$('#productAdd').submit(function(e) { // add product submit function
e.preventDefault();
$(this).ajaxSubmit({
contentType: 'application/json',
data: $('form[name="productAdd"]').serialize(),
error: function(xhr) {
console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText);
},
success: function(response) {
if (typeof response.redirect === 'string')
window.location = response.redirect;
}
});
return false;
})
// Add button click handler
.on('click', '.addButton', function() {
optionIndex++;
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-option-index', optionIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
.find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end()
.find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end();
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-option-index');
// Remove fields
$row.find('[name="options[' + index + '].title"]').remove();
$row.find('[name="options[' + index + '].isbn"]').remove();
$row.find('[name="options[' + index + '].price"]').remove();
// Remove element containing the fields
$row.remove();
});
});
NODEJS: Here's my nodejs route, I use multer for managing file upload. I've a foreach should manage the inputs from the form, but it just see the first element.
router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) {
var newProduct = new Product();
newProduct.imagePath = req.file.filename;
newProduct.title = req.body.title;
newProduct.description = req.body.description;
newProduct.price = req.body.price;
newProduct.save()
.then(function (product) {
console.log(req.body.options);
req.body.options.forEach(function (option) {
var newOption = new ProductOption();
newOption.type = option.optionType;
newOption.value = option.optionValue;
newOption.price = option.optionPrice;
newOption.product = product;
newOption.save();
});
})
.then(function (options) {
req.flash('success', 'Product uploaded correctly.');
res.send({redirect: '/user/shop/products/add'});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to save the newAddress to DB: ' + err);
});
});
It was a simple mistake, I named the fields dinamically added, differently from the static ones.
this code
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
should be like this
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end()