File upload click simulation button triggers form - javascript

I'm creating a gallery that allows the uploader to upload an image/multiple images at a time. As a default, one file input is displayed with a text input for the corresponding image description.
I also have another button which simulates the file input being clicked for aesthetical purposes. Upon clicking this button, the file browser triggers but the form in which the file inputs are placed seems to submit?
<button id="new-dialogue">add image</button>
<form action="action.php" method="post" enctype="multipart/form-data">
<div class="create-upload">
<!-- SECTION REPEATED WITH DIFFERENT IDS AS #NEW-DIALOGUE CLICKED -->
<div class="upload">
<input class="image-upload" type="file" id="input1" name="file[]"/>
<button class="btn-select" id="1">select file</button>
<input id="desc" type="text" name="desc[]"/>
</div>
<!-- SECTION -->
</div>
</form>
with JavaScript
$('document').ready(function() {
var i = 1;
$('#new-dialogue').click(function() {
i++
if(i >= 6) {
} else {
$('.create-upload').append('<div class="upload"><input class="image-upload" type="file" id="input' + i + '" name="file[]"/><button class="btn-select" id="file' + i + '">select file</button><input id="desc" type="text" name="desc[]"/></div>');
$('.image-upload').imgPreview();
}
});
$('.btn-select').click(function () {
var id = this.id;
$('input#input' + id).click();
});
});

Put type='button' to disable the button from acting as a submit type.
<button class="btn-select" id="file1" type='button'>select file</button>

Related

Hide / show depending on input type=file value

