Access the label text of a datalist option using jquery - javascript

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'/>

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.

How to show selected value using javascript in laravel

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

Select box options not getting selected by jquery with ajax response data

I have an update form in which the data is pre-populated by an ajax call. All the data is getting populated well except the select box. Im using jquery to populate data.
My select code:
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<!-- <option value="" selected></option> -->
<option value="F">Female</option>
<option value="M">Male</option>
</select>
</div>
Ajax call:
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName);
$("#middleName").val(cust.middleName);
$("#gender2").val(cust.gender);
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
I have tried these but none worked:
$('gender2 option[value='+cust.gender+']').attr('selected', 'selected');
$('#gender2 option[value='+cust.gender+']').prop('selected', true);
$("div.test select").val(cust.gender);
Note: im getting data from backed as cust.gender=M for male and cust.gender=F for female.
Try
$('#gender2').change(function() {var selectvalue =$('#aioConceptName').find(":selected").val(cust.gender);});
$("#gender2").change(function() {
//your ajax
});
Try this
When it comes to select box it requires change() event,
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName).trigger('change');
$("#middleName").val(cust.middleName).trigger('change');
$("#gender2").val(cust.gender).trigger('change');
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
See This Demo is working , now u can put your ajax function inside document ready function , and please check in ajax Response console.log() value is same as your select option value.
$(document).ready(function(){
$('#gender2').val("O");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<option value="F">Female</option>
<option value="M">Male</option>
<option value="O">Other</option>
</select>
</div>

value of an option appended to a select ends with " before the fetched value ends

I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.
Here's the empty select:
<select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>
This is the jQuery code:
$('#SenderSelect').on('change', function() {
$.ajax({
type: "POST",
url: 'operations/inner-operations/getNamesByService.php',
data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
success: function(data) {
var responseObj = jQuery.parseJSON(data);
console.log(responseObj);
$.each(responseObj, function(i, value) {
$("#SenderNames").append('<option value='+value+'>'+value+'</option>');
});
}
});
});
The appended option should look like this:
<option value="First Second">First Second</option>
However, it is appended like this:
<option value="First" second="">First Second</option>
I just realised that I'm not closing the string properly. The append should be like this:
$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');
the value tag must be wrapped by "".

Show/Hide div send all data to database

I have this show/hide div. And I am running into couple issues. I am using CodeIgniter by the way.
First : When I select real-estate the div shows. But if I select Service, the real-estate div won't hide. (Service has no div).
Second : If I select real-estate and fill out the form, and I change my mind and select automobile and fill out the form then send to database, I get all the fields from real-estate and automobile into my database. Which is not what I want.
Third : Is there a different approach if I wanna add more categories and more divs show/hide?
<select id="catid_1" name="catid_1">
<option value=""></option>
<option value="5">Real-Estate</option>
<option value="8">Automobile</option>
<option value="10">Service</option>
</select>
<!--Auto-->
<div id="8" class="forms">
Energie :
<select name="energy">
<option></option>
<option value="Gasoline">Gasoline</option>
<option value="Diesel">Diesel</option>
<option value="GPL">GPL</option>
<option value="Electric">Electric</option>
<option value="Hybrid">Hybrid</option>
</select><br />
Transmission :
<select name="tans">
<option></option>
<option value="Manuel">Manuel</option>
<option value="Automatic">Automatic</option>
</select><br />
Miles :
<input type="text" name="mile"/><br />
Year :
<input type="text" name="year"/><br />
</div>
<!--Realestate-->
<div id="5" class="forms">
Room :
<input type="text" name="room"/><br />
Surface :
<input type="text" name="surface"/><br />
</div>
<!--End Tech-->
$(function() {
$(".forms").hide();
$("#catid_1").change(function() {
var e = $(this).val();
if(e == '8' || e == '5') {
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
});
// Bind to the submit
$('#submit').click(function(e){
e.preventDefault();
// Parse the data only for the displayed div.
var resolve_data = function() {
var output = {};
// Here you place the acceptable fields.
$('.form-active input, .default input').each(function() {
output[$(this).attr('name')] = $(this).val();
});
return output;
};
// Submit the form here.
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: resolve_data(),
beforeSend: function(xhr, settings){
// Before sending, check the data.
alert(settings.data);
},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
});
});
first: service show/hide is not working because you're putting a conditional on the ID:
if(e == '8' || e == '5') { // <<-- remove this conditional
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
second: When you're doing your update, check the value of the drop down box and only update the fields that belong to that choice. Your form should be sending along the value of the option, so that's not to hard to do. For instance, if the select value is 5, only update the room and surface fields in your database. Don't try to clear the form when switching choices, it's safer to do this in the back end.
If you insist on doing it front end, put an actual form in there and .reset() it when changing options.
third: probably, but this seems OK no? Are you not happy with it?
http://jsfiddle.net/zf9BN/1/

Categories