Add database default value to dropdown list using jQuery AJAX - javascript

I'm working with CRUD operation using jQuery AJAX and bootstrap modal in laravel. But the problem is when I want to edit something. I can't populate my dropdown list after an AJAX success request. How can I set database default value in my edit modal Dropdown List?
My Code:
$(document).ready(function() {
$('.acedit').click(function() {
$('#form')[0].reset();
$('#modal_form').modal('show'); // show bootstrap modal
var id = $(this).data('id');
$.ajax({
url: "{{route('academic.edit')}}",
method: 'post',
data: {
id: id,
'_token': "{{csrf_token()}}"
},
success: function(data) {
//$('#mycontrolId').selectmenu('refresh').val(myvalue).attr("selected", "selected");
$('.degree').val(data.degree).attr('selected', true);
$('.divison').val(data.division);
$('.year').val(data.year);
console.log(data); //{id: 2, user_id: 5, degree: "ssc", division: "First", year: "2009", …}
}
});
});
});
My Controller Method:
public function acadedit(Request $request){
$id=$request->id;
$info=Academic::find($id);
return $info;
}
My edit modal Dropdown list:
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>

There is no selected attribute on the <select> element, it's only for the <option>s. However, you don't really need it, because setting the value of the <select> element is enough to change the selection. But you need to match the value exactly with the proper letter casing, so all capital letters in your case.
Change this:
$('.degree').val(data.degree).attr('selected',true);
To:
$('.degree').val(data.degree.toUpperCase());
If you really prefer to do it with the attribute on the <option> instead of the value of the <select>, then you need to add the <option> to the jQuery selector like this:
$('.degree option[value=' + data.degree.toUpperCase() + ']').attr('selected', true);
Demo:
$('.degree option[value=SSC]').attr('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>

If you want to use response data from your Controller by Ajax, then it better to return it in Json format:
Use return response()->json($info); instead of return $info;
As I can see from your console.log output you receive degree: "ssc", whereas
your select option is SSC, so you need to uppercase the data before use it: $('.degree').val(data.degree.toUpperCase()); or to downcase values of select options: <option value="ss">SSC</option>.

Related

how to return string with select box with select option selected as per a given variable

I using Datatable library to show a table in wordpress custom plugin where I need to return selectbox input. The select box option should display the option as it is saved in database but it is showing the first option always.
How to code the same thing in js when the select input is returned for a column in datatable. I have tried the following way:
columns: [{
{
'data': null,
'render': function (data, type, row, meta) {
return '<select class="selectpicker" name="pm" id="pm-' + row.mls + '"><option value="Tafolla">Tafolla</option><option value="Lucy">Lucy</option></select>';
}
},
}]
Well first get the JS value that is selected then based off return call the php value in a separate call not inlineHTML . Try not overcomplicate cross language calls ...
document.getElementById('my-select').addEventListener('change', function() {
console.log('You selected: ', this.value);
//Call PHP values based on selection e.g
if(this.value == 2)
{
var text = " <?php echo ($row['status'] == 'AR')?'selected='selected':''; ?>";
}
});
<select id="my-select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
The other way of doing it is in plain php with HTML select
<select name="formGender">
<option value="">Select...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
//PHP
<?php
if(isset($_POST['formSubmit']) )
{
$varGender = $_POST['formGender'];
}
?>

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

Post URL from multiple <select> elements

I have a page with isotope filter. It's using the combination filters with hash history. So whenever multiple filters are selected it updates the URL like this:
example.com/portfolio/#.filter1&.filter4&.filter6
Then I have a search form with multiple 'select' elements:
<form id="search-form" method="post">
<select>
<option value="filter1">Filter Name</option>
<option value="filter2">Filter Name</option>
<option value="filter3">Filter Name</option>
</select>
<select>
<option value="filter4">Filter Name</option>
<option value="filter5">Filter Name</option>
<option value="filter6">Filter Name</option>
</select>
...
<input type="submit" value="Search" />
</form>
I would like to combine the values from all the selected options of each 'select' element into the single URL and redirect to isotope ('portfolio') page with that combined value.
What would be the best way to achieve that? I'm unable to figure it out.
Try this in your js:
var data = { 'filters' : arrayHere };
$.ajax({
type: 'POST',
url: 'your url here',
data: data,
success: function(re) {
console.log('this is your return', re);
}
})
Make an array using $.each, and populate all values inside the array, then post it view ajax call.
1) Keep the selects out of the form and use IDs to access the selected values.
2) Create a hidden input field in the form
3) use onsubmit="mergeSelects()" javascript event.
4) create a function in js
function mergeSelects(){
//get all the values of selects
// append then and generate a string may be
var mergedStringVal = ""; // <--- store values here
// Set it in the hidden input field created in the form and submit them
document.getElementById("mergedSelects").val(mergedStringVal);
}

Set value of Select option in Javascript

Is there any function to set value of a <select> tag option? I have an ajax response array and I want to put this array in a <select> tag.
This is my code :
$.ajax({
type: "GET",
url: "http://.......api/1/AbsenceType",
dataType: "json",
success: function (data) {
// It doesn't work
var ind = document.getElementById('mySelect').selectedIndex;
document.getElementById('mySelect').options.value="2";//
}
})
And my select tag is :
<select id=mySelect name="mySelect" required="required" data-mini ="true" onchange="myFunction3();"/>
<option id ="type" value=""></option>
</select>
I have an ajax response array and I want to put this array in a tag.
Why don't you just add the options from the array to the select, then set the selected value, like this :
Start with an empty select :
<select id="mySelect" name="mySelect">
</select>
Then use this function as a callback :
var callback = function (data) {
// Get select
var select = document.getElementById('mySelect');
// Add options
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
// Set selected value
$(select).val(data[1]);
}
Demo :
http://jsfiddle.net/M52R9/
See :
Adding options to a select using Jquery/javascript
Set selected option of select box.
try this...
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>`
</select>
$("select").val("3");
visit live demo here: http://jsfiddle.net/y4B68/
thank you
Are you looking for something like that -
DEMO
You can add option like this -
$(function(){
$("#mySelect").html('<option value="2">2</option>');
});
Sorry i just missed that you are doing it in ajax callback. i have also updated in my demo.
you can also this too-
document.getElementById("mySelect").innerHTML = '<option value="2">2</option>';
Why don't you add new option instead of adding a value in option.

Put data into textboxes when item is selected in combobox

I have a combobox with a name and ID of "device". When a device is selected from the combobox e.g. "iPhone 1st Gen", I want a text field with a name and ID of "processor" to fill with the processor name e.g. "Underclocked 412Mhz".
How can I do this?
I can use HTML, PHP and Javascript.
You can do this using Ajax. The most easy way is making the AJAX request with jQuery.
Below an example:
Call a JavaScript function when the 'change' event ocurred on your combobox:
<select id="device" onchange="changeDevice(this.id);">[your options]</select>
Make an ajax request in your JavaScript method:
function changeDevice(deviceID){
$.ajax({
type:'post',
url:'[url of your php file]',
dataType:'text',
data:{device_id:deviceID},
success:function(response){
//assign the text response to your input text
$('#processor').val(response);
}
});}
You could fix this with plain old Javascript
<select name="combo">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="Duck">Duck</option>
<option value="Rabbit">Rabbit</option>
</select>
<input type="text" name="picked" id="picked">
<script>
document.getElementsByName('combo').item(0).onchange = function(){
document.getElementsByName('picked').item(0).value = document.getElementsByName('combo').item(0).value;
}
</script>

Categories