Dropdown list filled with undefined - javascript

I have a stored procedure which gets data from the database and I populate a dropdown list with that data. The problems is, I have a lot of undefined values in the dropdown. The correct data comes back and is successfully inserted in the dropdown but somehow I have a lot of undefined rows inserted in the dropdown as well.
var url = window.rootUrl + 'DUP/GetAllStreets';
$.getJSON(url, function (streets) {
console.log("streets", streets)
$("#streetNameID").append('<option></option>');
$.each(streets, function (index, value) {
$("#streetNameID").append('<option value="' + value.Ime_1251 + '">' + value.Ime_1251 + '</option>');
});
});
This is my function. I print the street out in the console, no undefined rows there. I am not sure what's causing this. Basically half of the rows are undefined

Related

How to control the 10 records previewed in a lookup control?

I am working with activities and the fields, to, from, etc.
We have created custom views dynamically in order to make the selection easier. That is fine
My problem is... when you push the icon to search contacts... Is it possible add and order a custom list for the previewed 10 records?
To avoid the user clicking on the "Look up More records", select the custom view and add the "TO" record?
Custom views always gives the power for users to switch & select the records. If you cannot solve it by user training, then implement some form save (or pre-update plugin) validations to iterate through the party list & alert them when things are not in place.
Otherwise - I used to do this addPreSearch and addCustomFilter technique all the time. Read more
function FilterPartyList() {
var Regarding = Xrm.Page.getAttribute("regardingobjectid").getValue();
//checking if regarding fields is empty before we apply the filter
if (Regarding != null) {
Xrm.Page.getControl("requiredattendees").addPreSearch(Filter);
}
}
function Filter() {
var RegardingValue = Xrm.Page.getAttribute("regardingobjectid").getValue();
//if Regarding has a value, proceed
if (RegardingValue != null) {
//used to retrieve Name of the Account held in the Regarding field
var RegardingTextValue = RegardingValue[0].name;
//GUID used in filter
var RegardingID = RegardingValue[0].id;
var plist_filter = "<filter type='and'>" + "<condition attribute='parentcustomerid' operator='eq' name='" + RegardingTextValue + "' value='" + RegardingID + "' />" + "</filter>";
Xrm.Page.getControl("optionalattendees").addCustomFilter(plist_filter, "contact");
}
}

HTML Javascript: pass checked box value to .js function correctly but webpage doesn't display data

I want to pass a checked value (upon hitting the submit button) to the .js function. The .js function should then take that checked value and query data from a sqlite db and AWS to populate the current webpage.
Here is what I think is happening in the posted code below. After checking a single box and hitting submit, the checked value is being passed to function getQuestionData(). Within getQuestionData(), an endpoint is created using the passed value then function appendInnerHTML is called to populate the page with queried data.
The error I get is
unreachable code after return statement[Learn More]
applied to the 4th line from the bottom ---- q.append('img').
I also noticed that whichever box is checked, my local URL changes. For example, if the box with Coordinate Geometry is checked, the url changes to
http://127.0.0.1:5000/?topic=Coordinate+Geometry
I had some help setting this up so I'm not 100% clear on the fundamentals, if that wasn't already obvious..
CODE
HTML
<form id="checkboxes">
<input type="submit" id="submitTopic" onsubmit="getQuestionData(this.value)">
</form>
.js
function getQuestionData() {
sampleValue = $('input[id=submitTopic]:checked').val()
//document.getElementById("submitTopic").value;
document.getElementById("question").innerHTML = ""
document.getElementById("solve").innerHTML = ""
var endPointQuestionData = '/api/v1/questions/' + sampleValue
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHMTL(response)
});
};
//populates webpage with data from sqlite db
function appendInnerHMTL(response) {
d3.select("#solve")
.append('h2')
.text("Solve.")
for (var i = 0; i < response.length; i++){
q = d3.select("#question")
d = q.append('div')
.append('strong')
.text(response[i]['id'])
d.append('div')
button = d.append('input')
.attr('class','button')
.attr('type','button')
.attr('value','Show Answer')
.attr('onclick','showAnswer('+ i + ')')
shownAnswer = d.append('div')
.attr('class','shownAnswer')
.text(response[i]['ans'])
document.getElementsByClassName('shownAnswer')[i].style.display='none';
//appends image from Amazon AWS to each id
q.append('img')
.attr('src', 'https://s3-us-west-1.amazonaws.com/actmath/' + response[i]['date'] + '/' + response[i]['id'] + '.JPG')
//retrieve .jpg file if .JPG file not found
.attr('onerror', 'this.oneerror=null;this.src=\"https://s3-us-west-1.amazonaws.com/actmath/' + response[i]['date'] + '/' + response[i]['id'] + '.jpg\";')
}
};

How can I erase a section of my table to display a message without touching the rest?

I have basically created a table that is made of two rows, the first row checks if the user input is correct or not, and the second row is displaying a button.
I have used the following code inside my script function inside the first row of my table to display the output response:
function checkUserInput() {
var userInput = document.getElementById("textInput").value;
var stringToCheckAgainst = random_images_array[num].split('.');
//this splits the item at the array index into an array, like so.
If the item is "apple.gif", the array reads ["apple", "gif"]
if (userInput == stringToCheckAgainst[0]) {
//user has inputted the correct string
//window.alert("user gave correct response!");
document.write("<p>" + txt.fontsize(5) + "</p>"); document.close();
} else {
//user has inputted an incorrect string
//window.alert("user gave incorrect response!");
document.write("<p>" + txt1.fontsize(5) + "</p>"); document.close();
}
}
</script>
However this code will delete the entire page (document). Can anyone advise me how to write the message only the top section of my page (or table) and leave the second row of my table unchanged?

Can't get JSON to render correctly in dropdown

