How do I focus the current selection in a HTML form? - javascript

I have a html form with multiple questions that user need to answer, I want to add some style as : when the user clicks a question I want it to be focused and blur the other questions, how should I approach this.
Here is the form I made,but I wan to change the opacity of the div when clicked on the input field please suggest how to approach this.
$(document).on('focus active', 'input, textarea', function(){
$('label[for='+$(this).attr('id')+']').addClass('active');
});
$(document).on('blur', 'input, textarea',function(){
$('label[for='+$(this).attr('id')+']').removeClass('active');
});
input[type=text], input[type="email"],input[type="number"] {
width: 50%;
display: block;
padding: 5px 5px;
margin: 8px 0;
box-sizing: border-box;
border: none;
border-bottom: 2px solid #ccc;
}
input:focus {
outline: none;
}
div {
opacity: 0.5;
}
.active{
font-size: 50px;
color: darkgray;
opacity: 1 px !important;
}
<!doctype html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
</head>
<div>
<label for="contact_form_name"><span class="qno">1.</span> What is your name?*</label>
<input id="contact_form_name" name="contact_form_mail" type="text">
</div>
<div>
<label for="contact_form_phone"><span class="qno">2.</span>What is your contact number?*</label>
<input id="contact_form_phone" name="contact_form_phone" type="number">
</div>
<div>
<label for="contact_form_email"><span class="qno">3.</span>What is your email address?**</label>
<input id="contact_form_email" name="contact_form_email" type="email">
</div>
<div>
<label for="contact_form_city"><span class="qno">4.</span>Which city do you live in?*</label>
<input id="contact_form_city" name="contact_form_city" type="text">
</div>
</body>

You should have dedicated Id for each div(each question will be inside a div i suppose). Later use focus and blur events of javascript based on id
document.getElementById("your_id").blur();
document.getElementById("your_id").focus();
You can also populate an array containing id of those questions and iterate a loop to focus and blur

Hi I would use JQuery to to add a class eg.focused on to the question the user is on, and all the other ones you would add another class eg.non-focused.
JQuery to add class to selected div
$(this).addClass('focused');
now in then add all the other div you add class non-focused
$('class_name_of_all_div').addClass('focused');
so you would have and html layout similar to this
<div class="question">
<input type="text" name="name" >Name</input>
</div>
<div class="question">
<input type="text" name="name" >Name</input>
</div
<div class="question">
<input type="text" name="name" >Name</input>
</div
so your function would look like this
$(".question").click(function() {
$(this).addClass('focused');
$('.question').addClass('focused');
});
now you add the styling for it
.non-focused {
filter: blur(2px);
}
and for focused
.non-focused {
filter: blur(0px) !important;
}
and you should be set.
let me know if you have any problems.

Related

Show checkboxes tethered beneath input box on click

I am looking for a way to have a list of checkboxes slide out from an input box when I click it. Basically what I'm looking for is a way to create an overlay form that's tethered to the input box. This image shows what I have before click (left) and what I want to happen on click (right).
Right now I have a bootstrap modal pop up on click, but obviously that's not very user friendly. Any working solution will do, from pure css to js packages. My front end currently works with just html, css, js & jquery.
I've tried the following, but that shows my checkboxes through/behind the text that's already there.
.change-search__form-container {
display: none;
position: absolute;
width: 300px;
background: #fff;
border: #000;
border-width: 1px;
}
A pure css solution based on previous answers and Pete's comments.
#myDiv{
display:none;
}
#myDiv:hover, #myDiv:focus-within {
display: block;
}
#myInput:focus + #myDiv {display:block}
<input id="myInput" placeholder="search query">
<div id="myDiv">
<input type="checkbox" id="box1">
<label for="box1">Stuff 1</label>
<input type="checkbox" id="box2">
<label for="box2">Stuff 2</label>
<br>
<input type="checkbox" id="box3">
<label for="box3">Stuff 3</label>
<input type="checkbox" id="box4">
<label for="box4">Stuff 4</label>
</div>
The DIV can be shown by using the below jQuery code
$("#searchbox").focus(function(){
$("#searchresults").show();
});
By using this code the DIV won't go away if the focus from textbox is lost
I solved the problem with the help of the comments. My CSS:
#change-search__form-container {
position: relative;
}
#change-search__dropdown-form {
z-index: 1;
display: none;
position: absolute;
width: 300px;
background: #fff;
border: #000;
border-width: 1px;
}
My jQuery:
$('#change-search__form-container').click(function () {
$('#change-search__dropdown-form').show();
});
This way the container shows on clicking the input box, and doesn't disappear when I click elsewhere (on one of the checkboxes, for example).
there is a great post for a very similar problem:
Css Focus on input div appearing
Runs for Safari and soon in chrome..
#myDiv2{display:none;}
#myInput:focus + div { display: block; }
#myDiv1:focus-within #myDiv2 { display: block; }
<div id="MyDiv1">
<input id="myInput" type="text"/>
<div id="myDiv2">
<label class="container">One
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
</div>
<div style="display:none">
<span> aaa </span>
</div>
</div>

