Get select multiple values with JQuery - javascript

I have a problem with JQuery, I have a multiple select that i can populate in 2 ways, manually taking some value from another select with a add button, and dynamically, with parsing a json returned from a spring call.
I have no problem to take the value when I add it manually, but, when I populate dynamically the select, the JQuery code doesn't take any value although int the html code there're values in the select.
Here my code:
The empty html selects
<div id="enti_disp_box">
<label>Enti disponibili</label>
<select id="ente" multiple> </select>
<button class="btn" onclick="addEnteInBox();" type="button">Aggiungi</button>
</div>
<div id="enti_att_box">
<label>Enti attivi*</label>
<select id="entiAttivi" multiple></select>
<button class="btn" onclick="removeEnteInBox();" type="button">Rimuovi</button>
</div>
JQuery for populate the second select manually
function addEnteInBox(){
var selectedOptions = document.getElementById("ente");
for (var i = 0; i < selectedOptions.length; i++) {
var opt = selectedOptions[i];
if (opt.selected) {
document.getElementById("entiAttivi").appendChild(opt);
i--;
}
}
}
function removeEnteInBox(){
var x = document.getElementById("entiAttivi");
x.remove(x.selectedIndex);
}
JQuery for populate the second select dynamically
function getEntiByIdUtente(idutente) {
var action = "getEntiByidUtente";
var payload = {
"idUtente": idutente,
"action": action,
"token": token
};
$.ajax({
type: "POST",
url: '../service/rest/enti/management_utenti',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(payload),
resourceType: 'json',
success: function(obj, textstatus) {
obj = obj.trim();
var json = JSON.parse(obj);
//parse response
if (obj.stato == 'error') {
alert('Errore');
} else {
$('#entiAttivi').empty();
//fetch obj.data and populate table
$(json.data).each(function() {
$("#piva").val(this.piva);
$("#codiceipa").val(this.codiceipa);
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
});
}
return json;
},
error: function(obj, textstatus) {
alert('Errore di comunicazione col server!');
}
});
}
JQuery for taking the value of the second select
var entiList = $("#entiAttivi").val();

This line seems to be wrong, it's not working for me
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
would you try replacing by
$('#entiAttivi').append($('<option value="' + this.idente + '">' + this.regionesociale + '</option>');
The append, is trying to create an option with the json as parent, this is not working. please try my code.

Related

Data fields are undefined in ASP.Net Core MVC using JSON

So, I have an issue with my Javascript code. I am using cascading dropdowns, one is for the car brand and another one for the car model. According to logic, when I choose one of the brands from the dropdown (e.g. Toyota or Audi, etc.) the second dropdown should show the models of the selected brand. Generally, I use GetModelsJson method in the controller to join Brand and Model tables and return models as json.
public JsonResult GetModelsJson(int p)
{
var models = (from x in GetModels()
join y in GetBrands() on x.BrandId equals y.Id
where x.BrandId == p
select new
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
return new JsonResult(new { data = models });
}
In the view, I want to display the dropdowns using following code:
#Html.Label("Brands")
#Html.DropDownList("drpBrand",Model.BrandList,"--Select Brand--", new {#class = "form-control"})
#Html.Label("Models")
#Html.DropDownList("drpModel",Model.ModelList,"--Select Model--", new {#class = "form-control"})
The problem starts in the javascript code. Everything works fine until a for loop. For some reason, length of the data variable and other fields like text and value are undefined.
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function(){
$('#drpBrand').change(function(){
var id = $('#drpBrand').val();
$.ajax({
url: '/Admin/Vehicle/GetModelsJson',
data: {p : id},
type: "POST",
dataType: "Json",
success: function(data){
console.log(data);
$('#drpModel').empty();
for (let i = 0; i < 3; i++){
$('#drpModel').append("<option value ='" + data[i].value + "'>" + data[i].text + "</option>");
}
}
});
});
});
</script>
As a result, the second dropdown for models becomes empty.
Picture of the web site
As you can see from this picture, the second dropdown is empty, although according to console data has its fields like "A5", "A4", "A6".
As the picture you uploaded the object from the server has a "data" field which contains the array so edit your code like this:
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function(){
$('#drpBrand').change(function(){
var id = $('#drpBrand').val();
$.ajax({
url: '/Admin/Vehicle/GetModelsJson',
data: {p : id},
type: "POST",
dataType: "Json",
success: function(data){
console.log(data);
$('#drpModel').empty();
for (let i = 0; i < data.data.length; i++){
$('#drpModel').append("<option value ='" + data.data[i].value + "'>" + data.data[i].text + "</option>");
}
}
});
});
});
</script>

