dropdown show right value - php

ve two values in my combo box. Car and bicycle when the user selects one of them it will be stored in the database with 1 or 2. But how do I make sure that when the user edits it the chosen values shows up.
For example I've saved bicycle in the database than when the user wants to edit it it must show bicycle and not car!
I'm working with laravel.
EDIT
<div class="form-group">
<label for="content" class="col-lg-2 control-label">Standaard route</label>
<div class="col-lg-10">
#if($standaardroute->isEmpty())
<label>U heeft nog geen standaardroutes. Maak deze hier aan.</label>
#else
<select class="form-control input-sm" name="standaardroute" id="standaardroute">
#foreach($standaardroute as $route)
<option value="{!! $route->id !!}">{!! $route->van !!} - {!! $route->naar !!}</option>
#endforeach
</select>
</div>
</div>
#endif
EDIT
I've 2 dropdown menus. When one dropdown is selected the other one should receive a number from the database and show the right value for example bicycle. When the first dropdown menu is selected it post a request and receives the values back. When I receive information back for a text box I say:
$("#van").val(result.van);
But how do I have to do this with a dropdown menu?
<script>
$(document).ready(function () {
var xhr;
});
$("#standaardroute").change(function(e) {
csrf = $("#token").attr('content')
option = $(this).val();
$.ajax({
url: '/public/receiveuserinformation',
type: 'POST',
data: { option_id: option },
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', csrf);},
success: function(result) {
$("#van").val(result.van);
//here should be something for the dropdownmenu
}
});
});
</script>

Suppose you've two options in an array: $types = array('1' => 'car', '2' => 'bicycle'); and you're saving it in products table and you've current product data in $product variable
<select>
<?php foreach($types as $type_id => type_name): ?>
<option value="<?php echo $type_id; ?>" <?php if($type_id == $product->type) echo "selected"; ?>>
<?php echo $type_name; ?>
</option>
<?php endforeach; ?>
</select>
EDIT: if you're using blade in laravel then you could simply achieve it by doing this:
{!! Form::label('type', 'Type: ') !!}
{!! Form::select('type', $types !!}
EDIT2: Try this:
<option value="{!! $route->id !!}" {{ ($standaardroute->route == $route->id) ? 'selected':'' }}>{!! $route->van !!} - {!! $route->naar !!}</option>
Note: replace $standaardroute->route your actual variable
EDIT3: Put this inside your success function:
$('#van option').each(function(){
$(this).removeAttr('selected');
if($(this).val() == result.van){
$(this).attr('selected', 'selected');
}
});
Note: I've not tested this

Related

How to display database details immediately when user choose any dropdown value in laravel using ajax?

I want to display details from the selected dropdown. All the details are from the database. The problem is, the price did not display when user choose 1 dropdown value. Which part did I missed? Here is my code:
Route:
Route::get('/prodview', [OrderController::class, 'prodfunct']);
Route::get('/findPrice', [OrderController::class, 'findPrice']);
Controller:
public function prodfunct()
{
$prod=DB::all();//get data from table
return view('orders.order',compact('prod'));//sent data to view
}
public function findPrice(Request $request){
//it will get price if its id match with product id
$p=DB::select('select price from pastas')->where('id',$request->id)->first();
return response()->json($p);
}
View:
<span>
<x-label for="pastaingredient" :value="__('Pasta Ingredient: ')" />
<x-input id="pastaingredient" style="font-size:14px;" class="pasta_ingredient" type="text" name="pastaingredient" value="{{ old('pasta_ingredient') }}" disabled />
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change', '.pastas', function()
{
var ingredient = $(this).find("option:selected").data("ingredient");
$('.pasta_ingredient').val(ingredient);
});
});
</script>
Other way to achieve this would be storing price value as data-attribute and then whenever user select any value from select-box you can simply use $(this).find("option:selected").data("price") to get value from options .
So , you just need to add data-price="{{ $pizzaitem->price }}" to your options i.e :
<option #if(old('pastas') == $pizzaitem->name) selected #endif value="{{ $pizzaitem->name }}" data-price="{{ $pizzaitem->price }}">{{ $pizzaitem->name }}</option>
Then , your jquery code will be like below :
$(document).on('change', '.pastas', function() {
var price = $(this).find("option:selected").data("price");
$('.prod_price').val(price);
});
The function var a=$(this).parent(); return the immediate parent of this. In this case, a is this div:
<div>
<x-label for="pastas" :value="__('Choose pastas:')" />
<select name="pastas" id="pastas" class="pastas">
<option #if(!old('pastas')) selected #endif disabled>Please choose</option>
#foreach ($pastainfo as $pizzaitem)
<option #if(old('pastas') == $pizzaitem->name) selected #endif value="{{ $pizzaitem->name }}">{{ $pizzaitem->name }}</option>
#endforeach
</select>
</div>
so that at this line a.find('.prod_price').val(data.price); JQuery only find prod_price in the a div and can not see it there leading this error.