Tabbing with popup keyboard needs to select and deselect textboxes

I have a series of text boxes on a page with a custom touch keyboard. The problem is when one clicks the tab on the custom keyboard and goes to the next text box, the text box's gradient does not remove (my class's removeClass('selected') does not function as usual). Even though the cursor moves on. I tried onfocus="myFunction()", css input:focus selector, and js .focus() / .focusout().
HTML
<div class="container">
<div class="control">
<fieldset class="control-input input-name-noread gradient open-keyboard">
<label>Name</label>
<input type="text" class="from" id="preference-name" autocomplete="off" value="George">
</fieldset>
</div>
<div class="control">
<fieldset class="control-input input-name-noread gradient open-keyboard">
<label>Name</label>
<input type="text" class="from" id="preference-name" autocomplete="off" value="George">
</fieldset>
</div><div class="control">
<fieldset class="control-input input-name-noread gradient open-keyboard">
<label>Name</label>
<input type="text" class="from" id="preference-name" autocomplete="off" value="George">
</fieldset>
</div></div>
JQuery
$(".keyboard-key-return").click(function() {
$(".control-input").addClass('gradient');
});
$(".open-keyboard").click(function() {
$(".keyboard").show();
});
$(".open-keyboard-readonly").click(function() {
$(".keyboard").hide();
});
$(".keyboard-close").click(function() {
$(".control-input").addClass('gradient');
});
$(".control-input").click(function() {
$(this).removeClass('gradient');
});
$(".keyboard-close").click(function(){
$(".from").blur();
})
$(".keyboard-key-return").click(function(){
$(".from").blur();
})
$(".control-input").focusout(function(){
$(".from").css({
"background-image": "-webkit-linear-gradient(top, rgb(239, 239, 239), rgb(220, 220, 220))"
});
});
$(".control-input").focusout(function(){
$(this).addClass('gradient');
});
css
.from {
width: 443px;
background-color: transparent;
border: none;
height: 68px;;
outline: none;
font-size: 28px;
margin: 5px 0px 0px 0px;
input:focus{
background-image: none;
}
}
Is there an alternative to these methods to detect where the cursor is or a way to detect the focus event so I can remove the class on tab?
This might be not the cleanest solution, but it is working as expected:
JQuery
$('.gradient').on('click', function(){
$('.gradient').removeClass('selected');
$(this).addClass('selected');
});
$('.gradient').on('keyup', function(e){
$('.gradient').removeClass('selected');
if (e.which == 9) { // is TAB key
$(this).parent().find('.gradient').trigger('click'); // searching for the next element
}
});
CSS
.gradient {
background-image: -webkit-linear-gradient(top, rgb(239, 239, 239), rgb(220, 220, 220));
}
.gradient.selected {
background-image: none;
}
Normally you need to prevent default for TAB key, see:
jQuery: keyup for TAB-key?
Solution
$(".keyboard-key-tab").click(function() {
$(".from").parent().find(document.activeElement).trigger('click');
});
.keyboard-key-tab is the button on the keyboard. When the keyboard opens it's within it's on js class and is no longer able to detect .click() or .focus() on this page unless you force it. .from is the input class on the text box, the code returns to it's parent and searches for the active child (the next text box). The code then forces a click which is handled by the code I already had in place to remove/add classes (in this case gradients).