I'm trying to take JSON from a PHP file and use it to populate a dropdown box.
I'm getting the JSON just fine from the PHP file. It looks like this:
[{"state":"AL"},{"state":"AK"},{"state":"AZ"},{"state":"AR"}]
I can see in the response in developer tools that it's coming over fine. However, when I look at the JSON, line 1 is empty and everything is on line 2. Not sure if that's a problem or not.
On the HTML side, here's what I've got:
<select id="myselect"></select>
and
$.getJSON('state_get.php', function(data) {
$.each(data, function(key, val) {
$('#myselect').append("<option>"+key.text+"</option>");
})
});
What I get in my dropdowns are a bunch of options with "undefined". There appear to be one for each JSON value, so something's party right, but not all the way.
Any help would be appreciated.
The first argument to each callback is the index, second is the value also the key to the property is State not text
$.getJSON('state_get.php', function (data) {
$.each(data, function (key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
})
});
First argument of $.each when looping an array is index, the second is the element of the array
Try
$('#myselect').append("<option>"+val.state+"</option>");
Each of the objects in your array would be an element
reference jQuery.each() API Docs
You object has property state, not text
$.each(data, function(key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
});
Try this
$('#myselect').append("<option>"+val.state+"</option>");
Lets have dropdown like below
<select id="myselect" name="stateList" class="state-list ></select>
You can append your value like this
var stateSelector = $('select.state-list');
var option = $("<option value=''></option>");
$.each(data, function(key, val) {
option = $("<option value='" + val.state + "'>" + val.state + "</option>");
stateSelector.append(option);
});
$('.state-list').selectpicker('refresh'); // you can refresh your dropdown if required

cascading dropdown list on mvc4 not updating nor loading javascript file

I'm currently trying to create a new set of cascading dropdown lists by following this tutorial :
http://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx
problem is it doesnt work and I'm basically illiterate on javascript (currently I dont have the time to sit and learn it), somehow the dropdown lists are not working, only the first one shows the first hierarchy info.
This is what I've done:
First the controller:
Here's the index method:
public ActionResult Index()
{
var list = repo.GetParentEstablishments();
ViewBag.Parent = (new SelectList(list.ToArray(),"EstablishmentId","Name"));
return View();
}
Here's the method that's supposed to return the list of children for the selected father:
[HttpPost]
public ActionResult Children(int parentId)
{
var parents = repo.GetChildrenEstablishments(parentId);
return Json(new SelectList(parents, "EstablishmentId", "Name"));
}
Here's the view for the index method:
#using (Html.BeginForm("Index", "Ticket", FormMethod.Post, new { id = "ParentChildrenFormID", data_childrenListAction = #Url.Action("ChildrenList") }))
{
<fieldset>
<legend> Parent/Children</legend>
#Html.DropDownList("Parents", ViewBag.Parent as SelectList, "Select a Parent", new {id="ParentsID"})
<div id="ChildrenDivId">
<label for="Children">Children </label>
<select id="ChildrenID" name="Children"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script src ="#Url.Content("~/Scripts/parentChildren.js")"></script>
And finally here's the script file:
$(function () {
$('#ChildrenDivId').hide();
$('#SubmitID').hide();
$('#ParentsID').change(function () {
var URL = $('#ParentChildrenFormID').data('childrenListAction');
$.getJSON(URL + '/' + $('#ParentsID').val(), function (data) {
var items = '<option>Select a Children</option>';
$.each(data, function (i, child) {
items += "<option value='" + child.value+ "'>" + child.Name + "</option>";
// state.Value cannot contain ' character. We are OK because state.Value = cnt++;
});
$('#ChildrenID').html(items);
$('#StatesDivID').show();
});
});
$('#ChildrenID').change(function () {
$('#SubmitID').show();
});
});
For what I've managed to understand from the javascript function, the div that has the label and dropdown for the children should appear hidden once the page is loaded and appear once the user selects a parent from the first list, currently this is not happening and instead everything shows up once the page is loaded. Also once I select a parent nothing happens on the second list, I can infer from this that the javascrip file is not being executed on the users browser, why isn't it being executed? what am I doing wrong?
Thank in advance, any help will be appreciated.
You have an error on the following line
items += "<option value='" + child.value + "'>" + child.Name + "</option>";
Which should be:
items += "<option value='" + child.Value + "'>" + child.Text + "</option>";
Since your controller action is returning a SelectList, this class is an IEnumerable<SelectListItem> where SelectListItem has 2 properties called Value and Text.
There's also another issue with your code. You have used the folllowing to construct the url to your controller action:
URL + '/' + $('#ParentsID').val()
which will result in an url of the form:
/SomeController/Children/123
But the action argument of your Children action is called parentId. If you are using the default route setup, only an {id} parameter will be sent as part og of the uri path (that's the default route pattern: {controller}/{action}/{id} and not {controller}/{action}/{parentid}). So you should either change your route setup or pass the parentId parameter like this:
$.getJSON(URL, { parentId: $('#ParentsID').val() }, function (data) {
...
});
Yet another issue with your code is that your Children conrtoller action is decorated with the [HttpPost] attribute but the $.getJSON method sends a GET request. So it won't work. You could use the $.post method instead:
$.post(URL, { parentId: $('#ParentsID').val() }, function (data) {
...
});
Another issue is that you are showing the StatesDivID but your actual div that was hidden is ChildrenDivId. Make sure you are showing the proper element:
$('#ChildrenDivId').show();
Also make sure you have the jQuery script referenced before your parentChildren.js script. Right now you have included your script inside the view but cannot see jQuery being included. Maybe you have it in your _Layout.
I would recommend you using a javascript debugging tool such as FireBug or Chrome developer toolbar to analyze your javascript code.

Categories

Resources