Is it Possible to make a button as File upload Button? - javascript

I am new in php. I have a form on which i place a button Value as Upload MB when user click on this button it redirects on a web form where i place a file upload control and user upload file here.
Here is image
After clicking this button user redirect on this form
here user upload file.
MY QUESTION
Is it possible that can i make my button Upload Mb as file upload button? Can it works like file upload control button?
Actually i want to save user time. I want that when user click on Upload MB button it not redirects on Form. But when user Click on Upload MB button it allow to user to upload file and open browsing window. After that when user upload file it redirects on form.
Can you guys tell me it is possible or not?

You can keep a <input type='file' hidden/> in your code and click it using javascript when the user clicks on the "Upload MB" button.
Check out this fiddle.
Here is the snippet.
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
<input id='fileid' type='file' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
Here is the complete code.
<html>
<head>
<script>
function setup() {
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
document.getElementById('fileid').addEventListener('change', submitForm);
function submitForm() {
document.getElementById('formid').submit();
}
}
</script>
</head>
<body onload="setup()">
<form id='formid' action="form.php" method="POST" enctype="multipart/form-data">
<input id='fileid' type='file' name='filename' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
<input type='submit' value='Submit' />
</form>
</body>
</html>

my 2 cents to the topic: all in code, no input needs to be added to the page.
function onClickHandler(ev) {
var el = window._protected_reference = document.createElement("INPUT");
el.type = "file";
el.accept = "image/*";
el.multiple = "multiple"; // remove to have a single file selection
// (cancel will not trigger 'change')
el.addEventListener('change', function(ev2) {
// access el.files[] to do something with it (test its length!)
// add first image, if available
if (el.files.length) {
document.getElementById('out').src = URL.createObjectURL(el.files[0]);
}
// test some async handling
new Promise(function(resolve) {
setTimeout(function() { console.log(el.files); resolve(); }, 1000);
})
.then(function() {
// clear / free reference
el = window._protected_reference = undefined;
});
});
el.click(); // open
}
#out {
width: 100px; height: 100px; object-fit: contain; display: block;
}
/* hide if it would show the error img */
#out[src=''] {
opacity: 0;
}
<img src="" id="out" />
<button onClick="onClickHandler(event)">select an IMAGE</button>
Note: the el might get garbage collected, before you process all data - adding it to window.* will keep the reference alive for any Promise-handling.

I would suggest to convert button to label. apply the css to label so that it looks like button.
e.g. -
<input type="file" id="BtnBrowseHidden" name="files" style="display: none;" />
<label for="BtnBrowseHidden" id="LblBrowse">
Browse
</label>

Bootstrap Way
.choose_file {
position: relative;
display: inline-block;
font: normal 14px Myriad Pro, Verdana, Geneva, sans-serif;
color: #7f7f7f;
margin-top: 2px;
background: white
}
.choose_file input[type="file"]{
-webkit-appearance:none;
position:absolute;
top:0;
left:0;
opacity:0;
width: 100%;
height: 100%;
}
<div class="choose_file">
<button type="button" class="btn btn-default" style="width: 125px;">Choose Image</button>
<input name="img" type="file" accept="image/*" />
</div>

