select multiselect values from ajax resonse after edit button click - javascript

I have an Edit button. When onclick event is triggering data from the main table is showing in an input field, but related data from pivot does not get selected from JSON response. In JSON output, I can view both main table data with pivot data related to particular id. But this data is not get selected in a multi-select element.
Main Table : 1)SchoolSubject 2)StudentClass
Pivot Table: Student_Class_School_Subject
Controller
public function EditSubject(Request $request)
{
$id = $request->id; //get id from blade
$subject = SchoolSubject::with('class')->where('id',$id)->first(); //select subject data match with id with class stored in pivot
return response()->json($subject); //output comes with subject and class stored in pivot
}
edit.modal.blade.php
<div class="controls" id="classSelector">
<select name="class_id[]" multiple="multiple" id="classSelect" required="" class="form-control">
<option value="-1" selected="" disabled="">
Select Class
</option>
#foreach ($allClassData as $class)
<option value="{{ $class->id }}">
{{ $class->name }}
</option>
#endforeach
</select>
</div>
view.blade.php
#section
<script>
$(document).on('click', '.editIcon', function(e) {
e.preventDefault();
let id = $(this).attr('id');
var _url = '{{ route('subject.edit.route') }}';
$.ajax({
url: _url,
method: 'get',
data: {
id: id,
_token: '{{ csrf_token() }}'
},
success: function(response) {
console.log(response.class);
$("#subject_id").val(response.id);//data from main table got successfully from same json response
$("#subject_i").val(response.subject); //data from main table got successfully from same json response
var pivotData = response.class; //this is data from pivot table but how to select multislect select box value from this json response
jQuery("#classSelect option").each(function() {
if (jQuery.inArray($(this).val(), response.class) != -1) {
$(this).prop('selected', true);
};
}); //this query is not working
/*var newHTML = [];
for (var i = 0; i < response.class.length; i++) {
newHTML.push('<span>' + response.class[i] + '</span>');
console.log(response.class[i])
}
$("#resultchecker").html(newHTML.join(""));*/
}
});
});
</script>
#endsection
JSON response from pivot table using response.class
JSON response from pivot table using response

Because you have a nested array of objects in your JSON, you have to loop once more and select the id. I'm sure there are better ways to do this, but at least you get the idea.
Change this part
jQuery("#classSelect option").each(function() {
if (jQuery.inArray($(this).val(), response.class) != -1) {
$(this).prop('selected', true);
};
}); //this query is not working
Like this
jQuery("#classSelect option").each(function() {
var $this = jQuery(this);
response.class.forEach(element => {
if($this.val() == element.id) {
$this.prop('selected', true);
}
});
});

Related

Asp.Net Core - Return values from the controller and put the values ​into the inputs by Ajax?

