Check if file is selected in Jquery - javascript

I created a button with file input. If I click on the button, I can choose a file from my computer. My problem is that I want to add alert if I select a file. How can I do this? I tried to solve this, but the alert appears when I click again on the button.
function openfileDialog() {
$("#fileLoader").click();
if($("#fileLoader").val() !== ""){
alert("You selected a file!");
}
}
#fileLoader
{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fileLoader" name="files" title="Load File" />
<input type="button" id="btnOpenFileDialog" value = "Click Me !!!" onclick="openfileDialog();" />

Try this:
<input type="file" id="fileLoader" name="files" title="Load File" onchange="alert('selected');" />

Use change event for this but one about this is It will fire only when you pick different file if you pick same file that you already selected It won't fire again.
function openfileDialog() {
$("#fileLoader").click();
}
$("#fileLoader").on("change", function(e){
if($("#fileLoader").val() !== ""){
alert("You selected a file!");
}
});
#fileLoader
{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fileLoader" name="files" title="Load File" />
<input type="button" id="btnOpenFileDialog" value = "Click Me !!!" onclick="openfileDialog();" />

Hi this might helpfull,
function openfileDialog() {
$("#fileLoader").click();
$('#fileLoader').change(function(){
if($(this).val() != ""){
alert("You selected a file!");
}
})
}

Use following code. Basically, you need to use onchange event. (Fiddle - https://jsfiddle.net/o2gxgz9r/65577/)
$(document).ready(function() {
var openfileDialog = function() {
$("#fileLoader").click();
}
$('#btnOpenFileDialog').click(openfileDialog);
$("#fileLoader").change(function() {
if ($("#fileLoader").val() !== "") {
alert("You selected a file!");
}
})
});
Note - alert will appear only when file is selected initially and later if a new file is selected. If you want it to appear even if same file is selected, then you need to modify the value property of the #fileLoader in openfileDialog function

Related

Show element in JavaScript by onkeypress function

I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}

Checking if an input file has been selected?

I am currently working on a website, where you are able to upload a file:
<input type="file" name="file" id="file" class="form-control" />
I then have a button which you can press to upload the selected file:
<button class="btn btn-primary" type="submit">Upload CV</button>
Here I would like the button to be clickable ONLY if a file has been selected. Is this possible using JS, and how?
Thanks in advance!
Using Jquery:
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$('input:submit').attr('disabled',false);
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
);
});
Add disabled attribute in button tag.
You can use JQuery as FullOfQuestions said, but it would be also good to verify that the file was selected before executing button code!
<input type="file" name="file" id="myFile"/>
<!--Add disabled attribute to the button so that is appears disabled at page load-->
<button id="myBtn" type="submit" disabled>Upload CV</button>
<script type="text/javascript">
$(function () {
//when input's value changes
$("#myFile").change(function () {
if($(this).val())
{
$("#myBtn").prop("disabled", false);
}
else
{
$("#myBtn").prop("disabled", true);
}
});
//when button is clicked
$("#myBtn").click(function () {
if($("#myFile").val())
{
console.log("file selected");
}
});
});
</script>
You can do this with native JS below. The button is enabled when a file has been selected, but if a file has not been selected, the button is disabled.
var button = document.querySelector('button[type=submit]');
button.disabled = true;
document.getElementById('file').addEventListener('change', function () {
if (this.value.length > 0) {
button.disabled = false;
} else {
button.disabled = true;
}
});
<input type="file" name="file" id="file" class="form-control" />
<button class="btn btn-primary" type="submit">Upload CV</button>

how to hide a button when there is only one input

