I have country and state dropdowns on a form. I want state dropdown to automatically change into an input text field when country is selected as US. I could write this code so far
$(function(){
$('#country').on('change',function(){
var selected=$(this).find("option:selected").val();
if(selected=='US'){
//need to write some code to change the dropdown into input text field
}
});
})
Can't think of any code inside if block to change the state dropdown into input text. How can I change the dropdown into input text field upon dynamic selection?
CodePudding user response:
you can use the jQuery css property to require displaying or hiding elements, so you can hide or show the input box or another drop down... like so
$(function(){
$('#country').on('change',function(){
var selected=$(this).find("option:selected").val();
if(selected=='US'){
$('#us_text').css('display', "block")
$('#cities').css('display', "none")
} else {
$('#us_text').css('display', "none")
$('#cities').css('display', "block")
}
});
}).jQuery
#us_text {
display:none;
}
#cities {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
<option selected>-- Select --</option>
<option value="US">us</option>
<option value="GB">GB</option>
<option value="CA">CA</option>
</select>
<input id="us_text" type="text" />
<select id="cities">
<option value="city1">city1</option>
<option value="city2">citey2</option>
</select>
CodePudding user response:
You can change the state dropdown into an input text field by manipulating the DOM with jQuery. Here's an example of how you can do it:
if(selected=='US'){
// hide the state dropdown
$('#state').hide();
// create a new input text field
var input = $('<input>', {
type: 'text',
id: 'state',
name: 'state'
});
// insert the input text field after the country dropdown
input.insertAfter($('#country'));
}
This code first hides the existing state dropdown by calling the hide() method on the #state element. Then it creates a new input text field by calling the $(‘input’, {...}) constructor, passing in the desired properties for the input field (type, id, and name). Finally, it inserts the new input text field after the country dropdown by calling the insertAfter() method on the input field, passing in the #country element as the argument.
You might also want to consider adding a default value for the input text field, and also add some validation to check if the user has entered something or not.