How to show selected value using javascript in laravel - javascript

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

Related

Data In Input Box Not Going to JavaScript var

Good day! I want to write an ajax request passing two variables to the controller. The problem is that I cannot get the values from the textboxes to my JavaScript
This is the JavaScript and the HTML code.
When I alert the day variable I get nothing it shows that the field is empty. I am very new to programming
$('#historic_form').submit(function(e) {
e.preventDefault();
var fund_id = $(this).val();
var day = $(this).val();
//data = $('#historic_form').serialize();
$.ajax({
url:'Search/Searchday',
type: 'POST',
dataType:'json',
data: {fund_id: fund_id, day: day},
error: function() {
alert(day);},
success: function(response) {
$("tbody").append("<tr><td>"+title+"</td><td>"+description+"</td></tr>");
}
});
});
And below are my HTML Codes
<select required id="member_id" name="member_id" class="form-control">
<option selected disabled>Select Member</option>
<?php for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->id."'>".$fMembers->row($i)->member_name."</option>";}?>
</select>
<select required class="form-control" id="fund_id" name="fund_id">
<option selected disabled>Select Fund</option>
</select>
<input type="date" required name="day" placeholder="Select a date" class="form-control datepicker hasDatepicker" data-dateformat="dd/mm/yy" id="histDate">
$('#historic_form').submit(function(e) {
Your event handler is triggered by a form submission, so inside the function this will refer to the <form>.
var fund_id = $(this).val();
var day = $(this).val();
<form> elements don't have values. You need to find() the <select> element you want to read the value from and call val() on that.

Access the label text of a datalist option using jquery

I am filling a data-list in html using data from a Json . The options are being appended to the data-list with the value and label text . on click of an option , I want the value and the text to be inserted into a form text field .
The value of the option can be accessed and is successfully inserted into the text field. But I am not able to access the label of the option to insert it.
I have tried using $(this).innerhtml(); , $(this).text(); , $(this).label(); , $(this).innerhtml(); and so on..
all of which turned out to return null value (undefined) instead of the required string.
$(document).ready(function ()
{
$.ajax({
type: 'POST',
url: '#Url.Action("MyJsonFunction")',
datatype: 'json',
success: function (data) {
$.each(data, function (index, data) { $("#myid1").append("<option value='"+data.Value+"'label='"+data.Text+"'></option > ");})},
error: function ()
{
alert("Something went wrong!");}});
$("#myid2").change(function ()
{
var s = $(this).val();
var d = $(this).html();
alert(d);
$("#input1").val(s);
$("#input2").val(d);
});
});
The value of the option is being inserted to the input text field but the label of the option is null when i try to access it .
when i alert it , it displays either an empty string or "undefined" .
$('body').on('change','#myid1',function(){ alert( $(this).find(':selected').attr('label') ) });
Please try this code. I am sure this will work
Try this solution.you have to make any one option as selected, because on form load,none of your options are selected and it will surely alert as undefined.
$(document).ready(function ()
{
$("#colors").trigger('change');
});
$("#colors").change(function () {
var d = $('#colors').find("option:selected").val();
alert(d);
$('#selvalue').val(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<label for="color">Favorite Color</label>
<input list="colors" name="color">
<datalist id="colors">
<option selected=selected value="Green">
<option value="Red">
<option value="Blue">
<option value="Yellow">
<option value="Orange">
</datalist>
<input type='text' id='selvalue' placeholder='Display seleted value'/>

How to display price of an item based on the second select box?

I have a previous question like this but it only applies to 2 select boxes so here I'm asking again if someone can help me with 3 select boxes. I have trouble displaying the price of an item based on the selection of a select box. I have 2 tables namely items and item_details. items table has columns item_id and item_name only. item_details table has columns item_details_id, item_id(fk from items table) item_size and price.
I can display the corresponding items_details on the second select box of the item based on the first select box.
HTML
<td>
<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>
</td>
<td>
<select name="item_details" class="form-control" id="item_details" >
</select>
</td>
<td>
<select name="price" class="form-control" id="price" >
</select>
</td>
ItemController
public function findItemDetails($id)
{
$details = DB::table("item_details")
->where("item_id",$id)
->lists("item_size","id");
return json_encode($details);
}
JS
$('select[name="item"]').on('change', function() {
var itemID = $(this).val();
if(itemID) {
$.ajax({
url: '/findItemDetails/ajax/'+itemID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="item_details"]').empty();
$.each(data, function(key, value) {
$('select[name="item_details"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error:function(){
}
});
}else{
$('select[name="item_details"]').empty();
}
});
Routes
Route::get('findItemDetails/ajax/{id}',array('as'=>'findItemDetails',
'uses'=>'ItemController#findItemDetails'));
I provided all the information needed to make 2 select boxes function but when i tried to search for topics about dynamic boxes that involves 3 select boxes i couldn't find any. I'm new to javascript and laravel, so i tried to duplicate my first code and changed the variables if by any chance i could display the price on the 3rd box but nothing works. Heres what i have.
ItemController
public function findPrice($id)
{
$itemdetails = DB::table("itemdetails")
->lists("price","id");
return json_encode($itemdetails);
}
JS
$('select[name="item_details"]').on('change', function() {
var itemdetailsID = $(this).val();
if(itemdetailsID) {
$.ajax({
url: '/findPrice/ajax/'+itemdetailsID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="price"]').empty();
$.each(data, function(key, value) {
$('select[name="price"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error:function(){
}
});
}else{
$('select[name="price"]').empty();
}
});
Routes
Route::get('findPrice/ajax/{id}',array('as'=>'findPrice',
'uses'=>'ItemController#findPrice'));

Fetching data through ajax and then apply filter using select

I have 3 different select menu: 1.Category 2.State 3.City
I am using ajax to fetch the data on "#searchresult" by using jquery on change method that send data on PHP.
Fetching is going properly but only for one "select" option.
What I want is when user change another "select" option, it will update the current "#searchresult" fetched data.
Like: Suppose, on changing "category" to "car", it fetch all the data of "cars" on "#searchresult" and now on "state" change to "new york", it update the "#searchresult" that are in new york.
I tried many different approches like using multiple if statements to find whether the select is choosen or not, but reached no where.
Thanks in advance.
My code is:
$(document).ready(function() {
$("#category").change(function() {
var data = $("#category option:selected").val();
var category = $("#category option:selected").text();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "category",
data: {
data: data
},
dataType: 'json',
cache: false,
success: function(response) {
$("#searchresult").html("");
for (var i = 0; i <= 5; i++) {
$("#searchresult").append('<div class="col-12 col-sm-10 col-md-4 col-lg-3 col-xl-2 merchant" style="background-image: url(https://im.proptiger.com/1/1543935/6/green-villa-elevation-7990949.jpeg?width=380&height=285);"> <div class="filter"></div> <span class="category">' + category + '</span> <div class="col align-self-end"> <p>' + response.contractor[i].first_name + '</p> <span>' + response.contractor[i].city_name + ',' + response.contractor[i].state_name + '</span> </div> <div class="slideup"> <p>More info?</p> Profile </div> </div>');
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
and PHP is sending data in the form of json.
Thanks
#user5745970 here is sample fiddle I created to give you an idea on what needs to be done. Link to the fiddle is below
The idea is to have 3 different change events for each of your select and trigger a call to your server. What you need to do is send the other select values as data if selected. For example, if you're changing the City when the category is already selected, you need to send both category and city to your server to get you the response. If all 3 server side calls return the same JSON structure, then you can have only 1 success and error callback.
Do change the urls, method types and callbacks accordingly to match what you need.
$(document).ready(function() {
var category = '';
var state = '';
var city = '';
$("#category").on('change', function() {
category = $("#category option:selected").text();
// here you need to check if state or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', category, handleCategorySuccess, handleCategoryError)
});
$("#state").on('change', function() {
state = $("#state option:selected").text();
// here you need to check if category or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', state, handleStateSuccess, handleStateError)
});
$("#city").on('change', function() {
city = $("#city option:selected").text();
// here you need to check if state or category is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', city, handleCitySuccess, handleCityError)
});
});
var ajax = function(url, method, data, successCallBack, errorCallBack) {
$.ajax({
type: method,
url: url,
data: data,
dataType: 'json',
cache: false,
success: successCallBack,
error: errorCallBack
});
}
function handleCategorySuccess(response) {
alert(response);
}
function handleCategoryError() {
alert('error');
}
function handleStateSuccess(response) {
alert(response);
}
function handleStateError() {
alert('error');
}
function handleCitySuccess(response) {
alert(response);
}
function handleCityError() {
alert('error');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
JSFiddle

Dropdown only saves and then display's first value

So to continue my last question (link). I've finally got that sorted out (with help), but now the value of the name is only the first value of the drop down list.
A brief explanation, I have 2 drop down menu's and when you select a option from one (A) the other drop down menu is updated (B). I know it has something to do with an array but I can't figure this out.
Here are my files.
HTML
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<?php
$sttub = str_replace('&', 'en', $stub);
$q = $row["Categorie"];
echo "
<option class='dropdownmenu_A' value='".$sttub."' name='".$q."'>"
.$row["Categorie"]."
<span style='font-size:1.2rem;color:#F8F8F8;'>
(" . $row['x'] . ")
</span>
</option>
";
}}?>
</select>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
JavaScript
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
var $mainName = $(".dropdownmenu_A").attr("name");
// call ajax
$("#sub_cat").empty();
$.ajax({
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_call&main_catid=' + $mainCat + '&main_name=' + $mainName,
success:function(results)
{
// alert(results);
console.log($mainCat,$mainName);
$("#sub_cat").removeAttr("disabled");
$("#sub_cat").append(results);
}
});
}
);
});
function.php
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$q = $_POST['main_catid'];
$x = $_POST['main_name'];
echo '<option value="-1" selected="selected">'.$x.'</option>'.$option;
die();
} // end if
}
I have tried using <select id="main_cat" name="main_cat[]"> like I found on google but this didn't work. Using $x[] = $_POST['main_name']; just echos the word Array. How do I get this to work and display the correct option that is selected and not just the first every time.
To be clear, here are my drop down menu's (sometimes my brain goes faster then I can type, so I hope it's clear).
select{height:30px}
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_A' value='option-1' name='Option 1'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
</select>
<select id="sub_cat" name="sub_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_B' value='sub-option-1' name='Sub Option 1'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
</select>
So right now if I select Option 1 from dropdownmenu_A it only echo's the first value from dropdownmenu_A to dropdownmenu_B and not Option 2 or Option 3.
1- You can't have <span/> tags inside <option/> tags as the latter cannot have any child elements.
2- <option/> doesn't have a name attribute. If you want to create a custom attribute, use HTML5 data attributes. That's what they are for.
3- printf is your new friend.
printf('<option class="dropdownmenu_A" value="%s" data-name="%s">%s (%s)</option>', $sttub, $q, $row["Categorie"], $row['x']);
4- I believe the problem is $(".dropdownmenu_A").attr("name") as this would always pull the same name and not the selected name. In your particular case, I would do
$(function(){
$('#main_cat').change(function(){
var $option = $(this).find('option:selected'),
id = $option.val(),
name = $option.data('name');
// open your browser's console log and ensure that you get the correct values
console.log(id, name);
$("#sub_cat").empty();
// call ajax
$.ajax({
url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data: {
action: 'my_special_ajax_call',
main_catid: id,
main_name: name
},
success: function (results) {
$("#sub_cat").removeAttr('disabled').html(results);
}
});
});
});
You should add a selected attribute to your selected option:
https://www.w3schools.com/tags/att_option_selected.asp

Categories