I have a drop down list and I want the value to be sent to the controller when an option is selected,replaceing the returned values ​​in the desired inputs
Html Inputs :
<input type="text" class="form-control js-inputs" id="microchipcode">
<input class="form-control js-inputs" id="fa-horse">
<input type="text" id="fa-fatherhorse" class="form-control js-inputs">
Html DropDown:
$('.js-selected-item').change(function () {
let Value = $(this).val();
$.ajax({
data: { value: Value },
Url: "/Horse/GetHorseByMcode",
type: "post",
success: function (data) {
}
});
});
Controller :
public async Task<IActionResult> GetInfoHorse(string value)
{
var horse = await _coach.GetHorseByMcode(value);
if (horse != null)
{
return Json(horse);
}
return NotFound();
}
Query :
public async Task<Horse> GetHorseByMcode(string value)
{
return await _context.Horses.SingleAsync(h => h.MicrochipCode == value.Trim());
}
If you want to put a value into an input via js, add an ID to the inputs and do the following:
JS:
document.getElementById('//inputId').value = '';
Jquery:
("#//inputId").val("");
How do I access the data inside the object?
You can check the request and response in f12 developer tool Network tab, like below.
and implement frontend code to populate input field(s) in ajax success callback function based on your actual returned data.
For example:
success: function (data) {
$("#fa-fatherhorse").val(data.fatherHorse);
//populate other inputs based on your actual returned data
How to replace Drop Down list ?
If you want to dynamically set the selected value/option of the dropdown, you can try:
$("#dropdown_id_here").val(value_of_selected_option);
If you want to dynamically append <option> to your dropdown, you can try:
var newoption = "<option value='" + option_val + "'>" + option_text + "</option>";
$("#dropdown_id_here").append(newoption);

How to update values of dropdown using another dropdown with AJAX nodejs?

I have two dropdowns. One is for selecting the Main category, the second for selecting the sub category.
I want to be able to populate the sub category based on the Main category selected.
What I have tried so far is using JQUERY and AJAX to listen to change in the value of the dropdown using jquery and send an ajax request to the relevant route.
View
<div class="form-control">
<label for="category">Category</label>
<select name="category" id="category">
<option value='Men'>Men</option>
<option value='Women'>Women</option>
<option value='Sports'>Sports</option>
</select>
</div>
<div class="form-control">
<label for="subcategory">Sub Category</label>
<select id="subcategory" name="subcategory">
</select>
</div>
AJAX and JQUERY
$("#category").on("change", function () {
$("#subcategory").empty();
showValue($(this).val());
});
var data = {};
function showValue(val) {
console.log(val);
data.category = val;
$.ajax({
url: "/admin/update-list",
type: "POST",
data: data,
success: function(result) {
updateDOM(result);
},
error: function (err) {
console.log(err);
}
});
};
var updateDOM = function (result) {
var data = result.data;
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
$("#subcategory").append("<option>"+ data[i] +"</option>");
};
};
/admin/update-list Route
router.post('/update-list', (req,res,next) => {
let data = [];
let category = req.body.category;
console.log('From the ajax call, category is' + category);
if(category = "Men") {
data = [
'Sneakers',
'Boots',
'High Heels',
'Litas',
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Women") {
data = [
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Sports") {
data = [
'Soccer Boots',
'Rugby Boots'
];
res.status(200).json({data});
res.end();
}
});
No matter what option I choose, the second dropdown returns the same data.
I would do this in PHP. Hopefully this conveys what you could adapt to your situation:
<select name="foo" >
</select>
ajax call
$.ajax({
type:'POST',
url:'your_code_page.php',
data:'param1='+variable,
success:function(html){
$('[name="foo"]').html(html);
}
});
PHP post back
echo "<option value=''>Please select a thing</option>"; <<outside loop
while ($row = sqlsrv_fetch_array($results)) {
$value = $row['value'];
$display = $row['display'];
//-display the result of the array
echo "<option value= " . $value . ">" . $display . "</option>"; << options returned in post
}

Controller not getting called though AJAX

I have a jsp page with 2 dropdown. the second dropdown should populate based on the value selected from first dropdown I am using AJAX for this to call a controller method on selecting the first dropdown to return the values for the second dropdown as json. On clicking submit entire form will be submitted to controller method. But on selecting the first dropdown, I am not getting any request on the controller method.
Jsp file
alert("Ok");
("#selectCategory").onChange(function() {
var categoryId = $(this).val();
alert(categoryId);
$.ajax({
type: 'GET',
url: "/categories/" + categoryId,
success: function(data) {
var slctSubcat = $('#selectSubcat'),
option = "";
slctSubcat.empty();
for (var i = 0; i < data.length; i++) {
option = option + "<option value='" + data[i].id + "'>" +
data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error: function() {
alert("error");
}
});
});
<form action="/show" method="post" modelAttribute="model">
<select class="form-control" id="selectCategory" name="sel">
<option value="Alto">Alto</option>
<option value="Esteem">Esteem</option>
</select> <br>
<select class="form-control" id="selectSubcat">
<option value="-1" label="-Select-" />
</select>
<input type="Submit" value="Submit" />
</form>
Controller method
#GetMapping("/categories/{categoryId}")
#ResponseBody
public List<String> get(#PathVariable("categoryId") String categoryId)
{
System.out.println("inside controller get "+categoryId);
ArrayList<String> l= new ArrayList<String>();
if(categoryId.equals("Alto"))
{
l.add("Alto Model 1");
l.add("Alto Model 2");
return l;
}
else if(categoryId.equals("Esteem"))
{
l.add("Esteem Model 1");
l.add("Esteem Model 2");
return l;
}
return null;
}
If I make a separate rest call to that controller method , I am getting the response as json [
"Esteem Model 1",
"Esteem Model 2"
], but through ajax, the request is not going.I am new to Ajax. Can someone please correct me if the below ajax code is wrong ?

Add ajax return value to selectbox?

I am trying to insert a value from my database to select box using it's ID. this my code for that
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$("#brnch_name").val(segments[17].trim());
}
});
My value has returned successfully. But, it shows nothing to my select box. Can anyone help me please?
You need to add proper html to select. Something like
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>"
}
And then $("#brnch_name").html(html).
For this example, I assume you are getting response in json format
Here is my solution:
$("#brnch_name").empty(); //clear the drop down box
for (var i=0;i<segments.length;i++)
{
html="<option value=\""+segments[i]+"\">"+segments[i]+"</option>";
$("#brnch_name").append(html);
}
You can loop the response and append to select with $('#branch_name').append($('<option>', { value: item.value, text : item.text })); here value is the value of option and text is text to be displayed on dorpdown.
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (i, item) {
$('#branch_name').append($('<option>', {
value: item.value,
text : item.text
}));
});
});
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
Use $.each like below:
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (key, value) {
$("#brnch_name").append($("<option></option>").val(segments[key].trim());
});
}
});
You need to iterate through each branch names from response and append the same as individual <option> tags. However you have already got several solutions for the same, while mine uses simple string replace.
/* this is only relevant script */
var response = 'Branch 1,Branch 2,Branch 3,Branch 4';
$('<option>' + response.replace(/\,/g, '</option><option>') + '</option>').appendTo('#branch_name');
/*in-case you wish to show a default selection */
$('#branch_name').prop('selectedIndex', 3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="branch_name"><option value="0">Select branch Name</option></select>

get value of selected item and change the list on second dropdown

i am trying to change the second dropdown list when an item is selected on 1st dropdown
$output_body = '<select>';
$accounts = $service->management_accounts->listManagementAccounts("~all");
foreach($accounts['items'] as $item) {
$output_body .= sprintf('<option value="%d">%s</option>', $item['id'], $item['name']);
}
$output_body .= '</select>';
so when i select an item from above dropdown list it should store value of selected item in variable and that variable will be used here which i believe update the dropdown list
$webproperties = $service->management_webproperties->listManagementWebproperties("var here");
foreach($webproperties['items'] as $item) {
$output_prop .= sprintf('<option value="">%s</option>', $item['name']);
}
$output_prop .= '</select>';
Here is a good example for cascading dropdowns in jQuery. (populating one based on the selection of another)
<script>
$(function () {
var productsSelect = $('#productId');
productsSelect.attr('disabled', true);
$('#categoryId').change(function () {
var categoryId = $(this).val();
$.getJSON('/GetProducts/' + categoryId, function (products) {
productsSelect.attr('disabled', false);
productsSelect.empty();
productsSelect.append(
$('<option/>')
.attr('value', '')
.text('-- Select Product --'));
$.each(products, function (index, product) {
productsSelect.append(
$('<option/>')
.attr('value', product.ProductId)
.text(product.ProductName)
);
});
});
});
});
</script>
It would be nice in my opinion to be able to use event bubbling on the parent element in conjunction with a html data element, submit the request to your php controller and assign the option data back to your view, but I'm not sure if you have the mvc framework to support this or not...
window.addEvent('domready', function() {
$('parent_option_list_container').addEvent('click:relay(a)', function(e, ele) {
if (ele.hasClass('some_option_in_the_list')) {
e.preventDefault();
var selected = ele.get('data-option-value');
var request = new Request({
method: 'POST',
url : '/form_controller/option_select_toggle_function/' + selected,
}).send();
}
}

Categories

Resources