ionic login button not working in android - button

Button is working when run on browser using ionic serve and ionic serve --lab command. I am able to login in web browser and redirected to dashboard.
When I generate .apk file and run on android device....login button is not working.
Not redirected to dashboard by click on login button with username and password.
I have tried this reference: Ionic android button not working
but still not get success...please give me any solution .
Login Template
<li class="item-content">
<div class="item-inner">
<div class="item-input">
<label class="item item-input">
<input class="style login3" type="email" name="email" placeholder="E-mail" ng-model="user.email">
</label>
</div>
</div>
</li>
<li class="item-content">
<div class="item-inner">
<div class="item-input">
<label class="item item-input">
<input class="style login3" type="password" name="password" placeholder="Password" ng-model="user.pwdForLogin">
</label>
</div>
</div>
</li>
</div>
<button ng-click="signIn(user)" >
Sign In
</button>
App.js
// State to represent Login View
.state('login', {
url: "/login",
templateUrl: "templates/login.html",
controller: 'LoginCtrl',
resolve: {
// controller will not be loaded until $waitForAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["Auth",
function (Auth) {
// $waitForAuth returns a promise so the resolve waits for it to complete
return Auth.$waitForAuth();
}]
}
})
Please help me....

Here I will show you a working example and you can use it for your code.
MY Custom CSS
.bgLogin{
width: 100%;
background-image: url("http://static.vecteezy.com/system/resources/previews/000/084/251/original/christmas-bokeh-vector-background.jpg");
background-size: 100% 100% !important;
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
}
.login-content
{
margin-top:8%;
padding:0px 10px 0px 10px;
}
.login-content .login-form
{
margin-top:40%;
}
View/HTML
<ion-view class="bgLogin" name="login-view">
<ion-nav-bar>
<ion-nav-back-button></ion-nav-back-button>
</ion-nav-bar>
<ion-content class="login-content">
<div class="login-form">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
</div>
<button class="button button-block login-button" ng-click="login()">Login</button>
</ion-content>
</ion-view>
App.js
Assuming your adding references to controller and service
var appStarter = angular.module('starter', ['ionic', 'starter.controllers', 'starter.services']);
define state
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
controller for login
appControllers.controller('LoginCtrl', function($scope, $rootScope, LoginService, $ionicPopup, $state, $ionicHistory) {
$scope.data = {};
$scope.login = function() {
LoginService.loginUser($scope.data.username, $scope.data.password).success(function(data) {
$rootScope.userName = $scope.data.username.toUpperCase();
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.welcome');
}).error(function(data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!',
buttons: [
{
text: 'Ok',
type: 'orange-btn'
}
]
});
});
}
});
Service for login
.service('LoginService', function($q) {
return {
loginUser: function(name, pw) {
var deferred = $q.defer();
var promise = deferred.promise;
if (name.toLowerCase() == 'ens' && pw == 'ens' || name.toLowerCase() == 'adam' && pw == 'adam'|| name.toLowerCase() == 'illum' && pw == 'illum'|| name.toLowerCase() == 'test' && pw == 'test') {
deferred.resolve('Welcome ' + name + '!');
} else {
deferred.reject('Wrong credentials.');
}
promise.success = function(fn) {
promise.then(fn);
return promise;
}
promise.error = function(fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
});

Related

How to make sure the page doesn't refresh so my csfile in my razor pages doesn't refresh

I have a project that includes using form post method with buttons. The problem is that it is like a shopping list where each item has 4 chechkboxes and 1 submit "add to cart" when that is pressed it gets in a tabel of purchased items. The problem is that when you press the submit it reloads the page and my Tanks.cshtml.cs file in the Tanks.html gets reloaded so i lose the date inside. So when i add a item to my list it is always gonna be the last one you clicked and not all the ones you clicked. It is in visual studio 2022 ASP.NET core and razor pages.
//cshtml
#for (int i = 0; i < #Model.tanks.Count; i++)
{
if(i == 4)
{
<p> </p>
<b style="color:white; background-color:#fecb2b; margin-left: 10px; margin-right: 10px; font-size: 30px;"> RVS TANKS </b>
<p> </p>
}
if(i == 8)
{
<p> </p>
<b style="color:white; background-color:#fecb2b; margin-left: 10px; margin-right: 10px; font-size: 30px;"> RVS UCO CADDY </b>
<p> </p>
}
<div class="#Model.tanks[i].gallery">
<div class="card">
<img src="~/lib/FotosTanks/#Model.tanks[i].afbeelding" style="width:100%; border-radius: 10px;">
<h1 style="color:#076044">#Model.tanks[i].soort</h1>
<p>Afmetingen: LxBxH (cm)<br> #Model.tanks[i].groote</p>
//here starts the problem
<form method="post">
<input name="PompEnZuigstang" type="checkbox" /> Met pomp & zuigstang<br />
<input name="LengteSlang" type="checkbox" /> Lengte slang (m): <br />
<select class="form-control" name="lengtes" style="width: 190px; color:#076044; margin-left: 18px;" >
<option>4</option>
<option>6</option>
<option>8</option>
<option>10</option>
<option>12</option>
</select>
<input name="Volumemeter" type="checkbox" /> Mechanische volumemeter<br />
<input name="Hittebestendig" type="checkbox" /> Hittebestendig (max. 120°C)<br />
<p> </p>
<input type="hidden" name="id" value="#i">
<p><button style=" border-radius: 4px;" onclick = "onPost(); return false" type = "button">Add to Cart</button></p>
</form>
</div>
</div>
}
//cshtml.cs
public void OnPost()
{
idNummer = Convert.ToInt16(Request.Form["id"]);
optie1 = Request.Form["PompEnZuigstang"];
optie2 = Request.Form["LengteSlang"];
Lengte = Request.Form["lengtes"];
optie3 = Request.Form["Volumemeter"];
optie4 = Request.Form["Hittebestendig"];
if (optie1 == "on")
{
tanks[idNummer].optie1 = "X";
}
else
{
tanks[idNummer].optie1 = "";
}
if (optie2 == "on")
{
tanks[idNummer].optie2 = $"{Lengte}m";
}
else
{
tanks[idNummer].optie2 = "";
}
if (optie3 == "on")
{
tanks[idNummer].optie3 = "X";
}
else
{
tanks[idNummer].optie3 = "";
}
if (optie4 == "on")
{
tanks[idNummer].optie4 = "X";
}
else
{
tanks[idNummer].optie4 = "";
}
Test.Add(tanks[idNummer]);
}
I've been looking for a solution for several hours
If you don't want to refresh the page,you can use ajax to call OnPost:
<button style=" border-radius: 4px;" onclick = "callAjax()" type = "button">Add to Cart</button></p>
<script>
$.ajax({
type: "POST",
url: '',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: $("form").serialize(),
success: function (data) {
...
},
error: function (result) {
alert("fail");
}
})
</script>

VueJs Enter-transition animation not working on click

The code is supposed to take a user's entry in the input box, push it to the end of the "tasks" array when "ADD TASK" is clicked which is then displayed using v-for. However, the list-enter-active animation doesn't work. It just snaps into the browser's display instead of easing in. "REMOVE TASK" works like it should though.
<template>
<div class="grid-container">
<div class="content">
<h1>To-Do It</h1>
<transition-group name="list" tag="p">
<div
v-for="(item, index) in tasks"
v-bind:item="item"
v-bind:index="index"
v-bind:key="item.id"
>
{{ item.count }}
</div>
</transition-group>
<input type="text" placeholder="Enter a task" v-model="userinput" />
<div>
<p v-bind:class="{ buttondiv: pshow }" v-on:click="addtask">
ADD TASK
</p>
<p v-bind:class="{ buttondiv: pshow }" v-on:click="removetask">
REMOVE TASK
</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Todo",
data: function() {
return {
userinput: "",
tasks: [],
show: true,
pshow: true
};
},
methods: {
addtask: function() {
if (this.userinput != "") {
this.tasks.push({ count: this.userinput });
this.userinput = "";
console.log(this.tasks);
} else {
return "failed";
}
},
removetask: function() {
this.tasks.pop(this.userinput);
}
}
};
</script>
<style>
#import "../assets/Todo.css";
.list-enter-active,
.list-leave-active {
transition: all 1s;
}
.list-enter,
.list-leave-to {
opacity: 0;
transform: translateY(30px);
}
.flip-list-move {
transition: transform 1s;
}
</style>

Why my submit button change his colour when its disabled because I selected other radio button in Angular 9

The problem I have right now is that I have my login and has two radio buttons one is selected for default until now its all fine, the submit button looks disabled but in the moment i click the other radio button the colour of the submit button change to the colour that it should have when is available.
Even when the colour of the button change you cant send the information until you put the correct data.
How can I solve this problem? . I'm using angular material, ng-bootstrap and scss.
Below I will let my code and pictures of it looks like
Code of the html where the radio buttons are located and the first form for the login page.
<div class="bg">
<div class="main-div color">
<mat-card class="z-depth center" flex="50" >
<mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
<mat-radio-button [value]="true" >User</mat-radio-button>
<mat-radio-button [value]="false">Admin</mat-radio-button>
</mat-radio-group>
<div class="row justify-content-center" *ngIf="radio_btn==false;else form2">
<form class="example-form " [formGroup]="loginForm" (ngSubmit)="sendUser()">
<mat-form-field class="example-full-width">
<input matInput formControlName="Identifier" placeholder="Identifier" >
</mat-form-field><br>
<div *ngIf="loginForm.get('Identifier').hasError('Identifier') && loginForm.get('Identifier').touched">Introduce an email</div><br>
<mat-form-field class="example-full-width">
<input matInput formControlName="Password" placeholder="Password" type="password">
</mat-form-field><br>
<div *ngIf="loginForm.get('Password').hasError('Password') && loginForm.get('Password').touched">Introduce the correctly password</div><br>
<button mat-raised-button [disabled]="loginForm.invalid" class="colour_button" type="submit">Sign in</button>
</form>
</div>
<ng-template #form2>
<app-home-admin></app-home-admin>
</ng-template>
</mat-card>
</div>
</div>
In the <app-home-admin></app-home-admin> is the other form that has the same code of the form above but without the radio buttons.
SCSS file
example-icon {
padding: 0 14px;
}
.example-spacer {
flex: 1 1 auto;
}
button {
display: block;
width: 100%;
margin: 2px;
text-align: center;
color: $orange !important;
}
.colour_button{
background: $colour_button;
}
And this is how i change the colour of the submit button when is disabled, its located in the style.scss.
.md-button.md-raised.md-primary.formPage:not(.disabledclassname) {
position: right !important;
color: #FFFFFF !important;
background-color:#008cba !important;
}
FormGroup in the ts file
export class HomeComponent implements OnInit {
radio_btn:boolean = true;
loginForm: FormGroup;
bSignIn = false;
isSigned:boolean = false;
snackMessage:string = 'Introduce valid data';
public errorMessage: string;
constructor(
private _builder:FormBuilder, private usersService: UsersService,private router: Router,
public _snackBar: MatSnackBar
) {}
sendUser(){
this.bSignIn = true;
let formData = new FormData();
formData.append('Identifier', this.loginForm.get('Identifier').value);
formData.append('Password', this.loginForm.get('Password').value);
this.usersService.validateUserCredentials(formData)
.subscribe(
res => {
this.bSignIn = false;
let auxRes: any = res;
if(auxRes.type == 'success'){
let auxUser = {
personId: auxRes.person_id,
clientId: auxRes.client_id,
projectId: auxRes.project_id
}
this.isSigned = true;
localStorage.setItem('leadLogged', JSON.stringify(auxUser));
this.goToUsersDashboard(auxRes.id);
}
else
this.openSnackBar(this.snackMessage);
},
);
}
ngOnInit(): void {
this.ValidateForms();
}
ValidateForms(){
this.loginForm = this._builder.group({
Identifier: ['',Validators.compose([Validators.required,Validators.minLength(7)])],
Password: ['',Validators.compose([Validators.required,Validators.minLength(5)])]
})
}
}
This is how it looks like, it should always look disabled until you put the correct information.
This is how i solve it
Putting this in the button
<button mat-raised-button [class.black]="!loginForm.invalid" [disabled]="loginForm.invalid" type="submit">Sign in</button>
and adding this class to the scss file
.black {
background-color:$black !important; ;
}

VueJS change border color of the input if input is already filled in

I need to change the border color of the input if the customer already filled in the field.
How can I do this using VueJS ?
<div class="some-basic-div", '#change' => 'checkForInput'>
<div class="dc-form-group ">
<input type='text' id='first_name' >
</div>
<div class="dc-form-group ">
<input type='text' id='last_name' >
</div>
<div class="dc-form-group ">
<input type='text' id='some_text' >
</div>
</end>
I have tried to use pure JavaScript.
checkForInput: function(e) {
let targetDiv = event.target;
if (targetDiv.value == "") {
targetDiv.classList.remove("mod-group-success");
} else {
targetDiv.classList.add("mod-group-success") ;
}
}
So when I am changing the input I need to change the style of the input which I filled in.
I've wrote this code for handling the issue:
Vue.config.productionTip = false
app = new Vue({
el: "#app",
data: {
testValue: ''
}
},
methods: {
checkForInput: function(e){
let input = event.target
if (input.value != "") {
input.classList.add("mod-group-success") ;
} else {
input.classList.remove("mod-group-success");
}
}
}
})
And putted on front end:
'#change' => 'checkForInput'
Uses Class & Styles binding,
below is one simple demo for class binding.
Vue.config.productionTip = false
app = new Vue({
el: "#app",
data: {
testValue: ''
},
computed: {
computedInputStyleEnable: function () { // or use one method instead of computed property
//apply your own logic at here to determinate if enable input-has-value-style
return this.testValue && this.testValue.length > 0
}
},
methods: {
applyInputStyle: function (targetInput) { // bind with one method and return Array
return [targetInput && targetInput.length > 0 ? 'input-has-value-style' : 'input-no-value-style']
}
}
})
.input-has-value-style {
border: 2px solid green;
background-color:lightgreen;
}
.input-no-value-style {
border: 2px solid red;
background-color:pink;
}
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div>
<p>Already filled in {{testValue.length}} characters.</p>
<input type='text' v-model="testValue"
:class="{'input-has-value-style': computedInputStyleEnable}"
/>
</div>
<div>
<p>Already filled in {{testValue.length}} characters.</p>
<input type='text' v-model="testValue"
:class="applyInputStyle(testValue)"
/>
</div>
</div>

Twitter Bootstrap Form File Element Upload Button

Why isn't there a fancy file element upload button for twitter bootstrap? It would be sweet if the blue primary button was implemented for the upload button. Is it even possible to finesse the upload button using CSS? (seems like a native browser element that can't be manipulated)
Here's a solution for Bootstrap 3, 4, and 5.
To make a functional file input control that looks like a button, you only need HTML:
HTML
<label class="btn btn-default">
Browse <input type="file" hidden>
</label>
This works in all modern browsers, including IE9+. If you need support for old IE as well, please use the legacy approach shown below.
This techniques relies on the HTML5 hidden attribute. Bootstrap 4 uses the following CSS to shim this feature in unsupportive browsers. You may need to add if you're using Bootstrap 3.
[hidden] {
display: none !important;
}
Legacy approach for old IE
If you need support for IE8 and below, use the following HTML/CSS:
HTML
<span class="btn btn-default btn-file">
Browse <input type="file">
</span>
CSS
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
Note that old IE doesn't trigger the file input when you click on a <label>, so the The CSS "bloat" does a couple things to work around that:
Makes the file input span the full width/height of the surrounding <span>
Makes the file input invisible
Feedback & Additional Reading
I've posted more details about this method, as well as examples for how to show the user which/how many files are selected:
https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/
Im surprised there was no mention of the <label> element.
Solution:
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" class="d-none">
Button Text Here
</label>
No need for any JS, or funky css...
Solution for including the filename:
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" style="display:none"
onchange="$('#upload-file-info').text(this.files[0].name)">
Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span>
The solution above requires jQuery.
Note: use $.text() when displaying user-supplied content on the page. An earlier version of this answer used $.html() which is not safe – filenames can contain HTML markup.
With no additional plugin required, this bootstrap solution works great for me:
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;'>
Choose File...
<input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'>
</a>
<span class='label label-info' id="upload-file-info"></span>
</div>
demo:
http://jsfiddle.net/haisumbhatti/cAXFA/1/ (bootstrap 2)
http://jsfiddle.net/haisumbhatti/y3xyU/ (bootstrap 3)
It's included in Jasny's fork of bootstrap.
A simple upload button can be created using
<span class="btn btn-file">Upload<input type="file" /></span>
With the fileupload plugin you can create more advanced widgets. Have a look at
http://jasny.github.io/bootstrap/javascript/#fileinput
Upload buttons are a pain to style because it styles the input and not the button.
but you can use this trick:
http://www.quirksmode.org/dom/inputfile.html
Summary:
Take a normal <input type="file"> and put it in an element with position: relative.
To this same parent element, add a normal <input> and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the <input type="file">.
Set the z-index of the <input type="file"> to 2 so that it lies on top of the styled input/image.
Finally, set the opacity of the <input type="file"> to 0. The <input type="file"> now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window. (Note that you can't use visibility: hidden, because a truly invisible element is unclickable, too, and we need the to remain clickable)
Works for me:
Pretty file input field in Bootstrap
Update
jQuery plugin style:
// Based in: http://duckranger.com/2012/06/pretty-file-input-field-in-bootstrap/
// Version: 0.0.3
// Compatibility with: Bootstrap 3.2.0 and jQuery 2.1.1
// Use:
// <input class="nice_file_field" type="file" data-label="Choose Document">
// <script> $(".nice_file_field").niceFileField(); </script>
//
(function( $ ) {
$.fn.niceFileField = function() {
this.each(function(index, file_field) {
file_field = $(file_field);
var label = file_field.attr("data-label") || "Choose File";
file_field.css({"display": "none"});
nice_file_block_text = '<div class="input-group nice_file_block">';
nice_file_block_text += ' <input type="text" class="form-control">';
nice_file_block_text += ' <span class="input-group-btn">';
nice_file_block_text += ' <button class="btn btn-default nice_file_field_button" type="button">' + label + '</button>';
nice_file_block_text += ' </span>';
nice_file_block_text += '</div>';
file_field.after(nice_file_block_text);
var nice_file_field_button = file_field.parent().find(".nice_file_field_button");
var nice_file_block_element = file_field.parent().find(".nice_file_block");
nice_file_field_button.on("click", function(){ console.log("click"); file_field.click() } );
file_field.change( function(){
nice_file_block_element.find("input").val(file_field.val());
});
});
};
})( jQuery );
Simplified answer using parts from other answers, primarily user2309766 and dotcomsuperstar.
Features:
Uses Bootstrap button addon for button and field.
Only one input; multiple inputs would be picked up by a form.
No extra css except "display: none;" to hide the file input.
Visible button fires click event for hidden file input.
split to remove file path uses regex and delimiters '\' and '/'.
Code:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary" onclick="$(this).parent().find('input[type=file]').click();">Browse</span>
<input name="uploaded_file" onchange="$(this).parent().parent().find('.form-control').html($(this).val().split(/[\\|/]/).pop());" style="display: none;" type="file">
</span>
<span class="form-control"></span>
</div>
With some inspiration from other posts above, here is a full solution that combines what looks like a form-control field with an input-group-addon for a clean file input widget that includes a link to the current file.
.input-file { position: relative; margin: 60px 60px 0 } /* Remove margin, it is just for stackoverflow viewing */
.input-file .input-group-addon { border: 0px; padding: 0px; }
.input-file .input-group-addon .btn { border-radius: 0 4px 4px 0 }
.input-file .input-group-addon input { cursor: pointer; position:absolute; width: 72px; z-index:2;top:0;right:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0; background-color:transparent; color:transparent; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<div class="input-group input-file">
<div class="form-control">
current_file_name.pdf
</div>
<span class="input-group-addon">
<a class='btn btn-primary' href='javascript:;'>
Browse
<input type="file" name="field_name" onchange="$(this).parent().parent().parent().find('.form-control').html($(this).val());">
</a>
</span>
</div>
This works perfectly for me
<span>
<input type="file"
style="visibility:hidden; width: 1px;"
id='${multipartFilePath}' name='${multipartFilePath}'
onchange="$(this).parent().find('span').html($(this).val().replace('C:\\fakepath\\', ''))" /> <!-- Chrome security returns 'C:\fakepath\' -->
<input class="btn btn-primary" type="button" value="Upload File.." onclick="$(this).parent().find('input[type=file]').click();"/> <!-- on button click fire the file click event -->
<span class="badge badge-important" ></span>
</span>
Please check out Twitter Bootstrap File Input.
It use very simple solution, just add one javascript file and and paste following code:
$('input[type=file]').bootstrapFileInput();
A simple solution with acceptable outcome:
<input type="file" class="form-control">
And the style:
input[type=file].form-control {
height: auto;
}
Solution for multiple upload
I tweaked two previous answers to include multiple uploads. In this way the label shows the file name, if only one is selected, or x files in the opposite case.
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" multiple="multiple" style="display:none"
onchange="$('#upload-file-info').html(
(this.files.length > 1) ? this.files.length + ' files' : this.files[0].name)">
Files…
</label>
<span class='label label-info' id="upload-file-info"></span>
It may also apply to change the button text and class.
<label class="btn btn-primary" for="multfile">
<input id="multfile" type="file" multiple="multiple" style="display:none"
onchange="$('#multfile-label').html(
(this.files.length == 1) ? this.files[0].name : this.files.length + ' files');
$(this).parent().addClass('btn-success')">
<span id="multfile-label">Files…</span>
</label>
I have Created a Custom upload button to accept only images, which can be modified as per your requirement.
Hope this helps!! :)
(Used Bootstrap framework)
Codepen-link
HTML
<center>
<br />
<br />
<span class="head">Upload Button Re-Imagined</span>
<br />
<br />
<div class="fileUpload blue-btn btn width100">
<span>Upload your Organizations logo</span>
<input type="file" class="uploadlogo" />
</div>
</center>
CSS
.head {
font-size: 25px;
font-weight: 200;
}
.blue-btn:hover,
.blue-btn:active,
.blue-btn:focus,
.blue-btn {
background: transparent;
border: solid 1px #27a9e0;
border-radius: 3px;
color: #27a9e0;
font-size: 16px;
margin-bottom: 20px;
outline: none !important;
padding: 10px 20px;
}
.fileUpload {
position: relative;
overflow: hidden;
height: 43px;
margin-top: 0;
}
.fileUpload input.uploadlogo {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
width: 100%;
height: 42px;
}
/*Chrome fix*/
input::-webkit-file-upload-button {
cursor: pointer !important;
}
JS
// You can modify the upload files to pdf's, docs etc
//Currently it will upload only images
$(document).ready(function($) {
// Upload btn
$(".uploadlogo").change(function() {
readURL(this);
});
function readURL(input) {
var url = input.value;
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "png" || ext == "jpeg" || ext == "jpg" || ext == "gif" || ext == "svg")) {
var path = $('.uploadlogo').val();
var filename = path.replace(/^.*\\/, "");
$('.fileUpload span').html('Uploaded logo : ' + filename);
// console.log(filename);
} else {
$(".uploadlogo").val("");
$('.fileUpload span').html('Only Images Are Allowed!');
}
}
});
this is the best file upload style I like:
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i> <span class="fileupload-preview"></span></div><span class="btn btn-file"><span class="fileupload-new">Select file</span><span class="fileupload-exists">Change</span><input type="file" /></span>Remove
</div>
</div>
you can get demo and more styles at:
http://www.jasny.net/bootstrap/javascript/#fileinput
but using this, you should replace twitter bootstrap with jasny bootstrap files..
regards.
Based on the absolutely brilliant #claviska solution, to whom all the credit is owed.
Full featured Bootstrap 4 file input with validation and help text.
Based on the input group example we have a dummy input text field used for displaying the filename to the user, which gets populated from the onchange event on the actual input file field hidden behind the label button. Aside from including the bootstrap 4 validation support we've also made it possible to click anywhere on the input to open the file dialog.
Three states of the file input
The three possible states are un-validated, valid and invalid with the dummy html input tag attribute required set.
Html markup for the input
We introduce only 2 custom classes input-file-dummy and input-file-btn to properly style and wire the desired behaviour. Everything else is standard Bootstrap 4 markup.
<div class="input-group">
<input type="text" class="form-control input-file-dummy" placeholder="Choose file" aria-describedby="fileHelp" required>
<div class="valid-feedback order-last">File is valid</div>
<div class="invalid-feedback order-last">File is required</div>
<label class="input-group-append mb-0">
<span class="btn btn-primary input-file-btn">
Browse… <input type="file" hidden>
</span>
</label>
</div>
<small id="fileHelp" class="form-text text-muted">Choose any file you like</small>
JavaScript behavioural provisions
The dummy input needs to be read only, as per the original example, to prevent the user from changing the input which may only be changed via the open file dialog. Unfortunately validation does not occur on readonly fields so we toggle the editability of the input on focus and blur ( jquery events onfocusin and onfocusout) and ensure that it becomes validatable again once a file is selected.
Aside from also making the text field clickable, by triggering the button's click event, the rest of the functionality of populating the dummy field was envisioned by #claviska.
$(function () {
$('.input-file-dummy').each(function () {
$($(this).parent().find('.input-file-btn input')).on('change', {dummy: this}, function(ev) {
$(ev.data.dummy)
.val($(this).val().replace(/\\/g, '/').replace(/.*\//, ''))
.trigger('focusout');
});
$(this).on('focusin', function () {
$(this).attr('readonly', '');
}).on('focusout', function () {
$(this).removeAttr('readonly');
}).on('click', function () {
$(this).parent().find('.input-file-btn').click();
});
});
});
Custom style tweaks
Most importantly we don't want the readonly field to jump between grey background and white so we ensure it stays white. The span button doesn't have a pointer cursor but we need to add one for the input anyway.
.input-file-dummy, .input-file-btn {
cursor: pointer;
}
.input-file-dummy[readonly] {
background-color: white;
}
nJoy!
I use http://gregpike.net/demos/bootstrap-file-input/demo.html:
$('input[type=file]').bootstrapFileInput();
or
$('.file-inputs').bootstrapFileInput();
I thought I'd add my threepence worth, just to say how the default .custom-file-label and custom-file-input BS4 file input and how that can be used.
The latter class is on the input group and is not visible. While the former is the visible label and has a :after pseudoelement that looks like a button.
<div class="custom-file">
<input type="file" class="custom-file-input" id="upload">
<label class="custom-file-label" for="upload">Choose file</label>
</div>
You cannot add classes to psuedoelements, but you can style them in CSS (or SASS).
.custom-file-label:after {
color: #fff;
background-color: #1e7e34;
border-color: #1c7430;
pointer: cursor;
}
/*
* Bootstrap 3 filestyle
* http://dev.tudosobreweb.com.br/bootstrap-filestyle/
*
* Copyright (c) 2013 Markus Vinicius da Silva Lima
* Update bootstrap 3 by Paulo Henrique Foxer
* Version 2.0.0
* Licensed under the MIT license.
*
*/
(function ($) {
"use strict";
var Filestyle = function (element, options) {
this.options = options;
this.$elementFilestyle = [];
this.$element = $(element);
};
Filestyle.prototype = {
clear: function () {
this.$element.val('');
this.$elementFilestyle.find(':text').val('');
},
destroy: function () {
this.$element
.removeAttr('style')
.removeData('filestyle')
.val('');
this.$elementFilestyle.remove();
},
icon: function (value) {
if (value === true) {
if (!this.options.icon) {
this.options.icon = true;
this.$elementFilestyle.find('label').prepend(this.htmlIcon());
}
} else if (value === false) {
if (this.options.icon) {
this.options.icon = false;
this.$elementFilestyle.find('i').remove();
}
} else {
return this.options.icon;
}
},
input: function (value) {
if (value === true) {
if (!this.options.input) {
this.options.input = true;
this.$elementFilestyle.prepend(this.htmlInput());
var content = '',
files = [];
if (this.$element[0].files === undefined) {
files[0] = {'name': this.$element[0].value};
} else {
files = this.$element[0].files;
}
for (var i = 0; i < files.length; i++) {
content += files[i].name.split("\\").pop() + ', ';
}
if (content !== '') {
this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
}
}
} else if (value === false) {
if (this.options.input) {
this.options.input = false;
this.$elementFilestyle.find(':text').remove();
}
} else {
return this.options.input;
}
},
buttonText: function (value) {
if (value !== undefined) {
this.options.buttonText = value;
this.$elementFilestyle.find('label span').html(this.options.buttonText);
} else {
return this.options.buttonText;
}
},
classButton: function (value) {
if (value !== undefined) {
this.options.classButton = value;
this.$elementFilestyle.find('label').attr({'class': this.options.classButton});
if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
this.$elementFilestyle.find('label i').addClass('icon-white');
} else {
this.$elementFilestyle.find('label i').removeClass('icon-white');
}
} else {
return this.options.classButton;
}
},
classIcon: function (value) {
if (value !== undefined) {
this.options.classIcon = value;
if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
this.$elementFilestyle.find('label').find('i').attr({'class': 'icon-white '+this.options.classIcon});
} else {
this.$elementFilestyle.find('label').find('i').attr({'class': this.options.classIcon});
}
} else {
return this.options.classIcon;
}
},
classInput: function (value) {
if (value !== undefined) {
this.options.classInput = value;
this.$elementFilestyle.find(':text').addClass(this.options.classInput);
} else {
return this.options.classInput;
}
},
htmlIcon: function () {
if (this.options.icon) {
var colorIcon = '';
if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
colorIcon = ' icon-white ';
}
return '<i class="'+colorIcon+this.options.classIcon+'"></i> ';
} else {
return '';
}
},
htmlInput: function () {
if (this.options.input) {
return '<input type="text" class="'+this.options.classInput+'" style="width: '+this.options.inputWidthPorcent+'% !important;display: inline !important;" disabled> ';
} else {
return '';
}
},
constructor: function () {
var _self = this,
html = '',
id = this.$element.attr('id'),
files = [];
if (id === '' || !id) {
id = 'filestyle-'+$('.bootstrap-filestyle').length;
this.$element.attr({'id': id});
}
html = this.htmlInput()+
'<label for="'+id+'" class="'+this.options.classButton+'">'+
this.htmlIcon()+
'<span>'+this.options.buttonText+'</span>'+
'</label>';
this.$elementFilestyle = $('<div class="bootstrap-filestyle" style="display: inline;">'+html+'</div>');
var $label = this.$elementFilestyle.find('label');
var $labelFocusableContainer = $label.parent();
$labelFocusableContainer
.attr('tabindex', "0")
.keypress(function(e) {
if (e.keyCode === 13 || e.charCode === 32) {
$label.click();
}
});
// hidding input file and add filestyle
this.$element
.css({'position':'absolute','left':'-9999px'})
.attr('tabindex', "-1")
.after(this.$elementFilestyle);
// Getting input file value
this.$element.change(function () {
var content = '';
if (this.files === undefined) {
files[0] = {'name': this.value};
} else {
files = this.files;
}
for (var i = 0; i < files.length; i++) {
content += files[i].name.split("\\").pop() + ', ';
}
if (content !== '') {
_self.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
}
});
// Check if browser is Firefox
if (window.navigator.userAgent.search(/firefox/i) > -1) {
// Simulating choose file for firefox
this.$elementFilestyle.find('label').click(function () {
_self.$element.click();
return false;
});
}
}
};
var old = $.fn.filestyle;
$.fn.filestyle = function (option, value) {
var get = '',
element = this.each(function () {
if ($(this).attr('type') === 'file') {
var $this = $(this),
data = $this.data('filestyle'),
options = $.extend({}, $.fn.filestyle.defaults, option, typeof option === 'object' && option);
if (!data) {
$this.data('filestyle', (data = new Filestyle(this, options)));
data.constructor();
}
if (typeof option === 'string') {
get = data[option](value);
}
}
});
if (typeof get !== undefined) {
return get;
} else {
return element;
}
};
$.fn.filestyle.defaults = {
'buttonText': 'Escolher arquivo',
'input': true,
'icon': true,
'inputWidthPorcent': 65,
'classButton': 'btn btn-primary',
'classInput': 'form-control file-input-button',
'classIcon': 'icon-folder-open'
};
$.fn.filestyle.noConflict = function () {
$.fn.filestyle = old;
return this;
};
// Data attributes register
$('.filestyle').each(function () {
var $this = $(this),
options = {
'buttonText': $this.attr('data-buttonText'),
'input': $this.attr('data-input') === 'false' ? false : true,
'icon': $this.attr('data-icon') === 'false' ? false : true,
'classButton': $this.attr('data-classButton'),
'classInput': $this.attr('data-classInput'),
'classIcon': $this.attr('data-classIcon')
};
$this.filestyle(options);
});
})(window.jQuery);
I modified #claviska answer and works as i like (Bootstrap 3, 4 not tested):
<label class="btn btn-default">
<span>Browse</span>
<input type="file" style="display: none;" onchange="$(this).prev('span').text($(this).val()!=''?$(this).val():'Browse')">
</label>
The following code makes as above the picture
Html
<form>
<div class="row">
<div class="col-lg-6">
<label for="file">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Browse</button>
</span>
<input type="text" class="form-control" id="info" readonly="" style="background: #fff;" placeholder="Search for...">
</div><!-- /input-group -->
</label>
</div><!-- /.col-lg-6 -->
</div>
</div>
<input type="file" style="display: none;" onchange="$('#info').val($(this).val().split(/[\\|/]/).pop()); " name="file" id="file">
</form>
Javascript
<script type="text/javascript">
$(function() {
$("label[for=file]").click(function(event) {
event.preventDefault();
$("#file").click();
});
});
</script>
I have the same problem, and i try it like this.
<div>
<button type='button' class='btn btn-info btn-file'>Browse</button>
<input type='file' name='image'/>
</div>
The CSS
<style>
.btn-file {
position:absolute;
}
</style>
The JS
<script>
$(document).ready(function(){
$('.btn-file').click(function(){
$('input[name="image"]').click();
});
});
</script>
Note :
The button .btn-file must in the same tag as the input file
Hope you found the best solution...
Try following in the Bootstrap v.3.3.4
<div>
<input id="uplFile" type="file" style="display: none;">
<div class="input-group" style="width: 300px;">
<div id="btnBrowse" class="btn btn-default input-group-addon">Select a file...</div>
<span id="photoCover" class="form-control">
</div>
</div>
<script type="text/javascript">
$('#uplFile').change(function() {
$('#photoCover').text($(this).val());
});
$('#btnBrowse').click(function(){
$('#uplFile').click();
});
</script>
Here is alternate trick, it's not the best solution but it just give you a choice
HTML code:
<button clss="btn btn-primary" id="btn_upload">Choose File</button>
<input id="fileupload" class="hide" type="file" name="files[]">
Javascript:
$("#btn_upload").click(function(e){
e.preventDefault();
$("#fileupload").trigger('click');
});
In respect of claviska answer - if you want to show uploaded file name in a basic file upload you can do it in inputs' onchange event. Just use this code:
<label class="btn btn-default">
Browse...
<span id="uploaded-file-name" style="font-style: italic"></span>
<input id="file-upload" type="file" name="file"
onchange="$('#uploaded-file-name').text($('#file-upload')[0].value);" hidden>
</label>
This jquery JS code is responsible will retrieving uploaded file name:
$('#file-upload')[0].value
Or with vanilla JS:
document.getElementById("file-upload").value
No fancy shiz required:
HTML:
<form method="post" action="/api/admin/image" enctype="multipart/form-data">
<input type="hidden" name="url" value="<%= boxes[i].url %>" />
<input class="image-file-chosen" type="text" />
<br />
<input class="btn image-file-button" value="Choose Image" />
<input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
<br />
<br />
<input class="btn" type="submit" name="image" value="Upload" />
<br />
</form>
JS:
$('.image-file-button').each(function() {
$(this).off('click').on('click', function() {
$(this).siblings('.image-file').trigger('click');
});
});
$('.image-file').each(function() {
$(this).change(function () {
$(this).siblings('.image-file-chosen').val(this.files[0].name);
});
});
CAUTION: The three form elements in question MUST be siblings of each other (.image-file-chosen, .image-file-button, .image-file)
http://markusslima.github.io/bootstrap-filestyle/
$(":file").filestyle();
OR
<input type="file" class="filestyle" data-input="false">

Resources