<html>
<body>
<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
<input type="hidden" id="filename" readonly="true"/>
<input type="button" value="Upload MB" id="fakeBrowse" onclick="HandleBrowseClick();"/>
</body>
<script>
function HandleBrowseClick()
{
var fileinput = document.getElementById("browse");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("browse");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>
</html>

There's an experimental feature that does exactly what you are looking for. You can take a look at it here: https://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker

Related

Check box not working on form before allowed to submit

Hello guys trying to get my checkbox to need to be clicked before submitting my button which is an onclick not submit??
<form>
<p>
<input style="padding:14px; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; width: 300px; border: none;" placeholder="Enter Date Here... e.g 17/05/1981" />
</p>
<p>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat" required="true"> <label style="color: #fff; font-size: 10px;"> Please Accept Terms</label></p>
<p><a id="generateButton" href="generate.html" class="progress-button red" data-loading="Creating..." data-finished="Start Over" data-type="background-vertical" onclick="getRandomImage()">Start Search</a></p>
</form>
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, or javascript, you can easily control if a checkbox group has at least one checked element.
function myFunction() {
document.getElementById("myCheck").required = true;
}
<form action="/action_page.php">
Checkbox: <input type="checkbox" id="myCheck" name="test">
<input type="submit" onclick="myFunction()">
</form>
You can add logic to your clickHandler to check that the box is checked. So instead of calling getRandomImage() directly you add some logic to conditionally call the function.
function clickHandler() {
// get the checkbox element from the DOM
const checkboxElement = document.getElementById('vehicle3');
// see if the checkbox is checked
if (checkBoxElement && checkBoxElement.checked) {
getRandomImage();
} else {
console.log("The checkbox wasn't checked!");
}
}
// add the handler to the button
document.getElementById('generateButton').addEventListener('click', clickHandler);

How to show a popup while a file is getting uploaded when the form is submitted on the webpage?

I am using the type 'file' with attribute 'multiple' in 'input' tag to upload multiple files on the webpage. Once I click the submit button, it takes a lot of time to upload the files and till the time all the files are uploaded, the user has to wait for the next web-page.
Following is the syntax I use:
<form method="POST" action="" enctype="multipart/form-data" id="form_submit">
<div class="form-group">
<label for="Label1"><strong>Upload files</strong>
</label>
<br>
<input type="file" id="Label1" name="Label1" multiple">
</div>
<button type="submit">Submit</button>
</form>
What I want add here is a popup when the submit button is pressed which will show which file is getting uploaded at the moment.
How to use javascript to achieve this?
What I want add here is a popup when the submit button is pressed which will show which file is getting uploaded at the moment.
You are asking a lot. But here a cool and simple example about what can be done to inform the user the upload is processing.
// Submit handler
document.querySelector("form").addEventListener("submit", function(e) {
// Make sure the are files
let fileCount = this.querySelector("[type='file']").files.length
if (fileCount) {
// Toggle the the "Uploading..." message
document.querySelector("#uploading-msg").classList.toggle("msg-hidden");
// Disable the button
this.querySelector("[type='submit']").setAttribute("disabled", true);
} else {
// Do not submit if there are no files
e.preventDefault();
}
})
// Do not use that JS!
// It's just to disable the submit in this demo
document.querySelector("form").addEventListener("submit", e => e.preventDefault())
#uploading-msg,
#uploading-msg+.dots {
color: green;
}
.msg-hidden,
.msg-hidden+.dots {
display: none !important;
}
.dots {
display: inline-block !important;
position: absolute;
animation: 2s infinite animated-dots;
overflow: hidden;
}
#keyframes animated-dots {
0% {
width: 0;
}
100% {
width: 0.7em;
}
}
<form method="POST" action="" enctype="multipart/form-data" id="form_submit">
<div class="form-group">
<label for="Label1"><strong>Upload files</strong>
</label>
<br>
<input type="file" id="Label1" name="Label1" multiple>
</div>
<button type="submit">Submit</button>
<span id="uploading-msg" class="msg-hidden">Uploading</span>
<div class="dots">...</div>
</form>

How to make a form switch dynamically using a type switcher button

I have to make a page, where there are 3 forms within it, but only one should be displayed. Also, these forms shouldn't be connected. For example if I would put in some kind of validation within all 3 of the forms, only the one I use should respond to the validation code, the other ones should stay idle untill I switch the form and use it. I have to make this without frameworks, plain, JS or PHP, HTML and CSS.
I have a page where I can switch forms, 1 is displayed, 2 are hidden. However, I made a validation class, and it is validating all 3 forms, since the 2 i'm not using are just hidden, not disabled so this is not working.
Any one know how I sould make these forms, so they would be independent from each other? I mean, how would they go about making this code, not making mine into account. I want to redo it and just add my other stuff on top of it.
if my deductions are correct on the little information given, here is probably what you are looking for
const
Bt_SwitchForm = document.getElementById("Switch-Form"),
FormX_Count = 3;
var
formActiv = 0,
formX = {};
function formX_Submit(e) {
e.preventDefault()
console.log('formX_Submit on =', this.id )
}
document.querySelectorAll('form').forEach( (elm, Item)=>
{
formX[elm.id] = { 'f' : elm, 'ref': Item }
elm.onsubmit = formX_Submit;
});
Bt_SwitchForm.onclick=()=>{
formActiv = ++formActiv % FormX_Count;
for(let elm in formX) {
formX[elm].f.className = formX[elm].ref===formActiv ? '': 'form_Off'
};
}
form {
display: block;
padding: 20px;
border: 1px solid grey;
width : 200px;
}
form.form_Off { display : none }
button { margin: 10px}
<form id="form1" class="">
<input type="text" id="inputTxt1" value="" placeholder="input form 1" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<form id="form2" class="form_Off">
<input type="text" id="inputTxt1" value="" placeholder="input form 2" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<form id="form3" class="form_Off">
<input type="text" id="inputTxt3" value="" placeholder="input form 3" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<button id="Switch-Form">Switch Form</button>
I think it is useless for me to explain this code since you seem to live with a strong power of deduction. ;)

