1

I want to change the type of an input on click of a button but it doesn't work. I tried this:

$('.addPhoto').click(function(){
 $(this).siblings('.auto_image').prop("type", "file");
});

It doesn't do anything at all. I searched on google and came across this: change type of input field with jQuery

It says it is possible to do it with straight DOM, but how would I select the class of a sibling with DOM?

Community
  • 1
  • 1

3 Answers3

3

You can replace the element all together but I don't think you can just change the type attribute see my example.

$('.addPhoto').on("click",function(){
    $(this).off("click").replaceWith("<input type='file' class='addPhoto'/>");
});

or

$('.addPhoto').one("click",function(){
    $(this).replaceWith("<input type='file' class='addPhoto'/>");
});

http://jsfiddle.net/ECzP4/

here is the jQuery documentation for replaceWith() http://api.jquery.com/replaceWith/

Jake Aitchison
  • 1,009
  • 6
  • 19
  • Wow why didn't I think of that haha. Thanks a lot I will try this. I did use replaceWith before but not off. I looked it up and it's just when you release the button as much as I understood from it –  Aug 15 '13 at 14:38
  • 1
    @Xegano no problem, Hope it answers your question. – Jake Aitchison Aug 15 '13 at 14:41
  • Using `.on()` is unnecessary...just use [`.one()`](http://api.jquery.com/one/) that way you don't need to call `.off()` – Dom Aug 15 '13 at 14:45
  • @milkshake sure thing, great solution btw! – Dom Aug 15 '13 at 14:48
1

To get the dom object just take the first item from your jQuery collection:

var domObject = $(this).siblings('.auto_image')[0]

Although it doesn't seem to be able to change from text to file - http://jsfiddle.net/7HTgA/

So what I would recommend is having two inputs, and show/hide them as required rather than trying to change the type of a single input.

Richard Dalton
  • 34,315
  • 6
  • 69
  • 88
0

Adds all its siblings with the auto_image class with the type - file.

$(this).siblings('.auto_image').attr('type','file')
Venkata Krishna
  • 13,950
  • 5
  • 37
  • 55