Custom Upload Button - javascript

hi i was just wondering how you can create you own custom file upload button, because the best i can do is
and what i want to achieve is
if there is anyway of doing this i would be very thankful,
and please can i have answers that explain how to do it with code and not answers with links to websites that allow you to download a button or something like that,Thank You :)

Although some of these answers will create something that looks like you want it to work, they will break down when they try to perform the way that you expect. The file input doesn't style well directly and you will have trouble trying it. However, there is a trick.
The trick is to turn the opacity of the input to 0 and then change the background underneath it to the button style that you want.
.file_button_container,
.file_button_container input {
height: 47px;
width: 263px;
}
.file_button_container {
background: transparent url(http://i.stack.imgur.com/BT5AB.png) left top no-repeat;
}
.file_button_container input {
opacity: 0;
}
<div class="file_button_container"><input type="file" /></div>

I think you can also try doing it this way:
Creating an additional <label for="X"></label> element which you can style easily with CSS
<div class="container">
<label for="upload" class="uploadButton">Upload</label>
<input type="file" name="upload" id="upload">
</div>
like
.container {
position: relative;
}
.uploadButton {
height: 25px;
width: 66px;
display: block;
cursor: pointer;
background: url('http://www.ifunia.com/images/christmas/youtube-upload-button.gif') center center no-repeat;
}
input[type="file"] {
display: block;
width: 66px;
height: 25px;
clip: rect(0px 0px 0px 0px);
position: absolute;
left: 0;
top: 0;
}
<form>
<div class="container">
<label for="upload" class="uploadButton"></label>
<input type="file" name="upload" id="upload" required />
</div>
<hr/>
<button type="submit">Submit</button>
</form>

The arrow isn't something you can "just do with code" and the rounded corners would work fine in firefox, but not in ie using css... if you just need to use a custom image it's easy:
css:
#my_upload_button{
background-image:url(path-to-file.png);
border:none;
}

In Vue JS
If you wanna put the upload image button inside the textarea
use Relative and Absolute position to put the camera icon inside the textarea
use bottom-3 right-4 to find the proper position
<div class="field relative">
<label>Description</label>
<textarea class="textarea" v-model="description" type="text" maxlength="10000"> </textarea>
<label for="upload-file" class="icn icn-camera cursor-pointer absolute bottom-3 right-4">
<input type="file" id="upload-file" hidden ref="file" #change="getImage($event)" accept="image/**" />
</label>
</div>
if not inside the textarea box, just one custom upload button then just keep the code like this
<label for="upload-file" class="icn icn-camera cursor-pointer">
<input type="file" id="upload-file" hidden ref="file" #change="getImage($event)" accept="image/**" />
</label>
change the default upload file icon to a camera icon

Step 1. Create a simple html markup
<div class="fileUpload btn btn-primary">
<span>Upload</span>
<input type="file" class="upload" />
</div>
Step 2. CSS: Tricky Part
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
For demo see here http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

Use the input's label as custom upload button:
<label for="pic" class="uploadfilelabel" >upload </label>
<input type="hidden" name="MAX_FILE_SIZE" value="110000">
<input id="pic" name="pic" type="file" size="110000">
and CSS:
label.uploadfilelabel{/*custom label here*/}
input[type=file]{display:none;}
Notice that we did not display the main input button, because otherwise it will occupy space

I'm too late to answer but someone surely will find this useful in future, no need to use of Javascript or Hidden field too. If you are using Bootstrap then definitely there's no need of btn CSS as well.
#upload_file
{
display: none;
}
.btn-primary {
background-color: #007bff;
border-color: #007bff;
color: #fff;
}
.btn {
-moz-user-select: none;
border: 1px solid transparent;
border-radius: 0.25rem;
display: inline-block;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
padding: 0.375rem 0.75rem;
text-align: center;
transition: color 0.15s ease-in-out 0s, background-color 0.15s ease-in-out 0s, border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
vertical-align: middle;
white-space: nowrap;
}
<label for="upload_file" class="custom-file-upload btn btn-primary"><i class="fa fa-cloud-upload"></i> File Upload</label>
<input class="margin" type="file" formnovalidate id="upload_file" name="file" accept="*">