when a checkbox is checked how to display a different hidden element using javascript

I have a form on my site, which has a dropdown box set to display:none; in CSS. I am trying to reveal the dropdown (display: inline;) when a checkbox of another element is checked. What would be possible solution here?
When, #Give_to_a_specific_Project is checked, #choose_a_specific_project_from_dropdown should be set to CSS as display: inline;
Here is the HTML:
Codepen: http://codepen.io/mizan/pen/yNbqRa
<form method="POST" action="" class="sc-checkout-form" id="hello_donation_form" data-sc-id="1" data-parsley-validate="" novalidate="">
<div class="sc-form-group">
<label>
<input type="checkbox" id="Give_to_a_specific_Project" class="sc-cf-checkbox" name="sc_form_field[Give_to_a_specific_Project]" value="Yes" data-parsley-errors-container="#sc_cf_checkbox_error_1" data-parsley-multiple="sc_form_fieldGive_to_a_specific_Project" data-parsley-id="0210">Give To A Specific Project?</label>
<input type="hidden" id="Give_to_a_specific_Project_hidden" class="sc-cf-checkbox-hidden" name="sc_form_field[Give_to_a_specific_Project]" value="No">
<div id="sc_cf_checkbox_error_1">
<ul class="parsley-errors-list" id="parsley-id-multiple-sc_form_fieldGive_to_a_specific_Project"></ul>
</div>
</div>
<div class="sc-form-group">
<select class="sc-form-control sc-cf-dropdown" id="choose_a_specific_project_from_dropdown" name="sc_form_field[choose_a_specific_project_from_dropdown]" data-parsley-id="8242">
<option value="HeartCrest Educational Center – Tema – Ghana" selected="" data-sc-price="HeartCrest Educational Center – Tema – Ghana">HeartCrest Education</option>
<option value="Hae Mona Children Home – Sebokeng – South Africa" data-sc-price="Hae Mona Children Home – Sebokeng – South Africa">Hae Mona Children Home</option>
<option value="Akuafo Farms – Ghana" data-sc-price="Akuafo Farms – Ghana">Akuafo Farms</option>
</select>
<ul class="parsley-errors-list" id="parsley-id-8242"></ul>
</div>
<div class="sc-form-group">
<label>
<input type="checkbox" id="recurring_monthly_gift" class="sc-cf-checkbox" name="sc_form_field[recurring_monthly_gift]" value="Yes" data-parsley-errors-container="#sc_cf_checkbox_error_2" data-parsley-multiple="sc_form_fieldrecurring_monthly_gift" data-parsley-id="4913">Make this a recurring monthly gift</label>
<input type="hidden" id="recurring_monthly_gift_hidden" class="sc-cf-checkbox-hidden" name="sc_form_field[recurring_monthly_gift]" value="No">
<div id="sc_cf_checkbox_error_2">
<ul class="parsley-errors-list" id="parsley-id-multiple-sc_form_fieldrecurring_monthly_gift"></ul>
</div>
</div>
<div class="sc-form-group">
<label>
<input type="checkbox" id="project_update_by_email" class="sc-cf-checkbox" name="sc_form_field[project_update_by_email]" checked="" value="Yes" data-parsley-errors-container="#sc_cf_checkbox_error_3" data-parsley-multiple="sc_form_fieldproject_update_by_email" data-parsley-id="7080">Receive Project Updates By Email</label>
<input type="hidden" id="project_update_by_email_hidden" class="sc-cf-checkbox-hidden" name="sc_form_field[project_update_by_email]" value="Yes">
<div id="sc_cf_checkbox_error_3">
<ul class="parsley-errors-list" id="parsley-id-multiple-sc_form_fieldproject_update_by_email"></ul>
</div>
</div>
<button class="sc-payment-btn"><span>Give by Credit Card</span></button>
I had to clean up your code quite a bit. There were a number of things wrong:
jQuery isn't loaded in your CodePen project
#choose_a_specific_project_from_dropdown was misspelled
You were not instantiating $(document).ready() correctly
You were attempting to listen for .changed() which doesn't exist
Now we're listening for .click() event
You were not showing/hiding the dropdown correctly. You were using .next() but that isn't necessary since you are referencing it by an ID selector.
Working CodePen project: http://codepen.io/anon/pen/bdWxVE
JavaScript code:
$(document).ready(function() {
$('#Give_to_a_specific_Project').click(function( event ){
if ($(this).is(':checked')) {
$('#choose_a_specific_project_from_dropdown').show();
}
else {
$('#choose_a_specific_project_from_dropdown').hide();
}
});
});
Use the onchange event of the checkbox. onchange check if the box is checked and if it is then show the select box.
If I have understood your question correctly, you can achieve this with CSS alone, with no JavaScript or jQuery. Here's a demo. Click on the [+] button to reveal the text.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Toggle Visibility</title>
<style>
input[type=checkbox] {
position: absolute;
clip:rect(0 0 0 0)
}
input[type=checkbox]~label span::after{
content: "+";
}
label {
position: absolute;
right: 0;
width: 1em;
height: 1em;
background-color: #fff;
border: 1px solid #000;
color: #000;
text-align: center;
}
/* Default State */
p#show-me {
background: #900;
width: 100%;
text-align: center;
overflow: hidden;
color: #fff;
box-sizing: border-box;
font-size: 1.35em;
margin:0 0 1.5em;
display: none;
}
/* Toggled State */
input[type=checkbox]:checked ~ label span::after{
content: "-";
}
input[type=checkbox]:checked ~ p#show-me{
display: inline;
}
</style>
</head>
<body>
<input type="checkbox" id="hide">
<label for="hide" onclick=""><span></span></label>
<p id="show-me">Click on the checkbox to hide this text.</p>
</body>
</html>