Updating rows that are added dynamically using ajax

I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.

Populate Dropdown List based on Autocomplete Value

I have three form fields for country(text input), city(text input) and street(dropdown):
country is autocomplete
city is auto-filled based on the result of country
street I want to generate dropdown list based on selected city
Here is my current JavaScript script:
$(".country").autocomplete("get_city.php",{ mustMatch:true })
.result(function (evt, data, formatted) {
$(".city").val(data[1]);
});
So far it's auto-filling the city(text input).
My problem now is to generate drop down list based on the filled city.
I Think you need somthing like this:
$(".country").change(function () {
var webMethod = "filewithdata.php";
var parameters = { id: $('.country').val() };
$.ajax({
type: "GET",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//console.log(response);
json_obj = $.parseJSON(response);
var output = '';
for (var i in json_obj) {
if (json_obj[i][4] == 1) {
output += '<option value="' + json_obj[i][0] + '">' + json_obj[i][0] + '</option>'
}
}
$('#dropdownElement').empty().append(output);
},
error: function (e) {
$(divToBeWorkedOn).html("Unavailable");
alert("Errror:" + e);
}
});
});

Text Area interfering with Ajax Code

I am just trying to clear the text area with an id of "discussion" it clears the textbox but it does not load the data from the server with the ajax statement. When I remove the line that clears that text area it loads all the data in fine but just adds to the current data.
Here is my code:
function LoadRoomMessages(id)
{
$.ajax(
{
type: "Get",
url: "#Url.Action("GetMessages", "Home")",
data: { roomId: id },
success: function (data)
{
// Here is the line that causes issues.
$('#discussion').val('');
json = data;
var obj = JSON.parse(json);
for (var i = 0; i < data.length; i++)
{
$('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
}
}
});
}
You may also try (as you asked to answer it)
$('#discussion').empty();

Set initial JQuery suggest value

I have a JQuery suggest box using a key and a value. The key is the saved value, for example a userId and the value is the shown value such as a username.
When having a blank field it works great. I type a few characters, select a name and the value is added as the value that is posted with the HTTP request. Now, how should I prefill a form's suggest with when it already has a value. When placing the saved userId as the value the suggest shows the userId but, obviously I want to show the username. I also tried to echo the username that was selected but than, if the username is not changed the posted value will be the username.
<script>
<!--
$(document).ready(function() {
$("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest",{
parse: function(data) {
var parsed = [];
data = data.data;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
value: data[i].key,
result: data[i].value
};
}
return parsed;
},
formatItem:function(item, index, total, query){
return item.value;
},
formatResult:function(item){
return item.id;
},
dataType: 'json'
});
});
-->
</script>
<input type="text" name="creatorUserId" id="creatorUserId" value="3" size="40" />
How could I solve this?
Try this
<script>
<!--
$(document).ready(function() {
$("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest",{
parse: function(data) {
var parsed = [];
data = data.data;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
key: data[i].key,
value: data[i].value
};
}
return parsed;
},
formatItem:function(item, index, total, query){
return item.value;
},
formatResult:function(item){
return item.id;
},
dataType: 'json'
});
});
-->
</script>
Deleting the current value of the text box on click (If and only if the text box has not yet been edited).
When the input looses focus, and if the input was un-edited, put the initial value back.

Categories