✓ I'm available for hire! Check out my open source work on Github or drop me an email

Douglas F Shearer

Posts Tagged with jquery

There are 2 matching posts.

Clearing a File Input Field Using JQuery

While working on some file uploads today, I was in need to a way to clear a file input field if a user changed their mind after selecting a file. I came up with the following simple solution.

In my example I place a ‘clear’ link next to the field, but a modified method could be called from anywhere.

HTML

Wrap the field you intend to clear in a span, with a descriptive ID so we can find it.

We’ll also want our ‘clear’ link to be descriptively IDed.

<span id="myfileinput"><input type="file" name="myfile" /></span>
<a href="" id="clearmyfile">clear</a>

JavaScript

Now in our JavaScript (JQuery) we want to add a click event to our clear link which will clear the file input field.

$('#clearmyfile').click(function(){
  var fieldSpan = $('#myfileinput');
  fieldSpan.html(fieldSpan.html());
});

Explanation

Since we can’t write to the value of a file input field due to security concerns, instead we overwrite the contents of the span, with the contents of the span (itself), thus creating a new file input DOM object which doesn’t have a value set.

A crude but working example can be found in this Gist.

 
 

JQuery on Rails

Now, I know I am totally late to the party on this one, but how much does JQuery rock??

For several years now I have done all of my JS stuff using the Prototype and Scriptaculous libraries. I think they’re pretty awesome tools, and certainly being part of the standard Ruby on Rails package has helped them gain a lot of respect and usage.

Today I had to do a fairly complex piece of UI prototyping that involved a lot of complex JS. It took me about an hour to do it with Prototype, but I wasn’t completely satisfied with the results. Some of m fellow ZoeCity devs had been talking about JQuery for a new project we’ve just started, so I thought I’d give it a bash. 20 minutes later I had a functional better implementation, with less, neater looking code.

What About Rails?

As I’ve already mentioned, Rails ships with Prototype, so how do you go about using JQuery in these places? Enter JRails by aaronchi. This is a Rails plugin which replaces all the regular Prototype utilizing helpers with JQuery. Sorted!

JQuery is stupidly easy to learn, especially for anyone from an OOP background, so you should definitely give it a try on your next project.