Ingus Graholskis Ingus Graholskis - 2 months ago 10
HTML Question

How to save name of select option instead of value

I have this code:



$("#subscription").on('change', function(){
$('#plan').val($(this).val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="bank_name" class="form-control input-md chosen-select" id="subscription">
<option value="">Choose Bank</option>
<option value="swiftbank1">bank 1</option>
<option value="swiftbank2">bank 2</option>
</select>
<input type="text" id="plan" class="form-control input-md" name="swift">





What it does is add swift code in to the input field, that works fine!

Problem is that when I add data on database then both values is what I choose example I choose bank 1 then both will be saved as
swiftbank1
.

I need it to save bank name (
bank 1
) and swift (
swiftbank1
) in database.

I understand that value is what it is but is it possible to add name in database instead of value? In this case this value works to be passed from selection to input.

Thanks

Answer

You can use .text for getting selected text.

$("#subscription").on('change', function(){
var text = $("#subscription :selected").text();
var value = $("#subscription").val();
console.log(text); // this will print text
console.log(value); // this will print value
//var plan = $('#plan').val(text); // this will change the value of plan
$("#plan").attr("value",text); // this will add the value attribute 
$('#plan').val(text); // this will change the value of plan
$('#subscription :selected').val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select name="bank_name" class="form-control input-md chosen-select" id="subscription">
<option value="">Choose Bank</option>
<option value="swiftbank1">bank 1</option>
<option value="swiftbank2">bank 2</option>
</select>
<input type="text" id="plan" class="form-control input-md" name="swift">