简体   繁体   English

如何同时获得选择框的文本和值并将其存储到数据库中?

[英]How to get both the text and value of a select box and store it into the database?

I'm trying to store the text and value of the select box i have into my database. 我正在尝试将我拥有的选择框的文本和值存储到数据库中。 I can properly store the value by requesting it from the select box name itself but I'm having troubles with storing the text. 我可以通过从选择框名称本身中请求它来正确存储该值,但是在存储文本时遇到了麻烦。 I have 2 tables namely Item and ItemOrder. 我有2个表,即Item和ItemOrder。

Item Table 项目表

id | id | name 名称

ItemOrder Table ItemOrder表

id | id | item_id(fk from item table) | item_id(来自项目表的fk)| item_name 项目名称

HTML 的HTML

<select name="item" class="form-control select2" id ="item">
    <option value="0" selected="true" disabled="true">Select Item</option>
     @foreach($items as $key => $i)
        <option value="{!!$key!!}">{!!$i!!}</option>
     @endforeach
</select>

ItemController ItemController

public function itemList()
{
  $items = Item::lists('name', 'id');
  return view('employee.itemList', compact('items'));
}
public function storeItem(Request $request){
    $info = array( 'item_name'=>$i,
      'item_id'=>$request['item'],
    DB::table('itemOrder')->insert($info);
  return redirect()->route('dashboard');
}

Routes 路线

Route::get('itemList', ['as' => 'itemList',
        'uses' => 'ItemController@itemLIst']);
Route::post('storeItem', ['as' => 'storeItem',
        'uses' => 'ItemController@storeItem']);

JS JS

$('select[name="item"]').on('change', function () {
 var e = document.getElementById("item");
 var itemText = e.options[e.selectedIndex].text;
 console.log(itemText);
});

I can store the item_id value on my database cause i set item_name to nullable for the meantime. 我可以将item_id值存储在数据库中,因为与此同时我将item_name设置为可空。 I tried to get the text through javascript and i can display it with console.log. 我试图通过javascript获取文本,并且可以通过console.log显示它。 Can anyone help me with storing the selected text as well? 有人可以帮我存储所选文本吗? Or is there a way to get the text through javascript or jquery? 或者有没有办法通过javascript或jquery获取文本?

Did you tried to use 您是否尝试过使用

"<option value=" 

to hold each option's text? 保留每个选项的文本? That way you can retrieve selected option text instead of some numeric code. 这样,您可以检索选定的选项文本,而不是一些数字代码。

Follow my code. 按照我的代码。

$(document).ready(function () 
{
  $('select[name="item"]').on('change', function () 
  {
  alert('Value change to ' +$(this).attr('value')+$(this).text());
   });
 });

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

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