It works fine when I select / deselect a file via the Choose File button:
$("input[type='submit']").toggle(false);
$("input[type='file']").change(function() {
if ($(this).val() != "") {
$("#btn").toggle();
} else {
$("#btn").toggle();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="fld" type="file" name="image" id="file">
<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />
<br>
<br>
<div id="remove_button">Remove</div>
Click on the Choose File button and select a file. The Upload / Edit picture button will appear. Now click on the Choose File button again but do not select a file and exit the small popup window. The Upload / Edit picture button will disappear.
In my case I want the input="file" value to be cleared and the Upload / Edit picture button to disappear if I clear the value by clicking on the <div id="remove_button">Remove</div>
Is there a way to do that?
JSFiddle
Add this code into your javascript
$("#btn").toggle(false);
$("#fld").change(function(){
if($(this).val() != "")
{
$("#btn").toggle();
}
else{
$("#btn").toggle();
}
});
$("#remove_button").click(function(){
$("#fld").val('');
document.getElementById("btn").style.visibility = "hidden";
})
and remove id tag from your html..it has two ids for the button
change it like
<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture"
class="btn" />
What you can do is to bind a click event listener to the #remove_button element (which I recommend that you should be using <button> instead of a <div>).
In the callback, you can simply set the value of the file input to an empty string, which effectively resets the field. Remember that you will need to use .trigger('change') to manually reinvoke the show/hide logic based on the file input value:
const $submit = $("input[type='submit']");
$submit.hide();
$("#fld").change(function() {
$submit.toggle(!!this.value);
});
$('#remove_button').click(function() {
$('#fld').val('').trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="fld" type="file" name="image" id="file">
<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />
<br>
<br>
<button id="remove_button">Remove</button>

Dynamically Added Input Value disappear on next addition

I am creating a webpage with ability to add input box dynamically , everything works fine. But whenever I add a new input box the value from all the input box added above that field get cleared automatically.
Here is the html which is generated on addition of the element
<div class="main_text_area" id="got_id_from_server">
<p>Add Delay For :</p>
<div class="remove_bg button btn" name="some_id_from_server"></div>
<p>
<div contenteditable class="text_im" placeholder="Enter Delay" id="some_id_from_server" onchange="post_delay(this)"></div>
</p>
<p>
<input class="text_im" placeholder="Select" type="text" id="some_id_from_server" list="some_id_from_server" onchange="post_delay(this)">
<datalist id="some_id_from_server">
<option value="Minutes"></option>
<option value="Hours"></option>
<option value="Days"></option>
</datalist>
</p>
</div>
This behavior occurs because adding new elements to your Dom will cause the Website to kind of render the view again & again so the (in this case) not stored values of a "input field given no ID attribute" you have inputted into your input-element will just reset.
So have a look at this two code snippets:
var count = 0;
function createInput(event) {
count++;
document.body.innerHTML += "<input value='Input #"+ count + "' / >"
event.preventDefault();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createInput()">Create Input</button>
Edit: Using jQuery will be the better solution so have a look at this code (To prevent the reset of the input fields you have to use "append()". Try it on your own!:
var count = 0;
$(function() {
$("#createInput").click(function(event) {
count++;
$('form').append('<input type="text" value="Input #' + count + '" />');
event.preventDefault();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="myForm" accept-charset="utf-8">
<button id="createInput">Create Input</button>
</form>

Two button submit form issue

Hi successfully made a form where there are two submit buttons.
I needed two buttons because I need each button to take the form to a different place, while get/post the information in the first form.
This is how I did it
Javascript:
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" input name="pick" required value="<?php echo isset($_POST['pick']) ? $_POST['pick'] : ''; ?>"/>
</div>
<input type="button" onclick="submitForm('page2.php')" class="btn small color left" value="ADD ANOTHER STOP" />
<input type="button" onclick="submitForm('page3.php')" class="btn medium color right" value="Continue" />
</form>
It works, both buttons submits to the relevant pages.
But now there is one problem I can't seem to fix, previously if the form was not filled, and i clicked submit, it would ask me to fill up the required fields, now it does not anymore.
If required fields are not filled up, it still submits the form.
I need button 1 to not require required fields to be filled up, and button 2 to require it as button 2 submits the form, while button 1 brings it to a new form to fill up with other details before they submit from there.
Anyone know of a way I can sort this?
You can try this: <input type="text" name="pick" id="pick" required/> and in the javascript
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
if (document.getElementById('pick').value) {
form.submit();
}}
else{
alert('Please fill the required field!');}
You just need to use jquery to validate the form when the first button is clicked and you can use formaction attribute on the button to specify where the button should go when it's clicked.
$('document').ready(function(){
$('#btn1').on('click',function(){
var pick = $('input[type="text"][name="pick"]').val();
if(pick == ""){
alert("enter pick");
return false;
}else{
$(this).submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" name="pick" value="your value">
</div>
<button type="submit" formaction="page2.php" class="btn small color left" id="btn1">ADD ANOTHER STOP</button>
<button type="submit" formaction="page3.php" class="btn medium color right">Continue</button>
</form>
You could use jQuery for this.
if ($('#something').length)
This will check if there exist an element with the id 'something', but not if it is empty or which value it has.
To check this you can use:
if($('#something').val().length>0)
or
if($('#something').val() != "")
Do with it what ever is needed.
You could even add this check within your submitForm function just above the current code.
Try this:
<script>
function submitForm(action) {
var a = $("input[name=pick]").val();
if(a) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
} else {
alert('please fill the required field');
return false;
}
}
</script>
Using this way(simple way):--
<form id="myForm" name="myForm" onSubmit="encriptar_rc4();return false;">
<input type="submit" name="submitOne" value="submitOne" class="submitButton" />
<input type="submit" name="submitTwo" value="submitTwo" class="submitButton" />
</form>
<script>
$(function(){
$(".submitButton").click(function(e){
alert($(this).attr("name"));
});
encriptar_rc4();{
alert('hola');
}
});
</script>

WebcamJS overriding return button in HTML form

For a community site, I created an HTML form to add new users. If a new user wants to make a profile photo right away, this is possible with WebcamJS (using v1.0.2, already got this working).
However, when I want to add a new user and filled in all data (with or without a picture) and press Return, instead of submitting the form, a new webcam div is opened.
I tried a lot of different things, even disabling the default behavior of the return key, but still the problem persists.
Hope anyone can help!
Simplified HTML example:
Webcam.set({
width: 400,
height: 300,
//dest_width: 400,
//dest_height: 300,
image_format: 'jpeg',
jpeg_quality: 80
});
$("#maak_foto").hide();
$("#foto_maken").click(function() {
Webcam.attach('#my_camera');
$("#maak_foto").show();
$("#my_camera").show();
$("#foto_form").show();
});
$("input#foto_gebruiken").click(function() {
$("#my_camera").hide();
$("#pre_take_buttons").hide();
});
function preview_snapshot() {
Webcam.freeze();
// swap button sets
document.getElementById('pre_take_buttons').style.display = 'none';
document.getElementById('post_take_buttons').style.display = '';
}
function cancel_preview() {
Webcam.unfreeze();
// swap buttons back
document.getElementById('pre_take_buttons').style.display = '';
document.getElementById('post_take_buttons').style.display = 'none';
}
function save_photo() {
// actually snap photo (from preview freeze) and display it
Webcam.snap(function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'Jouw foto:<br>' +
'<img src="' + data_uri + '"/>';
// swap buttons back
document.getElementById('pre_take_buttons').style.display = '';
document.getElementById('post_take_buttons').style.display = 'none';
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('webcam').value = raw_image_data;
//document.getElementById('wijzigen').submit();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://intern.ifmsa.nl/leden/webcam/webcam.js"></script>
<form name="htmlform" method="post" enctype="multipart/form-data" action="<?php $_SERVER['PHP_SELF'] ?>">
<label>Voornaam</label>
<input type="text" name="voornaam">
<br>
<label>Email</label>
<input type="email" name="email">
<br>
<label>Photo</label>
<div>
<input name="foto" type="file">
<button id="foto_maken" onclick="return false" ;>Or make another one</button>
<input id="webcam" type="hidden" name="webcam" value="">
</div>
<br>
<div id="results"></div>
<div id="my_camera" style="display: none; clear: left;"></div>
<div id="pre_take_buttons">
<input type="button" id="maak_foto" value="Take photo" onClick="preview_snapshot(); return false;">
</div>
<div id="post_take_buttons" style="display:none;">
<input type="button" value="Another photo" onClick="cancel_preview(); return false;">
<input name="webcamdefi" id="foto_gebruiken" type="button" value="Use photo" onClick="save_photo(); return false;">
</div>
<label>Confirm password</label>
<input name="pass" type="password" required>
<input class="submit" type="submit" name="submit" value="Wijzigen">
</form>
Simple magic (the first tag button#foto_maken is interpreted as the submit button and fire when the enter press):
change this:
<button id="foto_maken" onclick="return false" ;>Or make another one</button>
to this:
<input type="button" id="foto_maken" value="Or make another one"/>
[ http://jsfiddle.net/2es2yf0y/ ]
More clear example: http://jsfiddle.net/stdob/tfss0sz2/2/

Output multiple input file to a different id with a single button

In a nutshell,
Below is what I am trying to accomplish:
http://jsfiddle.net/n3r8conn/8/
but as shown I am having issues, it would work as follow:
User clicks on button once, the file gets selected from input and then display in the files_1 id, user clicks on button again, file gets selected, and then output into files_id2,
This part only shows the upload part, in other words, everything mention above beside displaying the image on screen.
Html COde:
<button id="uploadDevice" class="button button-block button-positive">
<i class="icon ion-android-mail"></i> <text id="textBtn1">From Device </text>
</button>
<input type="file" class="uploadDevice" id="files_1" name="image_file_arr[]" multiple>
<input type="file" class="uploadDevice" id="files_2" name="image_file_arr[]" multiple>
<input type="file" class="uploadDevice" id="files_3" name="image_file_arr[]" multiple>
JavaScript Code:
$('#uploadDevice').click(function(){
myGlobalCounter++;
$( '#files_' +myGlobalCounter ).val('Secret text ' + myGlobalCounter);
});
CSS code:
.uploadDevice{
visibility : hidden;
}
Update:
<ion-content>
<ion-slide-box id="uploadedPictures" on-slide-changed="slideHasChanged($index)">
<ion-slide>
<output id="profilePic1"></output>
</ion-slide>
<ion-slide>
<output id="profilePic2"></output>
</ion-slide>
<ion-slide>
<output id="profilePic3"></output>
</ion-slide>
</ion-slide-box>
<div class="row">
<div class="col col-50">
<button id="uploadFacebook" class="button button-block button-positive">
<i class="icon ion-social-facebook"></i> <text id="textBtn1"> From Facebook
</button>
</div>
<div class="col col-50"><a href="javascript:void(0)" id="buttonFile" href="">
<button id="uploadDevice" class="button button-block button-positive">
<i class="icon ion-android-mail"></i> <text id="textBtn1">From Device </text>
</button></a>
<input type="file" class="uploadDevice" id="files" name="image_file_arr[]" multiple>
</div>
</div>
<style>
.uploadDevice{
visibility : hidden;
}
</style>
<script>
$("#buttonFile").click(function(){
$("#files").trigger('click');
});
</script>
script
function handleFileSelect(evt) {
var $fileUpload = $("input#files[type='file']");
if (this.files.length > 4) {
alert("You can only upload a maximum of 5 files");
evt.preventDefault();
evt.stopPropagation();
return false;
}
var files = this.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
(function(i){
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
var span = document.createElement('span');
span.innerHTML = ['<img id="userPictures" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('profilePic' + (i + 1)).appendChild(span);
};
})(f);
reader.readAsDataURL(f);
})(i);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Here's another version of the 3rd answer.
This one just moves each FILE INPUT after you click on it, so you can see that the next FILE INPUT is now in place to be clicked.
Basically, instead of using z-index to rotate the just-clicked FILE INPUT to the bottom of the stack, I am moving it down the page so you can visually see what is happening.
jsFiddle Demo
Code:
var xx, global_cnt = 1;
$('#clicker').button(); //use jQueryUI to auto-style the button
$('div').click(function(){
xx = global_cnt * 60;
$('#real_uploader_' +global_cnt).css({'position':'absolute','top':xx+'px'});
global_cnt++;
if ( $('#real_uploader_' +global_cnt).length ){
$('#real_uploader_' +global_cnt).css('z-index','2');
}
});
Something like this?
jsFiddle Demo
HTML:
<input type="text" class="th" id="typeHidden_1" />
<input type="text" class="th" id="typeHidden_2" />
<input type="text" class="th" id="typeHidden_3" />
<input type="text" class="th" id="typeHidden_4" />
<input type="button" id="mybutt" value="Show Me" />
<input type="button" id="nutherbutt" value="Read Hidden Field" />
javasccript/jQuery:
var myGlobalCounter = 0;
$('#mybutt').click(function(){
myGlobalCounter++;
$( '#typeHidden_' +myGlobalCounter ).val('Secret text ' + myGlobalCounter);
});
$('#nutherbutt').click(function(){
for (n=1; n<= myGlobalCounter; n++){
var tmp = $('#typeHidden_' +n).val();
alert( tmp );
}
});
I apologize -- I did not read your answer carefully enough the first time.
The <input type="file" /> element is special. For security reasons, there is very little you can do with javascript to control a file input element. You cannot set the filename programmatically, and you cannot click the button programmatically.
However, there is a work-around that is frequently proposed:
HTML:
<div>
<button>Upload File</button>
<input type="file" id="upload_input" name="upload" />
</div>
CSS:
div{display:block;width:100px;height:20px;overflow:hidden;}
button{width:110px;height:30px;position:relative;top:-5px;left:-5px;}
input{font-size:50px;width:120px;opacity:0;filter:alpha(opacity:0); position:relative;top:-40px;left:-20px;background:yellow;}
non-working jsFiddle with code
References:
In JavaScript can I make a "click" event fire programmatically for a file input element?
Programmatically set the value of a type="file" input HTML element?
Let me try again.
I was having some difficulty understanding what you need. If I can get my head around that, then I'm pretty sure I can help.
Please check if this is what you need.
This code has 3 <input type="file" > elements. All 3 are "invisible" (using opacity, to they remain where they are on screen, they are just invisible).
The FILE inputs are also stacked on top of each other. At the start, input_1 is on top --- but it is invisible, so all you see is the BUTTON underneath it.
When "the button" (really, input_1) is clicked, three things happen:
(1) the OPEN dialog (Choose a file to upload) is displayed for input_1
(2) global_cnt is used to move input_1 to the back (using z-index)
(3) global_cnt is incremented, and then used again to move input_2 to the front
(4) global_cnt is now at the correct number to move input_2 to back when it is clicked
Each time the user clicks "the button" (really, they are clicking an invisible input type="file" element), a different input element is moved to the top. Therefore, by clicking the same "button", the user keeps uploading to a different file input.
Note: this works because when you click input_1, the div also gets the click event (through event bubbling).
jsFiddle Demo code
Code:
HTML:
<div>
<input type="button" id="clicker" value="Upload File" />
<input type="file" class="hidden_uploaders" id="real_uploader_1" name="upload_1" />
<input type="file" class="hidden_uploaders" id="real_uploader_2" name="upload_2" />
<input type="file" class="hidden_uploaders" id="real_uploader_3" name="upload_3" />
</div>
javascript/jQuery:
var global_cnt = 1;
$('#clicker').button(); //use jQueryUI to auto-style the button
$('div').click(function(){
if ( $('real_uploader_' +global_cnt).length ) $('real_uploader_' +global_cnt).css('z-index','-1');
global_cnt++;
if ( $('real_uploader_' +global_cnt).length ) $('real_uploader_' +global_cnt).css('z-index','2');
});
still working on this

Categories

Resources