You can’t transform one select
in input
. Instead, insert a input
guy hidden
after the select
. When selecting the option outro
in the select
, the script hides the select
and shows the input
in place, who will inherit the same name
of select
, and the select
loses the name
to have no conflict when submitting the form.
Behold:
$("#select").change(function(){
if($(this).val() == "outro"){
$(this)
.attr("name", "")
.hide()
.next("input").attr({
"type": "text",
"name": "opcoes"
})
.focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="alvo">
<select name="opcoes" id="select">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="outro">outro</option>
</select>
<input type="hidden" />
</div>
</form>
Reversal
Should you wish to select
reappear, you can include a small button x to reverse the process.
In this case you will have to insert the input
in an element. In this case, I used a span
. In this case, the input
hidden doesn’t have to be the type hidden
, because it will be hidden by span-parent. You also need to change parts of the code given in the first example (such as selectors and capture event types):
$("#select, #alvo span button").on("change click", function(e){
if($(this).val() == "outro" && e.type == "change"){
$(this)
.attr("name", "")
.hide()
.next("span")
.show()
.find("input")
.attr("name", "opcoes")
.focus();
}else if(e.target.id != "select" && e.type == "click"){
$("#select")
.attr("name", "opcoes")
.show()
.val('')
.next("span")
.hide()
.find("input")
.attr("name", "")
.val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="alvo">
<select name="opcoes" id="select">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="outro">outro</option>
</select>
<span style="display: none;">
<input type="text" />
<button type="button">x</button>
</span>
</div>
</form>
It’s hard to understand. You want when selecting the "Other" option in Select it to turn into a normal Input text, that’s it?
– hugocsl