Reputation: 683
I have an input box that allows text (type="text"), beside that I have a select box with 2 options. The first option of the select box is "address" (marked as selected by default), the second is "distance". While the first option requires the input type to be text, the second only requires numbers...
I want to make it so that when the user clicks "Distance" as an option, it changes the input type of the input box beside it to type="number".
<div class="row collapse-col connect-input">
<div class="col-1-2">
<input name="send_address" id="send-address" type="text" placeholder="Address">
</div>
<div class="col-1-2">
<select name="send_dist_type" id="send-dist-type">
<option value="address" selected>Address (Default)</option>
<option value="distance">Distance (km)</option>
</select>
</div>
</div>
I've googled around, I can't seem to find this out... I've asked a couple questions about inputs and JS previously on here, so I know I need to grab them by their ID's. After that, I really don't know.
Pseudo-code:
function addressChange() {
var inputBox = document.getElementById('send-address');
var selectBox = document.getElementById('send-dist-type');
if (selectBox.value.selected == 'distance') {
inputBox.type.change = 'number';
} else {
inputBox.type.change = 'text';
}
}
Am I along the right path? Any help is appreciated.
I want to stay away from jQuery.
Upvotes: 1
Views: 2221
Reputation: 36609
selectBox.value
is enough..value
will be string and it does not have property asselected
. Same goes forinputBox.type
function addressChange() {
var inputBox = document.getElementById('send-address');
this.value == 'distance' ? inputBox.type = 'number' : inputBox.type = 'text';
}
document.getElementById('send-dist-type').addEventListener('change', addressChange);
<div class="row">
<div class="col-1">
<div class="row collapse-col">
<div class="col-1">
<label for="send-address"><b>Address/Distance</b>
</label>
</div>
<div class="row collapse-col connect-input">
<div class="col-1-2">
<input name="send_address" id="send-address" type="text" placeholder="Address">
</div>
<div class="col-1-2">
<select name="send_dist_type" id="send-dist-type">
<option value="address" selected>Address (Default)</option>
<option value="distance">Distance (km)</option>
</select>
</div>
</div>
</div>
</div>
Upvotes: 3
Reputation: 68443
try setAttribute instead
function addressChange() {
var inputBox = document.getElementById('send-address');
var selectBox = document.getElementById('send-dist-type');
inputBox.setAttribute("type", selectBox.value );
}
Upvotes: 2