Assign "select" attribute to jquery select2 dropdown dynamically

I am working on jquery select2 dropdown. I have to display the multiple selected option in select area. For this purpose i loop through each of select2. If condition is met i will assign 'selected' attribute property to option so that it may appears in the select area.
But somehow the select2 fails to display the selected ''.
HTML CODE:
<div class="form-group col-md-12">
<label for="inputsskill">Skill<span class="required-field">*</span></label>
<fieldset>
<select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
#if(!$skills->isEmpty())
#foreach($skills as $skill)
<option value="{{$skill->id}}">{{$skill->name}}</option>
#endforeach
#endif
</select>
</fieldset>
</div>
JQUERY CODE:
// parse skills
var parseData = JSON.parse(skill);
// parseData is an array which contain 1,2,3 values like ['1','2','3']
$("#skill_name > option").each(function() {
// if select2 and array values matches assign selected attribute to that option
if( $.inArray($(this).val(), parseData) !== -1 ) {
$(this).attr('selected', 'selected');
}
});
Select2 Jquery:
$( "#skill_name" ).select2({
});
I dont know where i am going wrong, i would appreciate if someone guide me in this.
Thanks,
you can achieve this functionality with PHP easily.
E.g : fetch skills from the database which you want to preselect and create an array of skills. Then match this in your loop.Like
<div class="form-group col-md-12">
<label for="inputsskill">Skill<span class="required-field">*</span></label>
<fieldset>
<select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
#if(!$skills->isEmpty())
#foreach($skills as $skill)
<option value="{{$skill->id}}" <?php
if(in_array($skill->name, $selectedskillsArray)){
echo $selected = 'selected';
}
?> >{{$skill->name}}</option>
#endforeach
#endif
</select>
</fieldset>
</div>
Try this one.
Jquery solution
$( "#skill_name" ).select2({
});
$('#skill_name').val(["1","2","3"]).trigger('change');

displaying live data what user insert into form

