使用JavaScript从下拉列表L-5.1中获取选定的值

时间:2015-12-29 06:15:37

标签: javascript drop-down-menu http-post laravel-5.1 laravel-blade

我试图使用Javascript获取所选值并将值发送到服务器端,以便使用Laravel-PHP处理它。这是我到目前为止所写的内容,但是我没有在服务器端获得它,我还需要做更多的事情吗?

这是刀片文件:

{!! Form::open(array('url' => 'created-products', 'method' => 'post'), array('id'=>'createproduct')) !!}
{!! Form::token() !!}

    @if(!Auth::check())
        <p><h3>Please login to create product</h3></p>
        @else
            <p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies, null, array('id'=>'companynameId')) !!} </p>
            <p>{!! Form::text('productname', Input::old('productname')) !!}</p>
            <p>{!! Form::hidden('hiddenCompanyName', '', array('id'=>'selectedCompanyHidden')) !!}</p>
            <p>{!! Form::submit('CREATE PRODUCT') !!}</p>

    @endif

    <script>
        var returnedCompany = document.getElementById("companynameId");
        var storedCompany = returnedCompany.options[returnedCompany.selectedIndex].value;

        var hiddenCompanyId = document.getElementsByName('hiddenCompanyName');
        document.createproduct.hiddenCompanyId.value = storedCompany;
        document.forms["createproduct"].submit();
    </script>
{!! Form::close() !!}

这是从刀片文件中获取值的函数:

private static function compareCompany(ProductRequest $productRequest){
        $companyPicked = $productRequest->hiddenCompanyName;
        $listedCompanies = Company::where('user_id', '=', Auth::user()->id);
        $companies = new Company;
        if($companies->user_id === Auth::user()->id)
        {   
            foreach($listedCompanies as $company) {
                if($company->companyname === $companyPicked)
                {
                    return $company->id;
                } 
            }
        }
    }

这是将其保存到数据库中的功能。

public function store(ProductRequest $productRequest)
{
   $product = new Product;
    $company = new Company;
   if($productRequest->isMethod('post')){

   $product->user_id     = Auth::user()->id;
   $product->company_id  = $this->compareCompany($productRequest);
   $product->companyname = $productRequest->companyname;
   $product->productname = $productRequest->productname;

   $product->save();
   return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
   }else{
        return redirect('company-create')->withErrors($productRequest)->withInput();
    }
}

请帮忙。我已经好几天了。升值。

1 个答案:

答案 0 :(得分:0)

您现在拥有的代码会在您做任何事情之前提交表单,您应该添加@echo off echo "start job here" :: Do your work here pause :: remove the pause, it's just for simulating exit 事件:

onsubmit

希望这有帮助。