Here is an approximation to the button you want with css/html
html
<button class="upload">Choose a file to upload...</button>
css
.upload{
border:0;
padding:10px 20px;
-moz-border-radius:10px;
border-radius:10px;
background-color:#4488ee;
color:white;
font-size:16px;
}
demo http://jsfiddle.net/gaby/qdX5d/2/
for rounded corners in pre-IE9 use css3pie

Related

How to recreate an element by giving css property through inputs in javascript or jquery

i had created a layout in which i have a form with multiple inputs and a block element (Div) which has already created. Now i want give value (as in px) in input fields and block should be recreated for e.g if the block has 30px width and 30px height initially now i want to change it through inputs when i submit the form the block should be recreated. i think this is to be done in javascript or jquery. Please help me out of this situation your will will be appericiated. here is code below
This is the Fiddle https://jsfiddle.net/gr0q5ea0/
Html
<div class="form-container">
<form action="" id="myForm" name="myForm">
<div class="recreateBox"></div>
<div class="form-row">
<div class="leftSetction">
<div class="input-container">
<label for="name" class="form-label">Height:</label>
<input type="text" class="form-input inputbox" name="height">
</div>
</div>
<div class="leftSetction">
<div class="input-container">
<label for="name" class="form-label">Width:</label>
<input type="text" class="form-input inputbox" name="width">
</div>
</div>
</div>
<div class="form-row">
<div class="leftSetction">
<div class="input-container">
<label for="name" class="form-label">Border Width:</label>
<input type="text" class="form-input inputbox" name="Borderwidth">
</div>
</div>
<div class="leftSetction">
<div class="input-container">
<label for="name" class="form-label">Border Radius:</label>
<input type="text" class="form-input inputbox" name="Borderradius">
</div>
</div>
</div>
<div class="form-row">
<div class="input-container">
<button type="submit" class="btnSubmit" >Submit</button>
</div>
</div>
</form>
</div>
css
.form-container{
position: relative;
width: 100%;
padding: 8px;
box-sizing: border-box;
background: rgba(40, 91, 255, 0.24);
margin: auto auto 35px auto;
max-width: 50%;
top: 17px;
}
.input-container{
width: 100%;
height:auto;
padding-bottom: 12px;
}
.form-label{
font-weight: bold;
margin-bottom: 10px;
font-size: 15px;
display: block;
color:#000;
}
.form-input{
display: block;
width: 50%;
height: 35px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
.form-row{
position: relative;
width: 100%;
padding: 14px;
display: inline-block;
box-sizing: border-box;
}
.btnSubmit{
padding: 10px 40px;
position: relative;
background: #31708f;
border-radius: 5px;
outline: none;
box-shadow: none;
color: white;
border:none;
}
.leftSetction ,.rightSection{
width: 49%;
padding-top: 12px;
box-sizing: border-box;
padding-right: 30px;
position: relative;
float: left;
}
.inputbox{
width: 100%;
}
.recreateBox{
width:150px;
height:150px;
position: relative;
margin: 0 auto;
padding: 15px;
background: #5cb85c;
}
With jQuery you can solve it like this (demo here https://codepen.io/8odoros/pen/rmOyEN)
$('.btnSubmit').click(function(){
//Get the given values
var h = $('input[name=height]').val();
var w = $('input[name=width]').val();
var bw = $('input[name=Borderwidth]').val();
var br = $('input[name=Borderradius]').val();
//Set the values
$('.recreateBox').css('height',h);
$('.recreateBox').css('width',w);
$('.recreateBox').css('border-width',bw);
$('.recreateBox').css('border-radius',br+'px');//Needs that 'px' to work
});
There's no need to use form submit for this, so I also changed the button type from submit to button
Try using jQuery to solve it. Whenever the form is submitted just give the box a new CSS-attribute:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
// Hook onto the form's submittion-event
$('#myForm').submit( function( event ) {
// Cancel the original submitting-event
event.preventDefault();
// Retrieve the values from the inputfields
var height = $('#myForm input[name="height"]').val();
var width = $('#myForm input[name="width"]').val();
var borderWidth = $('#myForm input[name="Borderwidth"]').val();
var borderRadius = $('#myForm input[name="Borderradius"]').val();
// Retrieve field (best practice for jQuery)
$recreateBox = $('.recreateBox');
// Set CSS-attributes of the box
$recreateBox.css('height', height);
$recreateBox.css('width', width);
$recreateBox.css('border-width', borderWidth);
$recreateBox.css('border-radius', borderRadius + 'px');
});
</script>
Just copy & paste this at the bottom of your file.
Updated JSFiddle: https://jsfiddle.net/gr0q5ea0/5/
Best of luck!
Take value for input height and width and use jquery for modifying the width and height of the box.
var height= $("input[name=height]").val();
$(".recreateBox").css("height", height);
if you know this can be done through jquery what you have tried ?
you can get the value of the input boxes using class selector something like this -
var a = $('.input').val()
and then use that value to set the css od that div -
$(".yourDiv").css({"height": a });
you can do all this on the click event of the button.

Opening file select when clicking on a div not file input tag

I wanted to design an image uploader. For selecting an image we do this:
<input type="file" />
but I don't want to use that regular input, I have a div and I want that when user clicks on that, file selecting dialog opens and after that everything continues in standard way.
I want to use Angular.js rather than jQuery if possible because my project is under Angular.js
You dont need javascript to do this, please dont look at the inline style
<div style="position: relative; border: 1px solid red; width: 50px; height: 30px; line-height: 30px; text-align: center;" >
Open
<input type="file" style="opacity: 0.0; position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 100%; height:100%;" />
</div>
Note you need to add more crossbrowser opacity lines
see demo http://jsfiddle.net/yp2dykn5/
Edited this seams to be a populair question/answer.
So i updated this answer with the information below including cross browser opacity lines support.
div {
position: relative;
border: 1px solid red;
width: 50px;
height: 30px;
line-height: 30px;
text-align: center;
}
.file_upload {
opacity: 0.0;
/* IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
/* IE 5-7 */
filter: alpha(opacity=0);
/* Netscape or and older firefox browsers */
-moz-opacity: 0.0;
/* older Safari browsers */
-khtml-opacity: 0.0;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 100%;
height:100%;
}
<form>
<div>
Open
<input type="file" class="file_upload" />
</div>
</form>
I would give the <input> element the CSS property display: none; Then I would apply whatever styling needed to fit your situation to a <label> element linked to the <input> through the use of the for attribute (link to w3school page). In all browsers I know of, clicking on the <label> of an <input> works the same as clicking on the <input>.
This solution only using CSS and does not use JavaScript. The <label> can be styled in any way that a <div> can be styled.
Edit: I elaborated on my answer since I noticed the complexity of the top answer.
.hide {
display: none;
}
.file_upload {
border: 1px solid red;
padding: 5px;
}
<label for="getFile1" class="file_upload">Open File</label>
<input type="file" id="getFile1" class="hide"/>
My suggestion with Jquery would be to keep a div and an input[type="file"].The input should be made hidden and trigger the click of input using JQuery, like below
HTML
<div id="id">Open</div>
<input id="yourinputname" type="file" name="yourinputname" style="display: none;" />
jQuery
$('#id').on('click', function() {
$('#yourinputname').trigger('click');
});
See the fiddle
My File upload form with bootstrap and fontawesome
<html>
<head>
<link rel="stylesheet" type="text/css" href="path/to/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="path/to/fontawesome-all.css" />
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data" >
<div class="card mb-4 shadow-sm p-4">
<h4 class="my-0 font-weight-normal">Upload File</h4>
<div class="card-body">
<h2 class="card-title">
<label style="cursor: pointer;" for="file_upload">
<span class="text-muted fa fa-upload"></span>
</label>
<input type="file" id="file_upload" class="d-none"/>
</h2>
</div>
</div>
</form>
</body>
</html>
If you are using react: (sorry for the hideous indentation, stack would not let me format it correctly)
#getFile {
display: none;
}
<label htmlFor="getFile">
<FontIcon iconName="photo" className="uploadIcon"/>
<input type="file" id="getFile" />
</label>

Issue with HTML display format?

In my application I need to select the image. So I use input tag of type "file". The UI looks like the following image,
<input type="file" id="fileUploader">
How can I write the above input tag as <a> tag so that when clicking on the camera image I need to select the file,
<a href="#" onClick='#'><img src="img/camera.jpg"/></a>
Try like below for change the default file picker using jquery mobile
HTML is like:
<span class="ui-btn ui-icon-plus ui-btn-icon-left ui-corner-all fileinput-button">
<span>Pick File </span>
<input type="file" name="files" multiple data-role="none"/>
</span>
css is Like:
.fileinput-button {
position: relative;
overflow: hidden;
float: left;
margin-right: 4px;
}
.fileinput-button input {
position: absolute;
top: 0;
right: 0;
margin: 0;
opacity: 0;
filter: alpha(opacity=0);
transform: translate(-300px, 0) scale(4);
font-size: 23px;
direction: ltr;
cursor: pointer;
}
FIDDLE DEMO
Try this:
$(function(){
$('#anchorlink').click(function(){
$(this).replaceWith('<input type="file" id="fileUploader" />');
$('#fileUploader').click();
})
});
<a href="#" id="anchorlink" >click<img src="stylish.png"/></a>
http://jsfiddle.net/dQHh5/3/
A better option than a would be to use a label with for, and keep the input hidden.
Demo: http://jsfiddle.net/abhitalks/GpsAJ/
Markup:
<label for="fileUploader" />
<input type="file" id="fileUploader" />
CSS:
#fileUploader {
display: none;
}
label[for=fileUploader] {
display: inline-block;
width: 128px; height: 128px;
cursor: pointer;
background: url('your-camera-image-here') no-repeat left center;
}
I think this one is what you need
<img onclick="javascript:document.getElementById('myFile').click();" src="http://www.clker.com/cliparts/O/r/K/T/t/n/camera-icon-hi.png" style="width:50px;height:auto" />
<input type="file" id="myFile" style="display:none" />
I just hide my input file and let the onclick attribute of image show the dialog..
Just refer to my sample below.
http://jsfiddle.net/fbB46/