I am trying to make display value from live filling form. For example, selecting value from dropdown select box, then its showing me ID, but I wanted to display value which is DB table.
Suppose, I select field:NSEwhile filling form, its should be live diaply "NSE" but its showed me ID as '1'
exchange table:
below is my code:
JS:
function all_function()
{
value = $("#exchange").val();
if (value != "")
{
$("#exchange_value").html("Selected Exchanges :"+value);
}
}
PHP:
{!! Form::open(['method'=>'POST', 'action'=> 'trades\AddSingleTradeController#store', 'id'=> 'form', 'files'=>true]) !!}
<div class="row">
<div class="form-group col-sm-4">
{!! Form::label('exchange_id', 'Exchanges:') !!}
{!! Form::select('exchange_id', [''=>'Choose Options'] + $exchanges , null, ['class'=>'form-control', 'id'=>'exchange', 'name'=>'exchange_id', 'onchange' => 'all_function()'])!!}
</div>
<p id="exchange_value"></p>
{!! Form::close() !!}
Try this:
function all_function()
{
value = $("#exchange option:selected").text();
if (value != "")
{
$("#exchange_value").html("Selected Exchanges :"+value);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="exchange" id="exchange" onchange="all_function()">
<option value="1">abc</option>
<option value="2">def</option>
<option value="3">ghi</option>
<option value="4">jkl</option>
<option value="5">mno</option>
</select>
<div id="exchange_value"></div>

Laravel AJAX form (receiving data concern)

I have an issue recieving the data from a form which was modified with AJAX.
I have 2 fields: Cinema and Session.
The Session field updates automatically based on which cinema you have chosen. However, when I try to get the session field's value in my controller, it returns as "" (blank) where-as I want it to return what is actually displayed in the drop down box in the form.
Code:
Script:
<script>
$('#cinema').on('change', function(e){
console.log(e)
var cinema_id = e.target.value;
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data
console.log(data)
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value="'+subcatObj.id+'">'+subcatObj.session_time+'</option>');;
});
});
});
</script>
Controller:
public function cart()
{
$formData = array(
'cinema' => Input::get('cinema'),
'sesh' => Input::get('sesh'),
'ticketType' => Input::get('ticketType'),
'count' => Input::get('count')
);
$cinemaDetails = Cinema::find($formData['cinema']);
$session = Session::find($formData['sesh']);
return view('movies/ticketpage/cart')
->with('formData', $formData)
->with('cinemaDetails', $cinemaDetails)
->with('session', $session);
}
View/Blade file:
<div class="container">
<div class="row">
<div class="col-sm-4">
<h2>{{$movie->title}}</h2>
<img src="/WDAAssign2/Assign2-A/{{ $movie->image }}" height="200" width="150">
<p>{{ $movie->description }}</p>
</div>
<div class="col-sm-4">
<h2>Purchase tickets!</h2>
{!! Form::open(array('action'=>'MoviePageController#cart', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Type of ticket:</label>
<br>
<select id= ="ticketType">
<option value="adult">Adult</option>
<option value="concession">Concession</option>
<option value="children">Children</option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
</div>
</div>
</div>
Routes:
Route::post('/movie/ticketpage/cart', 'MoviePageController#cart');

repopulate child dropdow when parent dropdown changed

TL;DR
How to make jQuery request from parent dropdown ( using .change() ) to working url that outputs JSON and repopulate child dropdown.
END TL;DR
I'm using Laravel 5.1 so my code will be a bit Laravel specific but not much since this is beginner level jQuery problem.
I have two dropdowns. One is for categories (parent) and other is for subcategories (child).
My parent dropdown:
<div class="form-group">
{!! Form::label('category_id', '*Categories') !!}
{!! Form::select('category_id', $categories, null) !!}
</div>
which generates
<div>
<label for="category_id">Categories</label>
<select id="category_id" name="category_id">
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
</div>
My child dropdown:
<div sytle="display:none;">
{!! Form::label('subcategory_id', 'Subcategory') !!}
{!! Form::select('subcategory_id', [], null) !!}
</div>
which generates
<div sytle="display:none;">
<label for="subcategory_id">Subcategories</label>
<select id="subcategory_id" name="subcategory_id">
</select>
</div>
I have defined route: subcategoriesfordropdown/{i} to which I send i and it gives me JSON with the children of parent category. For example if I use URL subcategoriesfordropdown/2 I get:
{"3":"Subcategory 1 title","4":"Subcategory 2 title"}
Numbers in "" are subcategories IDs. This is all working properly.
Now I want to repopulate child dropdown with these id/title pairs so that I get:
<div sytle="display:none;">
<label for="subcategory_id">Subcategories</label>
<select id="subcategory_id" name="subcategory_id">
<option value="3">Subcategory 1 title</option>
<option value="4">Subcategory 2 title</option>
</select>
</div>
I made this jQuery script:
<script>
$(document).ready(function(){
$("#category_id").change(function (){
var category = $(this).val();
alert( "Category: " + category );
});
});
</script>
And it pops an alert box with category ID as I change the parent dropdown values. However, instead of alert function I want it to run POST request (I believe POST is the right one here but GET is OK too) to get the JSON data and create options values from it. Also change the display:none; but that shouldn't be a problem.
I tried replacing alert(); with:
$.post( "/subcategoriesfordropdown/" + category, , function( data ){
alert( "Data: " + data );
});
to receive the data given by subcategoriesfordropdown/{i} but I'm failing here.
So here is my TODO list:
run POST request
get JSON data
populate child dropdown with JSON data
remove display:none; attribute
I hope I ain't missing something elese here. Thank you all in advance!
You're definitely on the right tracks.
The only issue I see with your $.post is the extra , after category. I'd also suggest using the "json" tag - it just prevents you have to use json_decode within the function.
To update the select box you can use Javascript along these lines.
(Untested, but theoretically correct barring typos)
$.post( "/subcategoriesfordropdown/" + category, function( data ){
var $select = $('#subcategory_id');
$select.empty();
$.each(data, function(value, text){
$select.append($("<option></option>")
.attr("value", value).text(text));
});
$select.show();
}, "json");

Categories