Control image upload size in textarea of HTML Form

I'm using the following WIZWIG editor "http://js.nicedit.com/nicEdit-latest.js" posting into the below HTML form. I want to control the size of images that are uploaded. Image size should be something like 200px height, 300px width. I've tried CSS, HTML & JavaScript to no avail. Can't figure this out...
<style>
.nicEdit-main{
background-color: white;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit- latest.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas({buttonList : ['bold','italic','underline','strikeThrough','html','forecolor','link','upload','unlink','removeformat']}) });
</script>
<form name="comments" action="<?php echo $_SERVER['PHP_SELF']; ?>"method="post" onsubmit="return checkForm();">
<?php if ($isGuest) { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4">disabled for guest account</textarea>
</div>
<input type="submit" name="action" disabled value="Add Comment" />
<?php } else { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4"></textarea>
</div>
<input type="submit" name="action" value="Add Comment" />
<?php //header("Location: test.php");
} ?>
</form>
Although this was not possible few years ago(you had to send the file to the server side to be able to process file information) now it is do possible with the FileReader() object and pure JS.
You use the .files[0] to get the file then create a temporary img object on the DOM(to be able to do the process) and then assign the file to that DOM object(with the help of FileReader())and then you just compare the file width or height. This is an example how you can do it:
imgfile.onchange = function(e) {
var oFile = document.getElementById("imgfile").files[0]; //Get the selected file by the user
var img = document.getElementById("imgdom"); //get the reserve image element on the dom to be able do all our processing with this object type
document.getElementById("imgdom").style.display = "none";//This is optional if you want to show or not the image to the user
var reader = new FileReader(); //This is the magic object that allows you to process a file on the client side
reader.onload = function (e) {
console.log(e.total); // file size
img.src = e.target.result; // putting file in dom without server upload.
alert(img.width);
//Do what ever condition you want here
//if img.width > 200 do this, else do that
};
reader.readAsDataURL(oFile );
//return false;
};
<form method="post" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" name="imgfile" id="imgfile">
</form>
<div>
<img id="imgdom" src="" />
This issue has been resolved with the following CSS Code:
.nicEdit-main img {
width: 350px;
}
img[src*="http://somedomain.com"] {
width: 350px;
}
Thanks to all who commented...

How can I download one of several files, depending on a selected radio button?

I have some HTML that includes two radio buttons. Depending on which radio button has been selected, I want to download one of two files. How can I do that?
Here's what I've tried so far:
<head>
<script type="text/javascript">
function downloadAddin(){
document.getElementById("bit32");
if (document.getElementById("bit32").checked) {
document.location.href="ECSSetup32.exe";
} else {
document.location.href="ECSSetup64.exe";
}
}
</script>
</head>
<form>
<p><input type="radio" id="bit32" name="arch" checked>Windows 32-bit
<br><input type="radio" id="bit64" name="arch">Windows 64-bit
<p>
<button type="submit" onclick="downloadAddin()"id="download_button"
style="background-color: #0078FF; padding: 1%; color: #ffffff; border:1px
solid; border-radius:10px; font-size:75%">Accept and Download</button>
</form>
I want users to be able to choose a radio button, press the "Agree and Download" button and then get one of the two .exe files they requested. Any ideas?
A simple JS code will do the job.
<input type="radio" name="download" id="x86"/>winrar x86 <br />
<input type="radio" name="download" id="x64"/>winrar x64 <br />
<input type="button" id="download" value="download"/>
var radio_x86 = document.getElementById('x86');
var radio_x64 = document.getElementById('x64');
var button = document.getElementById('download');
button.onclick = downloadFile;
function downloadFile() {
if(radio_x86.checked) {
window.open("http://www.rarlab.com/rar/wrar500.exe");
}else if(radio_x64.checked) {
window.open("http://www.rarlab.com/rar/winrar-x64-500.exe");
} else {
alert("Please check one of the options first.");
}
}
Fiddle example
EDIT: Fiddle: your own code
You don't need to wrap your input elements with <form> tag unless you're using post/get.

Categories