i have created a input type file for uploading site. also i created two button , one of them is for appending the input type file and another is for removing them, but i wanna to hide the delete button when i have only one input type file, these are my codes :
JavaScript:
$(document).ready(function (e) {
$('.add').click(function (e) {
$('.addon').append('<div class="choose"><input type="file" name="userFile" /></div>');
});
$('.delete').click(function (e) {
$('.addon > .choose').last().remove();
if ($('<div class="choose"><input type="file" name="userFile" /></div>').length == 1) {
$('.delete').css('display', 'none');
} else {
$('.delete').css('display', 'block');
}
});
});
and the html
<div class="addon">
<div class="choose">
<input type="file" name="userFile" />
</div>
</div>
but it doesn't work, can you please help me?
You should give the input a class
<input type="file" name="userFile" class="file" />
and then change your if statement to
if($('.file').length == 1){....
It's hard to tell exactly what you are asking, but it seems to me like you want the check for length to be triggered by the onChange event for your input element.
Have your if condition as
$('.delete').length > 1
Thats what you seem to be asking. And the HTML seems incomplete for this question

How do I check if a file has been selected in a <input type="file"> element?

I have multiple checkboxes and a file upload input. I would like to re-enable a button if one or more checkbox's are checked AND if the input value is not null.
Here is a link to bootply
Here my html
<div class="upload-block">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="file" id="InputFile">
<button id="upload-btn" type="button blue-button"
class="btn blue-button" disabled>Submit</button>
</div>
Here is my javascript starting point:
Updated via Karl
Bind a change event on all input and then use some condition:
$('.upload-block input').change(function() {
$('#upload-btn').prop(
'disabled',
!($('.upload-block :checked').length && $('#InputFile').val()));
});
Example
This works for all the checkboxes and #InputFile has a value other than none. i.e. where a file has been chosen. However this does not work in IE9
How can I update this to work in IE9?
Bind a change event on all input and then use some condition:
$('.upload-block input').change(function() {
$('#upload-btn').prop(
'disabled',
!($('.upload-block :checked').length && $('#InputFile').val()));
});
Example
Like this:
if($('#InputFile').val().length){
//do your stuff
}
You can better use by using $.trim() method not to allow (trim) spaces:
if($.trim($('#InputFile').val()).length){
//do your stuff
}
Pure JS:
<input type="file" id="InputFile">
<button onclick="buttonSubmitClicked(event)">Submit</button>
<script>
function buttonSubmitClicked(event) {
if (!document.getElementById("InputFile").value) {
event.preventDefault();
alert("Please choose a file!");
} else {
alert("File've been chosen");
}
}
</script>
jsfiddle: check it out
$('.upload-block input').change(function() {
if ($('.upload-block :checked').length && $('#InputFile').val() ) {
$('#upload-btn').prop('disabled',false);
}
else {
$('#upload-btn').prop('disabled',true);
}
});
No need of separate selectors for checkbox and input file .upload-block input is enough to catch catch both the checkbox and file value change
I would apply the validation to all elements involved. This way changing either the checkboxes or the input will update disabled
$('#InputFile, .upload-block :checkbox').change(function(){
var isValid= $('.upload-block :checkbox:checked').length && $('#InputFile').val();
$('#upload-btn').prop('disabled',isValid);
});

Radio button opens textbox when checked, but won't close it when unchecked

I'm trying to create a dynamic form whereby users can select to either upload and image or embed a youtube clip.
I have tried this using radio inputs:
<script type="text/javascript">
$(".youtube").change(function () {
//check if radio button is checked.
if (this.checked && this.value === "youtube") {
//show a text box 'embedbode' when radio 'youtube' is checked
$("#embedcode").show();
} else if (!this.checked && this.value === "image"){
//hide the text box when 'image' is checked
$("#embedcode").hide();
}
});
</script>
And this is the html:
<input type="radio" value="image" id="type" name="type" checked='checked' autocomplete="off" />
<label>Image</label>
<input type="radio" value="youtube" id="type" name="type" class="youtube" />
<label>Video</label>
<input id="embedcode" placeholder="embed code" name="embedcode" type="text"/>
The radio button image is selected by default. When a I click on the video radio button a textbox opens whereby I can input an embed code for the video.
However, when I click back to image, should I change my mind on what I want to upload, the embed textbox is still there.
I've looked at the JS and can't see where I'm going wrong.
I tried adjusting the terms and adding an extra else if but the textbox won't hide when I click back to image.
Where am I going wrong?
<script type="text/javascript">
$(document).ready(function(){
$("#embedcode").hide();
$("input[name='type']").change(function () {
if($(this).val() == "youtube")
$("#embedcode").show();
else
$("#embedcode").hide();
});
});
</script>
When they check the other one, and you do (fixed your code here, to be jQuery):
if (!$(this).prop('checked') && $(this).val() === "image")
It is now checked... so it won't hide it. All you need to do is check for the value, since they clicked it and it's a radio, it will always be checked.
if ($(this).val() === "image")
An easier way to do this would just be:
$(".youtube").change(function () {
$("#embedcode").toggle($(this).val() == "youtube");
});
<script type="text/javascript">
$(document).ready(function(){
$("#embedcode").hide();
$("input:radio").change(function () {
if($(this).val() == "youtube")
{
$("#embedcode").show();
}
else
{
$("#embedcode").hide();
}
});
});
</script>

Categories

Resources