Javascript checkbox toggle div hide show

I am looking to have a checkbox (Football) that when
Unchecked:
displays one DIV (FootballChoice) containing a label image for the checkbox that changes with mouseover
Checked:
hides the DIV (FootballChoice)
shows a hidden DIV (FootballChecked) that contains an alternate label image
shows another hidden DIV (FootballTeams).
When unchecked again, this needs to return to it's original state.
Alternatively if anyone knows how to change the label image when checked to the same as the one specified in the mouseover element here, that would also be a usefull altetrnative?
Thank you in advance.
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("value")=="FootballTeams"){
$(".FootballTeams").toggle();
$(".FootballChecked").toggle();
$(".FootballChoice").toggle();
}
});
});
</script>
.FootballChecked {
display: none;
}
.FootballChoice {
display: show;
}
.sport {
display: none;
border: 1px dashed #FF3333;
margin: 10px;
padding: 10px;
background: #003366;
}
<input id="Football" type="checkbox" value="FootballTeams">
<div class="FootballChoice">
<label for="Football" class="FootballChoice">
<img src="http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_100x130.png" onmouseover="this.src='http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_NAME_100x130.png';" onmouseout="this.src='http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_100x130.png';" alt="Football" title="Football">
</label>
</div>
<div class="FootballChecked">
<label for="Football">
<img src="http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_NAME_100x130.png" alt="Football" title="Football">
</label>
</div>
<div class="sport FootballTeams">
Football Teams here
</div>
Do you have to use JavaScript? You could use the CSS Pseudo-selector :checked and the General Siblings Selector to display elements based on whether the checkbox is :checked or not.
E.G:
#football {opacity:0.2;}
.checked {display:none;}
#football:checked ~ .unchecked {display:none;}
#football:checked ~ .checked {display:block;}
label {
display:inline-block;
border:1px solid blue;
padding:20px;
background:url(http://lorempixel.com/100/100/sports)
}
label:hover {
border-color:red;
background:url(http://lorempixel.com/100/100/cats)
}
div {border:1px dotted green;}
<input id="football" type="checkbox" value="1" />
<div class="unchecked">
Unchecked:
displays one DIV
<div id="FootballChoice">
(FootballChoice) containing a
<label for="football">label image for the checkbox that changes with mouseover</label>
</div>
</div>
<div class="checked">
Checked:
hides the DIV (FootballChoice)
shows a hidden DIV
<div id="FootballChecked">
(FootballChecked) that contains an
<label for="football">alternate label image</label>
</div>
shows another hidden DIV .
<div id="FootballTeams">
(FootballTeams)
</div>
When unchecked again, this needs to return to it's original state.
</div>
http://jsfiddle.net/zpz3mvuv/

How to style "input file" with CSS3 / Javascript? [duplicate]

This question already has answers here:
Styling an input type="file" button
(46 answers)
Closed 7 years ago.
I would like to style <input type="file" /> using CSS3.
Alternatively, I would like user to press on a div (that I will style) and this will open the Browse window.
Is that possible to do that using HTML, CSS3, and Javascript / jQuery only ?
I have this rough example that you might want to get some idea...
html​
<div id="file">Chose file</div>
<input type="file" name="file" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
CSS
#file {
display:none;
}​
jQuery
var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function(){
$this = $(this);
$('#file').text($this.val());
})
$('#file').click(function(){
fileInput.click();
}).show();
demo
​​​​​​​​​​​​​​
After checking Reigels idea, and this one, I wrote this simple solution to the common problem of styling a type="file" input field (tested it on Firefox, Safari and Chrome).
<div style="position:relative;">
<div id="file" style="position:absolute;">Click here to select a file</div>
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="document.getElementById('file').innerHTML = this.value;">
</div>
Then you can of course style the "file" div as you want.
And if you want to use a type="text" input instead of a div, simply change innerHTML for value:
<div style="position:relative;">
<input type="text" id="file" style="position:absolute;" placeholder="Click here to select a file">
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="document.getElementById('file').value = this.value;">
</div>
Here is my original answer using jQuery:
<div style="position:relative;">
<div id="file" style="position:absolute;">Click here to select a file</div>
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="$('#file').text($(this).val());">
</div>
I made a custom style for this as well. Check it out
JS Fiddle Demo - Custom Input type="file"
HTML
<input type="file" id="test">
<div class="button-group">
Browse
Save
Clear
</div>
<input type="text" id="testfile"></input>
CSS
body {
padding:100px;
}
input[type="file"] {
position:absolute;
display:none;
}
#testfile {
height: 26px;
text-decoration: none;
background-color: #eee;
border:1px solid #ccc;
border-radius:3px;
float:left;
margin-right:5px;
overflow:hidden;
text-overflow:ellipsis;
color:#aaa;
text-indent:5px;
}
#actionbtnBrowse, #actionbtnSave {
margin:0 !important;
width:60px;
}
JQuery
$("#browse").click(function () {
$("#test").click();
})
$("#save").click(function () {
alert('Run a save function');
})
$("#clear").click(function () {
$('#testfile').val('');
})
$('#test').change(function () {
$('#testfile').val($(this).val());
})
Also add to external resources tab:
https://github.com/necolas/css3-github-buttons/blob/master/gh-buttons.css
Here is how to do it using HTML, CSS and Javascript (without any frameworks):
The idea is to have the <input type='file'> button hidden and use a dummy <div> that you style as a file upload button. On click of this <div>, we call the hidden <input type='file'>.
Demo:
// comments inline
document.getElementById("customButton").addEventListener("click", function(){
document.getElementById("fileUpload").click(); // trigger the click of actual file upload button
});
document.getElementById("fileUpload").addEventListener("change", function(){
var fullPath = document.getElementById('fileUpload').value;
var fileName = fullPath.split(/(\\|\/)/g).pop(); // fetch the file name
document.getElementById("fileName").innerHTML = fileName; // display the file name
}, false);
body{
font-family: Arial;
}
#fileUpload{
display: none; /* do not display the actual file upload button */
}
#customButton{ /* style the dummy upload button */
background: yellow;
border: 1px solid red;
border-radius: 5px;
padding: 5px;
display: inline-block;
cursor: pointer;
color: red;
}
<input type="file" id="fileUpload"> <!-- actual file upload button -->
<div id="customButton">Browse</div> <!-- dummy file upload button which can be used for styling ;) -->
<span id="fileName"></span> <!-- the file name of the selected file will be shown here -->
The fake div is not needed! No Js no extra html. Using only css is possible.
The best way is using the pseudo element :after or :before as an element overt the de input. Then style that pseudo element as you wish. I recomend you to do as a general style for all input files as follows:
input[type="file"]:before {
content: 'Browse';
background: #FFF;
width: 100%;
height: 35px;
display: block;
text-align: left;
position: relative;
margin: 0;
margin: 0 5px;
left: -6px;
border: 1px solid #E0E0E0;
top: -1px;
line-height: 35px;
color: #B6B6B6;
padding-left: 5px;
display: block;
}
--> DEMO
In addition of Reigel,
here is more simpler implementation. You can use this solution on multiple file input fields, too. Hope this helps some people ;-)
HTML (single input)
<input type="file" name="file" />
HTML (multiple input)
<!-- div is important to separate correctly or work with jQuery's .closest() -->
<div>
<input type="file" name="file[]" />
</div>
<div>
<input type="file" name="file[]" />
</div>
<div>
<input type="file" name="file[]" />
</div>
JavaScript
// make all input fields with type 'file' invisible
$(':file').css({
'visibility': 'hidden',
'display': 'none'
});
// add a textbox after *each* file input
$(':file').after('<input type="text" readonly="readonly" value="" class="fileChooserText" /> <input type="button" value="Choose file ..." class="fileChooserButton" />');
// add *click* event to *each* pseudo file button
// to link the click to the *closest* original file input
$('.fileChooserButton').click(function() {
$(this).parent().find(':file').click();
}).show();
// add *change* event to *each* file input
// to copy the name of the file in the read-only text input field
$(':file').change(function() {
$(this).parent().find('.fileChooserText').val($(this).val());
});
Here's an example that I'm using that utilizes jQuery, I've tested against Firefox 11, and Chrome 18, as well as IE9. So its pretty compatible with browsers in my book, though i only work with those three.
HTML
Here's a basic "Customizable" HTML structure.
<span>
File to Upload<br />
<label class="smallInput" style="float:left;">
<input type="file" name="file" class="smallInput" />
</label>
<input type="button" class="upload" value="Upload" style="float:left;margin-top:6px;margin-left:10px;" />
</span>
CSS
Here's a sample of my CSS
label.smallInput {
background:url(images/bg_s_input.gif) no-repeat;
width:168px;
}
JavaScript
This is the heavy lifter.
/* File upload magic form?? */
$("input.smallInput[type=file]").each(function(i){
var id = "__d_file_upload_"+i;
var d_wrap = $('<div/>').attr('id',id).css({'position':'relative','cursor':'text'});
$(this).wrap(d_wrap).bind('change blur focus keyup click',function(){
$("#"+id+" input[type=text]").val($(this).val());
}).css({'opacity':0,'zIndex':9999,'position':'absolute'}).removeClass('smallInput');
obj = $(this);
$("#"+id).append($("<input/>").addClass('smallInput').attr('type','text').css({'zIndex':9998,'position':'absolute'}).bind('click',function(e){obj.trigger('click');$(this).blur();}));
obj.closest('span').children('input.upload[type=button]').bind('click',function(e){
obj.trigger('click');
$(this).blur();
});
});
/* ************************ */
Explanation
The HTML is pretty straight forward, just a simple element, i include the button so it can be named independently from the rest, sure this could be included in the JavaScript, but simply put, I'm a bit on the lazy side. The code searches for all inputs with a class of smallInput that have the type of file this allows you to define default HTML and fallback form structure in case a browser decides to be a pain.
This method only uses JavaScript to ensure delivery, it does not alter any browser behaviors in regards to the file input.
You can modify the HTML and JavaScript to make it very robust, this code suffices my current project so i doubt I'll be making any changes to it.
Caveats
Different browsers treat the value of the file input differently, which in chrome results in c:\fakeroot\ on windows machines.
Uses anonymous functions, (for lack of a better word) which means if you have too many file inputs you can cause the browser to behave slowly on processing.
Ran into the same issue today, but it seems there's an easy way to have your own styles - hide the input, and style the associated label:
<div class="upload">
<label for="my-input"> Upload stuff </label>
<input type="file" id="my-input" name="files[]" />
</div>
CSS:
.upload input{
display: none;
}
.upload label{
background: DarkSlateBlue;
color: white;
padding: 5px 10px;
}
Works in latest Chrome, Firefox and IE 10. Didn't test others
While Reigel's answer conveys the idea, it doesn't really have any style attached to it. I came across this problem recently and despite the plethora of answers on Stack Overflow, none really seemed to fit the bill. In the end, I ended up customizing this so as to have a simple and an elegant solution.
I have also tested this on Firefox, IE (11, 10 & 9), Chrome and Opera, iPad and a few android devices.
Here's the JSFiddle link -> http://jsfiddle.net/umhva747/
$('input[type=file]').change(function(e) {
$in = $(this);
$in.next().html($in.val());
});
$('.uploadButton').click(function() {
var fileName = $("#fileUpload").val();
if (fileName) {
alert(fileName + " can be uploaded.");
}
else {
alert("Please select a file to upload");
}
});
body {
background-color:Black;
}
div.upload {
background-color:#fff;
border: 1px solid #ddd;
border-radius:5px;
display:inline-block;
height: 30px;
padding:3px 40px 3px 3px;
position:relative;
width: auto;
}
div.upload:hover {
opacity:0.95;
}
div.upload input[type="file"] {
display: input-block;
width: 100%;
height: 30px;
opacity: 0;
cursor:pointer;
position:absolute;
left:0;
}
.uploadButton {
background-color: #425F9C;
border: none;
border-radius: 3px;
color: #FFF;
cursor:pointer;
display: inline-block;
height: 30px;
margin-right:15px;
width: auto;
padding:0 20px;
box-sizing: content-box;
}
.fileName {
font-family: Arial;
font-size:14px;
}
.upload + .uploadButton {
height:38px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data">
<div class="upload">
<input type="button" class="uploadButton" value="Browse" />
<input type="file" name="upload" accept="image/*" id="fileUpload" />
<span class="fileName">Select file..</span>
</div>
<input type="button" class="uploadButton" value="Upload File" />
</form>
Hope this helps!!!
Here is a solution with a text field where the user types in the (relative) pathname of the file copy on the server (if authorized) and a submit button to browse the local system for a file and send the form:
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<p><input type="file" name="upload_file" id="upload_file" size="40"/></p>
<p><input type="text" id="upload_filename" name="upload_filename" size="30" maxlength="100" value="<?php echo htmlspecialchars($filename, ENT_COMPAT, 'UTF-8'); ?>"/>
<input type="submit" class="submit submit_upload" id="upload_upload" name="upload_upload" value="Upload"/></p>
</form>
The scripting part hides the file input, clicks it if the user clicks on the submit button, submits the form if the user has picked up a file. If the user tries to upload a file without entering a filename, the focus is first moved to the text field for the filename.
<script type="text/javascript">
var file=$('#upload_file');
var filename=$('#upload_filename');
var upload=$('#upload_upload');
file.hide().change(function() {if (file.val()) {upload.unbind('click').click();}});
upload.click(function(event) {event.preventDefault();if (!filename.val()) {filename.focus();} else {file.click();}});
</script>
Simply style the submit button for a perfect result:
.submit {padding:0;margin:0;border:none;vertical-align:middle;text-indent:-1000em;cursor:pointer;}
.submit_upload {width:100px;height:30px;background:transparent url(../images/theme/upload.png) no-repeat;}
This is my method if i got your point
HTML
<form action="upload.php">
<input type="file" id="FileInput" style="cursor: pointer; display: none"/>
<input type="submit" id="Up" style="display: none;" />
</form>
jQuery
<script type="text/javascript">
$( "#FileInput" ).change(function() {
$( "#Up" ).click();
});
</script>
When you retreive the value of an input field, browser will return a fake path (literally C:\fakepath[filename] in Chrome). So I would add the following to the Javascript solutions:
val=$('#file').val(); //File field value
val=val.replace('/','\\'); //Haven't tested it on Unix, but convert / to \ just in case
val=val.substring(val.lastIndexOf('\\')+1);
$('#textbox').val(val);
Ofc, it could be done in a single line.

Categories