简体   繁体   English

如何保存选择选项的名称而不是值

[英]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 . 问题是,当我在数据库上添加数据时,两个值都是我选择的示例,我选择了bank 1,然后两个都将另存为swiftbank1

I need it to save bank name ( bank 1 ) and swift ( swiftbank1 ) in database. 我需要它来将银行名称( bank 1 )和swift( swiftbank1 )保存在数据库中。

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. 您可以使用.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 由于您需要传递值以将其存储在数据库中,因此一种快速的方法是将value保留为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 $valueArray[0]将具有swiftbank1$valueArray[1]将具有bank1

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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