简体   繁体   中英

Input[type='file'] label name

I am trying to modify the look of an input[type='file'] element which I have done,

<div class="own_image_wrapper">
  <%= f.label :image, id: 'own-image-label', class: 'lato-font fileContainer image_button' do %>
  Choose Your Own
  <%= f.file_field :image %>
 <% end %>
</div>

CSS

.fileContainer {
  overflow: hidden;
  position: relative;
}

.fileContainer input[type='file'] {
  cursor: inherit;
  display: block;
  font-size: 999px;
  filter: alpha(opacity=0);
  min-height: 100%;
  min-width: 100%;
  opacity: 0;
  position: absolute;
  right: 0;
  text-align: right;
  top: 0;
}

.image_button{
  padding:15px;
  color:$white;
  background:$blue;
  text-transform:uppercase;
}

The next stage for me is to change the label text once a user selects a file, my first issue is that the event doesn't always fire, leaving a button with no content.

$(document).ready( function() {
// Update Choose your own image label with file name
$( '#own-image-label [type=file]' ).on( 'click', function (){
  var $input = $( this );

  setTimeout( function (){
     $input.parent().text( $input.val().replace(/([^\\]*\\)*/,'') )
   }, 0 )
  } );

});

and when it does fire I can't click the input any more as the following has been removed from the DOM:

<input id="campaign_image" type="file" name="campaign[image]">

and secondly how can I stop the input type['file'] from being removed from the DOM?

Edit

This is the markup before

<label id="own-image-label" class="lato-font fileContainer image_button" for="campaign_image">
  Choose Your Own
  <input id="campaign_image" type="file" name="campaign[image]">
</label>

And then if I select a file called myfile.jpg this is the markup

<label id="own-image-label" class="lato-font fileContainer image_button" for="campaign_image">myfile.jpg</label>

When you set the text of the label , it overwrites its current contents. You need to target the text node itself, and set the value of that:

this.parentNode.childNodes[0].nodeValue = $input.val().replace(/([^\\]*\\)*/,'');

You must ensure that the DOM is ready before you attempt to attach the handler, otherwise it may not be attached. Also, it doesn't look to me like your setTimeout() serves any purpose. If you don't need it for any specific reason, you can remove it.

Here's a fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM