You can not transform a select
into input
. Instead, enter a input
type hidden
after select
. When you select the option outro
in select
, the script hides select
and shows input
in place, which will inherit the same name
from select
, and select
loses name
to avoid conflict when submitting the form.
See:
$("#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><formaction="">
<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
If you want the select
to reappear, you can add a small x button to revert the process.
In this case, you must enter the input
into an element. In this case, I used span
. In this case, input
hidden does not have to be hidden
, because it will be hidden by span-pai . 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><formaction="">
<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>