I'm trying to passed my selected list in variable. Like this but it prints me a undefined value.
function showUserOptions(a)
{
var b = console.log(a[a.selectedIndex].value);
alert (b);
}
I can get the value using console.log but I want the user click the selected list the value inside in variable will changed.
Form:
<div class = "form-group">
<label for = "to" class = "control-label">To:</label>
<select onChange = "showUserOptions(this)" name = "to" class = "form-control" multiple>
#foreach ($result as $list)
<option value = "{{ $list->id }}">{{ $list->username }}</option>
#endforeach
</select>
</div>
Controller:
public function getDocuments()
{
$result = DB::table('users')->where('id', '!=', Auth::id())->get();
return view ('document.create')->with('result', $result);
}
provide a id to your drop down, and its name will be an array so that it can hold multiple values like:
<select name="myDropDown[]" id="myDropDown" class= "form-control" multiple>
#foreach ($result as $list)
<option value = "{{ $list->id }}">{{ $list->username }}</option>
#endforeach
</select>
$('#myDropDown').change(function(){
var selectedVal = $(this).val();
// it will return the selected values in an array
});
Try this, it work.
Related
A select element with a pre-selected value does not render correctly, if I do not add wire:model to the element, it works well and shows the selected value in the select element.
But I need to add wire:model to save user-updated data
<div class="m-widget4">
#foreach ($this->result as $data)
<div>{{$data->id}}</div>
<select wire:model="list_session_picker.{{ $data->id }}" wire:key="{{ $data->id }}">
<option value="" disabled hidden>Select Session</option>
#foreach ($sessionData as $session)
<option value="{{ $session->id }}">{{ $data->user_session_id == $session->id ? 'selected' : '' }} {{ $session->session }}</option>
#endforeach
</select>
#endforeach
</div>
Componenet.php
public $result = [], $list_session_picker = [];
public $search_picker;
public function render()
{
$data['sessionData'] = Session::all('id', 'session');
$data['sectionData'] = Section::all('id', 'section');
return view('livewire.promote', $data);
}
public function search()
{
$search = ScCompany::query();
if (!empty($this->search_picker)) {
$search->where('session_id', $this->search_picker);
return
$this->result = $search
->whereNull('date_of_enter')
->with(['session:id,session', 'section:id,name'])
->get();
}
}
It works if I remove wire:model, so how could I show the selected value while using wire:model or is there any other way ?
Note** here i set wire:model="list_session_picker.{{ $data->id }}" so the list comes from for each loop can't update each other (on changing the option of one select will not uodate another select element in the list) .
I found this and this solutions, but how to apply them in my case, not much clear to me
You should set the selected element in the livewire component and not in the view. The view will reflect the state of the component thanks to the wire model.
At present you have conflicting views of which element should be selected and they will always be at odds with each other.
Just wire model. If you have an existing item selected, then set it state at the component.
i want to show the selected value to the select option, the value actually selected but cannot show that value on select option form.
for example i have a 3 value it can be choose is anyaman, cendana, and bakulan. when 1 edit that form with value cendana, the showed value is the first sequence (anyaman) but when i open that select option that focused on the true data value (cendana).
This is HTML Script :
<div class="mb-1">
<label class="form-label" for="user-role">Asal Kelompok</label>
<select id="editkelompok_id" name="kelompok_id" class="select2 form-select">
<option disabled="" value=""> <b> Pilih asal kelompok </b></option>
#foreach($kelompok as $data)
<option value="{{$data->id}}">{{$data->nama_desa}} - {{$data->nama_kelompok}} </option>
#endforeach
</select>
</div>
The Controller
public function detaildataanggota($id)
{
$status = anggota::findOrfail($id);
return $status;
}
Java Script
<script type="text/javascript">
function detaildataanggota(id){
$.ajax({
url: "{{url('admin/pendataan/dataanggota/detail')}}" + "/" + id,
dataType: "json",
success: function(status) {
$('#editid').val(status.id);
$('#editnama_anggota').val(status.nama_anggota);
$('#editnik').val(status.nik);
$('#editjabatan').val(status.jabatan);
$('#editjenis_kelamin').val(status.jenis_kelamin);
$('#edittanggal_lahir').val(status.tanggal_lahir);
$('#editalamat').val(status.alamat);
$('#editkelompok_id').val(status.kelompok_id);
},
});
}
</script>
The problem is on #editkelompok_id
Try this
let select = $('#editkelompok_id');
select.on('change',()=>{
// Your stuff
})
or
let options = $('#editkelompok_id').children();
options.each(function() {
let option = $(this);
option.on('change', () => {
select.val(option.val());
})
})
I hope it was useful
I'm working with dependent dropdown select. I'm trying to get the value name from a list to store in my DB, but I getting only the index (number). How to solve this? Can you help me?
I have these codes:
HTML
<div class="form-group col-md-4">
<label for="state">State:</label>
<select name="state"class="form-control state" id="state" onchange="ChangecatList()" required >
<option selected>Select State...</option>
#foreach($state as $k => $v)
<option value="{{$k}}" name="$key">{{ $k }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-4">
<label for="city">City/ City:</label>
<select class="form-control city" id="city" placeholder="City" name="city"></select>
</div>
JS
var catAndActs = {};
catAndActs['AC'] = ['City1','City2'];
function ChangecatList() {
var catList = document.getElementById("state");
var actList = document.getElementById("city");
var selCat = catList.options[catList.selectedIndex].value;
while (actList.options.length) {
actList.remove(0);
}
var cats = catAndActs[selCat];
if (cats) {
var i;
for (i = 0; i < cats.length; i++) {
var cat = new Option(cats[i], i);
actList.options.add(cat);
}
}
}
I'm using Laravel 6 - When I debug -> dd($request), it show me that I'm getting the index.
LARAVEL
+request: Symfony\Component\HttpFoundation\ParameterBag {#52 ▼
#parameters: array:14 [▼
"_token" => "kYkq2DhQ7v5XPjY8Aql7gPu5uWnoDYIxRDQXGza2"
"state" => "AC"
"city" => "7" // <- here
Simply place the value as the second parameter to get the city as the value as shown below
var cat = new Option(cats[i], cats[i]);
You may find the constructor documented here https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option
I'm currently trying to send the values of two dropdowns to a django view. My code would have worked properly had the dropdowns been independent. The problem is that it isn't the case. The first one updates the second one, so I need to make my AJAX post request once the second dropdown has been updated.
Here is my current html/Javascript code:
<select name="d1" class="toChange">
{% for item in items1 %}
<option val="{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<select name="d2">
{% for item in items2 %}
<option val="{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<script type="text/javascript">
function dropdownChange () {
var value_d1 = $(".toChange option:selected").val();
var value_d2 = $("select[name=d2] option:selected").val();
$.ajax({
url: '/myApp/templates/',
type: 'POST',
data: {'d1': value_d1, 'd2': value_d2},
success: function(data) {
var str = '';
data.forEach(function(opt){
str += '<option value="' + opt + '">' + opt + '</option>';
});
document.getElementById("d2").innerHTML = str;
}
});
$(".toChange").change(dropdownChange);
So here the change in d1 updates d2 but the AJAX call is made before d2 gets updated and therefore sends the wrong value to my view. How can I overcome this issue?
UPDATE: adding the code suggested by TM.96
<select id="d1" name="d1" class="toChange">
{% for item in items1 %}
<option val="{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<select id="d2" name="d2">
{% for item in items2 %}
<option val="{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<script type="text/javascript">
let select1 = document.getElementById('d1');
let select2 = document.getElementById('d2');
function onChangeSelect1() {
window.select2.value = window.select1.options[window.select1.selectedIndex].value;
onChangeSelect2();
}
function onChangeSelect2() {
console.log('Value of Select 1: ' + window.select1.value);
console.log('Value of Select 2: ' + window.select2.value);
$.ajax({
url: '/myApp/templates/',
type: 'POST',
data: {'d1': select1, 'd2': select2},
success: function(data) {
var str = '';
data.forEach(function(opt){
str += '<option value="' + opt + '">' + opt + '</option>';
});
document.getElementById("d2").innerHTML = str;
}
});
}
$(".toChange").change(dropdownChange);
</script>
UPDATE 2:
def MyView(request):
if request.method == 'POST' and request.is_ajax:
result_r = request.POST.get('d1')
result_d = request.POST.get('d2')
query_results = data_immo.objects.all()
regions = data_immo.objects.values_list("nom_reg", flat=True).distinct().order_by('nom_reg')
departments = data_immo.objects.values_list("insee_dep").filter(Q(nom_reg=result_r)).distinct()
cities = data_immo.objects.values_list("nom_com").filter(Q(insee_dep=result_d)).distinct()
print(departments)
query_results_dict = {
'query_results': query_results,
'regions': regions,
'departments': departments,
'reg': result_r
}
departmentsVar=[]
for item in departments:
item = int(item[0])
departmentsVar.append(item)
departmentsVar.sort()
departmentsVar = json.dumps(departmentsVar)
citiesVar=[]
for item in cities:
citiesVar.append(item)
citiesVar.sort()
citiesVar = json.dumps(citiesVar)
return HttpResponse(departmentsVar, content_type='application/json')
Technically, I need to return both departmentsVar and citiesVar but for some reasons my attempts have failed. It seems that I can only return one variable (so here departmentsVar). I tried to add the two in a dictionary but it didn't work.
Okay, so I put up a minimal working example for you below:
Server side:
urls.py
urlpatterns = [
path('Ajax/Test', views.ajax_test),
]
views.py
def ajax_test(request):
return JsonResponse(request.GET)
Client side:
HTML
<label for="selectCity">City:</label>
<select id="selectCity" onchange="onChangeSelectCity()">
<option disabled selected value> -- select an option --</option>
<option value="1">Munich</option>
<option value="2">Los Angeles</option>
</select>
<label for="selectState">State:</label>
<select id="selectState" onchange="onChangeSelectState()">
<option disabled selected value> -- select an option --</option>
<option value="1">Bavaria</option>
<option value="2">California</option>
</select>
<label for="selectCountry">Country:</label>
<select id="selectCountry" onchange="onChangeSelectCountry()">
<option disabled selected value> -- select an option --</option>
<option value="1">Germany</option>
<option value="2">United States</option>
</select>
Javascript
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<!-- JavaScript example code -->
<script>
// Set global variables. You can also set these inside the functions and use
// them as local variables.
// When you declare a variable outside the function, it is added in the
// window object internally.
let selectCity = document.getElementById('selectCity');
let selectState = document.getElementById('selectState');
let selectCountry = document.getElementById('selectCountry');
// Triggers if Select City changes.
function onChangeSelectCity() {
// Print values of the select fields in console.
console.log('On change Select City:');
console.log('Value of Select City: ' + window.selectCity.value);
console.log('Value of Select State: ' + window.selectState.value);
console.log('Value of Select Country: ' + window.selectCountry.value);
// Call function that is also called if Select State changes.
onChangeSelectState(window.selectCity.value);
}
// Triggers if Select State changes.
function onChangeSelectState(value = 0) {
// If function got called from onChangeSelectCity.
if (value > 0) {
window.selectState.value = value;
}
// Print values of the select fields in console.
console.log('On change Select State:');
console.log('Value of Select City: ' + window.selectCity.value);
console.log('Value of Select State: ' + window.selectState.value);
console.log('Value of Select Country: ' + window.selectCountry.value);
// Call function that is also called if Select Country changes.
onChangeSelectCountry(window.selectState.value);
}
// Triggers if Select Country changes.
function onChangeSelectCountry(value = 0) {
// If function got called from onChangeSelectState.
if (value > 0) {
window.selectCountry.value = value;
}
// Print values of the select fields in console.
console.log('On change Select Country:');
console.log('Value of Select City: ' + window.selectCity.value);
console.log('Value of Select State: ' + window.selectState.value);
console.log('Value of Select Country: ' + window.selectCountry.value);
// Put your ajax code here...
let url = 'Ajax/Test';
$.ajax({
type: "GET",
data: {
'city': window.selectCity.value,
'state': window.selectState.value,
'country': window.selectCountry.value
},
url: url,
success: function (data) {
console.log(data);
}
});
}
</script>
Explanation:
I put up three select fields (City, State and Country).
If City gets changed, State and Country will get updated corresponding to City.
If State gets changed, Country will get updated corresponding to State. City won't get changed.
If Country gets changed, nothing gets updated. City and State won't get changed.
The ajax call gets triggered on all three cases and sends the correct values (either none or set) to the django view. Also the django view returns the values back and they will get correctly printed in the console.
In my view tests.index is it possible to open my route tests.show by clicking in a select dropdown where datas comes from database ?
My controller :
public function index(Request $request)
{
$tests = DB::table('test')->distinct()->get();
return view('tests.index')->with('tests', $tests);
}
public function show($id)
{
$test = Test::findOrFail($id);
return view('tests.show', compact('test'));
}
My view index :
<select id="apports" type="dropdown-toggle" class="form-control" name="apports" onchange="{{ route("tests.show", $test->id) }}">
<option value="choisir" selected disabled>Choisir</option>
#foreach($tests as $test)
<option class="apports" value="{{$test->id}}">{{$test->apports}}</option>
#endforeach
When I put my route here : onchange I get the error "Undefined variable: test"
when I add a button below the select like that :
<a class="btn btn-small btn-success" href="{{ route("tests.show", $test->id) }}">Show</a>
I get always the last id of the table...
I would prefer not have a button, just when I change value in the select, return tests.show... Is someone could help me please ?
The $test variable is not set in the index view, only the $tests collection is available because you load the view with that:
return view('tests.index')->with('tests', $tests);
You need to use some JavaScript to achieve what you are looking for.
In the index template:
<select id="apports" type="dropdown-toggle" class="form-control" name="apports" onchange="goToTestPage(this.value)">
Then in your JavaScript file:
function goToTestPage(id) {
window.location.href = "link to your show route/"+id;
}
If the test id is changed dynamically by the user, you can't set it on PHP because PHP is executed before the user actually does the selection, so you have to rely on JavaScript
All you need is a javascript snippet to read the select option change and redirect you.
<select id="apports" type="dropdown-toggle" class="form-control" name="apports">
<option value="choisir" selected disabled>Choisir</option>
#foreach($tests as $test)
<option class="apports" value="{{ route("tests.show", $test->id) }}">{{ $test->apports }}</option>
#endforeach
</select>
<script>
$('select').on('change', function (e) {
var link = $("option:selected", this).val();
if (link) {
location.href = link;
}
});
</script>