stack kid stack kid - 1 month ago 6
HTML Question

Take input field data to save in select option value

I have this dropdown list with different values. What i am trying to do is whenever I select other option, the hidden div with id=othertype show and I will type in input field and want to save that data but its not working. I can't use the same name attribute twice I know but I don't want a separate column just for other input. Is it possible to save the input value in same column as options? I want value of input field and not the value I am passing in other option which is other itself.

<div class="form-group">
<div class="col-sm-12">
<label for="p_type">Type*:</label>
<select class="form-control" name="qp_type" id="p_type" required>
<option value="Css">CSS</option>
<option value="HTML">HTML</option>
<option value="PhP">PhP</option>
<option value="Other">Other</option>
</select>
</div>
</div>

<div class="form-group" id="otherType" style="display:none;">
<div class="col-sm-12">
<label for="pType">If you chose ‘Other’, please describe below:</label>
<input id="pType" type="text">
</div>
</div>


Script

$('#p_type').on('change',function(){
if( $(this).val()==="Other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});



Answer

Looks like you are trying to use either the input of the text field or the value from the dropdown. You can just enable or disable the one field. The names can be the same, that is not a problem.

<div class="form-group">
    <div class="col-sm-12">
    <label for="p_type">Type*:</label>
    <select class="form-control" name="qp_type" id="p_type" required>
        <option  value="Css" selected>CSS</option>
        <option  value="HTML">HTML</option>
        <option  value="PhP">PhP</option>
        <option  value="Other">Other</option>
    </select>
    </div>
</div>

<div class="form-group" id="otherType" style="display:none;">
    <div class="col-sm-12">
        <label for="pType">If you chose 'Other', please describe below:</label>
        <!-- START OFF WITH THIS ONE DISABLED, NAME IT THE SAME AS ABOVE --->
        <input id="pType" type="text" name="qp_type" disabled>
    </div>
</div>

<script>
$(document).ready(function(){
    $('select[name=qp_type]').change(function(){
        if($(this).val() == 'Other') {
            $('#otherType').show();
            $('#pType').prop('disabled',false);
        }
        else {
            $('#otherType').hide();
            $('#pType').prop('disabled',true);
        }
    });
});
</script>
Comments