[英]Changing type of an input
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
我在谷歌搜索并遇到了这个: 用jQuery改变输入字段的类型
It says it is possible to do it with straight DOM, but how would I select the class of a sibling with DOM? 它说可以用直接DOM做到这一点,但是我如何选择带有DOM的兄弟类呢?
You can replace the element all together but I don't think you can just change the type attribute see my example. 您可以一起替换元素,但我认为您不能只更改type属性,请参阅我的示例。
$('.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/ http://jsfiddle.net/ECzP4/
here is the jQuery documentation for replaceWith()
http://api.jquery.com/replaceWith/ 这里是
replaceWith()
的jQuery文档http://api.jquery.com/replaceWith/
To get the dom object just take the first item from your jQuery collection: 要获取dom对象,只需从jQuery集合中获取第一项:
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/ 虽然它似乎无法从一个
text
更改为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. 所以我建议有两个输入,并根据需要显示/隐藏它们,而不是尝试更改单个输入的类型。
使用类型为file的auto_image
类添加其所有兄弟。
$(this).siblings('.auto_image').attr('type','file')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.