open the file upload dialogue box onclick the image

I want to open the image upload file dialogue box if I click the button tag. Is it possible? If so how can I do it in PHP?
while{
echo "<td><button><img src='".$cfet['productimage']."' width='50' height='40'></button></td>";
}
Include input type="file" element on your HTML page and on the click event of your button trigger the click event of input type file element using trigger function of jQuery
The code will look like:
<input type="file" id="imgupload" style="display:none"/>
<button id="OpenImgUpload">Image Upload</button>
And on the button's click event write the jQuery code like :
$('#OpenImgUpload').click(function(){ $('#imgupload').trigger('click'); });
This will open File Upload Dialog box on your button click event..
<input type="file" id="imgupload" style="display:none"/>
<label for='imgupload'> <button id="OpenImgUpload">Image Upload</button></label>
On click of for= attribute will automatically focus on "file input" and upload dialog box will open
you need to add a little hack to achieve this.
You can hide a file upload(input type=file) behind your button.
and onclick of your button you can trigger your file upload click.
It will open a file upload window on click of button
<button id="btnfile">
<img src='".$cfet['productimage']."' width='50' height='40'>
</button>
<div class="wrapper"> //set wrapper `display:hidden`
<input type="file" id="uploadfile" />
</div>
and some javascript
$("#btnfile").click(function () {
$("#uploadfile").click();
});
here is a fiddle for this example: http://jsfiddle.net/ravi441988/QmyHV/1/embedded/result/
Also, You can write all inline, direct at html code:
<input type="file" id="imgupload">
Upload file
return false; - will be useful to decline anchor action after link was clicked.
<label for="profileImage">
<a style="cursor: pointer;"><em class="fa fa-upload"></em> Change Profile
Image</a></label>
<input type="file" name="profileImage" id="profileImage" style="display: none;">
you can show the file selection dialog with a onclick function, and if a file is choosen (onchange event) then send the form to upload the file
<form id='foto' method='post' action='upload' method="POST" enctype="multipart/form-data" >
<div style="height:0px;overflow:hidden">
<input type="file" id="fileInput" name="fileInput" onchange="this.form.submit()"/>
</div>
<i class='fa fa-camera' onclick="fileInput.click();"></i>
</form>
<input type="file" name="pic1" id="pic1" style="display:none;"/>
<label for="pic1">
<img src="dist/img/picfilename.png">
</label>
Above code is tested and it works.
<button id="OpenImgUpload" onclick="$('#imgupload').trigger('click');">Image Upload</button>
<input type="file" id="imgupload" style="display:none"/>
HTML Code:
<form method="post" action="#" id="#">
<div class="form-group files color">
<input type="file" class="form-control" multiple="">
</div>
CSS:
.files input {
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
padding: 120px 0px 85px 35%;
text-align: center !important;
margin: 0;
width: 100% !important;
height: 400px;
}
.files input:focus{
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
border:1px solid #92b0b3;
}
.files{ position:relative}
.files:after { pointer-events: none;
position: absolute;
top: 60px;
left: 0;
width: 50px;
right: 0;
height: 400px;
content: "";
background-image: url('../../images/');
display: block;
margin: 0 auto;
background-size: 100%;
background-repeat: no-repeat;
}
.color input{ background-color:#f1f1f1;}
.files:before {
position: absolute;
bottom: 10px;
left: 0; pointer-events: none;
width: 100%;
right: 0;
height: 400px;
display: block;
margin: 0 auto;
color: #2ea591;
font-weight: 600;
text-transform: capitalize;
text-align: center;
}
<!-- File input (hidden) -->
<input type="file" id="file1" style="display:none"/>
<!-- Trigger button -->
<a href="javascript:void(0)" onClick="openSelect('#file1')">
<script type="text/javascript">
function openSelect(file)
{
$(file).trigger('click');
}
</script>
<!--Hide input field to open it using button-->
<input type="file" #file11 style="display:none">
and <button type="file" (click)="file11.click()">Open file dialog</button>

Clear icon inside input text

Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?
I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?
I want the icon inside the input text element, something like:
--------------------------------------------------
| X|
--------------------------------------------------
Add a type="search" to your input
The support is pretty decent but will not work in IE<10
<input type="search">
Older browsers
If you need IE9 support here are some workarounds
Using a standard <input type="text"> and some HTML elements:
/**
* Clearable text inputs
*/
$(".clearable").each(function() {
const $inp = $(this).find("input:text"),
$cle = $(this).find(".clearable__clear");
$inp.on("input", function(){
$cle.toggle(!!this.value);
});
$cle.on("touchstart click", function(e) {
e.preventDefault();
$inp.val("").trigger("input");
});
});
/* Clearable text inputs */
.clearable{
position: relative;
display: inline-block;
}
.clearable input[type=text]{
padding-right: 24px;
width: 100%;
box-sizing: border-box;
}
.clearable__clear{
display: none;
position: absolute;
right:0; top:0;
padding: 0 8px;
font-style: normal;
font-size: 1.2em;
user-select: none;
cursor: pointer;
}
.clearable input::-ms-clear { /* Remove IE default X */
display: none;
}
<span class="clearable">
<input type="text" name="" value="" placeholder="">
<i class="clearable__clear">×</i>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Using only a <input class="clearable" type="text"> (No additional elements)
set a class="clearable" and play with it's background image:
/**
* Clearable text inputs
*/
function tog(v){return v ? "addClass" : "removeClass";}
$(document).on("input", ".clearable", function(){
$(this)[tog(this.value)]("x");
}).on("mousemove", ".x", function( e ){
$(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]("onX");
}).on("touchstart click", ".onX", function( ev ){
ev.preventDefault();
$(this).removeClass("x onX").val("").change();
});
// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
/*
Clearable text inputs
*/
.clearable{
background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
border: 1px solid #999;
padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
border-radius: 3px;
transition: background 0.4s;
}
.clearable.x { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
<input class="clearable" type="text" name="" value="" placeholder="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The trick is to set some right padding (I used 18px) to the input and push the background-image right, out of sight (I used right -10px center).
That 18px padding will prevent the text hide underneath the icon (while visible).
jQuery will add the class "x" (if input has value) showing the clear icon.
Now all we need is to target with jQ the inputs with class x and detect on mousemove if the mouse is inside that 18px "x" area; if inside, add the class onX.
Clicking the onX class removes all classes, resets the input value and hides the icon.
7x7px gif:
Base64 string:
data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
Could I suggest, if you're okay with this being limited to html 5 compliant browsers, simply using:
<input type="search" />
JS Fiddle demo
Admittedly, in Chromium (Ubuntu 11.04), this does require there to be text inside the input element before the clear-text image/functionality will appear.
Reference:
Dive Into HTML 5: A form of Madness.
input type=search - search field (NEW) HTML5.
According to MDN, <input type="search" /> is currently supported in all modern browsers:
<input type="search" value="Clear this." />
However, if you want different behavior that is consistent across browsers here are some light-weight alternatives that only require JavaScript:
Option 1 - Always display the 'x': (example here)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
el.addEventListener('click', function(e) {
e.target.previousElementSibling.value = '';
});
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Always display the 'x':</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
Option 2 - Only display the 'x' when hovering over the field: (example here)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
el.addEventListener('click', function(e) {
e.target.previousElementSibling.value = '';
});
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
display: block;
}
.clearable-input > [data-clear-input] {
display: none;
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Only display the 'x' when hovering over the field:</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
Option 3 - Only display the 'x' if the input element has a value: (example here)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
var input = el.querySelector('input');
conditionallyHideClearIcon();
input.addEventListener('input', conditionallyHideClearIcon);
el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
input.value = '';
conditionallyHideClearIcon();
});
function conditionallyHideClearIcon(e) {
var target = (e && e.target) || input;
target.nextElementSibling.style.display = target.value ? 'block' : 'none';
}
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
display: none;
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Only display the 'x' if the `input` element has a value:</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
You could use a reset button styled with an image...
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>
See it in action here: http://jsbin.com/uloli3/63
I've created a clearable textbox in just CSS. It requires no javascript code to make it work
below is the demo link
http://codepen.io/shidhincr/pen/ICLBD
Since none of the solutions flying around really met our requirements, we came up with a simple jQuery plugin called jQuery-ClearSearch -
using it is as easy as:
<input class="clearable" type="text" placeholder="search">
<script type="text/javascript">
$('.clearable').clearSearch();
</script>
​
Example: http://jsfiddle.net/wldaunfr/FERw3/
If you want it like Google, then you should know that the "X" isn't actually inside the <input> -- they're next to each other with the outer container styled to appear like the text box.
HTML:
<form>
<span class="x-input">
<input type="text" class="x-input-text" />
<input type="reset" />
</span>
</form>
CSS:
.x-input {
border: 1px solid #ccc;
}
.x-input input.x-input-text {
border: 0;
outline: 0;
}
Example: http://jsfiddle.net/VTvNX/
Change the text box type as 'search' in the design mode or
<input type="search">
EDIT: I found this link. Hope it helps. http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html
You have mentioned you want it on the right of the input text. So, the best way would be to create an image next to the input box. If you are looking something inside the box, you can use background image but you may not be able to write a script to clear the box.
So, insert and image and write a JavaScript code to clear the textbox.
Use simple absolute positioning - it's not that hard.
jQuery:
$('span').click(function(){
$('input', $(this).parent()).val('');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
Vanilla JS:
var spans = document.getElementsByTagName("span");
function clickListener(e) {
e.target.parentElement.getElementsByTagName("input")[0].value = "";
}
for (let i = 0; i < spans.length; i++) {
spans[i].addEventListener("click", clickListener);
}
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
jQuery Mobile now has this built in:
<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">
Jquery Mobile API TextInput docs
Something like this??
Jsfiddle Demo
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.searchinput{
display:inline-block;vertical-align: bottom;
width:30%;padding: 5px;padding-right:27px;border:1px solid #ccc;
outline: none;
}
.clearspace{width: 20px;display: inline-block;margin-left:-25px;
}
.clear {
width: 20px;
transition: max-width 0.3s;overflow: hidden;float: right;
display: block;max-width: 0px;
}
.show {
cursor: pointer;width: 20px;max-width:20px;
}
form{white-space: nowrap;}
</style>
</head>
<body>
<form>
<input type="text" class="searchinput">
</form>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script> <script>
$(document).ready(function() {
$("input.searchinput").after('<span class="clearspace"><i class="clear" title="clear">&cross;</i></span>');
$("input.searchinput").on('keyup input',function(){
if ($(this).val()) {$(".clear").addClass("show");} else {$(".clear").removeClass("show");}
});
$('.clear').click(function(){
$('input.searchinput').val('').focus();
$(".clear").removeClass("show");
});
});
</script>
</body>
</html>
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>
You can do with this commands (without Bootstrap).
Array.from(document.querySelectorAll('.search-field')).forEach(field => {
field.querySelector('span').addEventListener('click', e => {
field.querySelector('input').value = '';
});
});
:root {
--theme-color: teal;
}
.wrapper {
width: 80%;
margin: 0 auto;
}
div {
position: relative;
}
input {
background:none;
outline:none;
display: inline-block;
width: 100%;
margin: 8px 0;
padding: 13px 15px;
padding-right: 42.5px;
border: 1px solid var(--theme-color);
border-radius: 5px;
box-sizing: border-box;
}
span {
position: absolute;
top: 0;
right: 0;
margin: 8px 0;
padding: 13px 15px;
color: var(--theme-color);
font-weight: bold;
cursor: pointer;
}
span:after {
content: '\2716';
}
<div class="wrapper">
<div class="search-field">
<input placeholder="Search..." />
<span></span>
</div>
</div>
Here's a jQuery plugin (and a demo at the end).
http://jsfiddle.net/e4qhW/3/
I did it mostly to illustrate an example (and a personal challenge). Although upvotes are welcome, the other answers are well handed out on time and deserve their due recognition.
Still, in my opinion, it is over-engineered bloat (unless it makes part of a UI library).
I have written a simple component using jQuery and bootstrap.
Give it a try: https://github.com/mahpour/bootstrap-input-clear-button
Using a jquery plugin I have adapted it to my needs adding customized options and creating a new plugin. You can find it here:
https://github.com/david-dlc-cerezo/jquery-clearField
An example of a simple usage:
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">
<table>
<tr>
<td><input name="test1" id="test1" clas="test" type='text'></td>
<td>Empty</td>
</tr>
<tr>
<td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
<td>Not empty</td>
</tr>
</table>
<script>
$('.test').clearField();
</script>
Obtaining something like this:
No need to include CSS or image files. No need to include that whole heavy-artillery jQuery UI library. I wrote a lightweight jQuery plugin that does the magic for you. All you need is jQuery and the plugin. =)
Fiddle here: jQuery InputSearch demo.

Categories

Resources