简体   繁体   中英

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

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"> 

try this to get text of selected option

$("#subscription").on('change', function(){
    $('#plan').val(this.options[this.selectedIndex].text);
});

Since you will need to pass the value to store in database so a quick way is to keep the value as swiftbank1###bank1

Split the string with ### on server end and store them separately like this:

 $selectValue = $_POST['select_name'];
 $valueArray = explode("####",$selectValue);

$valueArray[0] will have swiftbank1 and $valueArray[1] will have bank1

使用这个$('#plan').val($('#subscription option:selected').text());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM