Select List Generated using JSON and jQuery appends empty options - javascript

I have a field that represents a zip code of a user. When the user leaves that text box, an AJAX request is sent to the server to receive cities that may be associated with that zip code.
I am trying to use the JSON received from that request to populate a select list to replace the text box that is currently assumed for city (if one city is returned, I just change the value of the text box).
For example, a user puts in 20910 as their zip code and it returns Silver Spring. I replace the textbox for city with Silver Spring. Another user puts in 84107 as their zip code and it replaces the textbox with a select list of Murray, Salt Lake City.
It receives the JSON just fine, but I am not sure if I am doing something wrong in my JavaScript. When the select is rendered, it gives blank fields after each value.
Here is my jQuery:
$('#AddressData_ZipCode').blur(function() {
var zip = $('#AddressData_ZipCode').val();
var pattern = /^\d{5}([\-]\d{4})?$/;
if (zipCode.length > 0 && pattern.test(zip)) {
$.getJSON("/GeneralInfo/GetCitiesInZip", { zipCode: zip }, function(data) {
if (data.length > 1) {
var citiesComboBuilder = "<select id='AddressData_City'>";
for (var i = 0; i < data.length; i++) {
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "<option/>";
}
citiesComboBuilder += "</select>";
$('#AddressData_City').replaceWith(citiesComboBuilder);
}
else
$('#AddressData_City').val(data);
});
}
});
This is the returned JSON:
["Murray","Salt Lake City"]
And this is the HTML that I receive after the function runs:
<select id="AddressData_City">
<option value="Murray">Murray</option>
<option/>
<option value="Salt Lake City">Salt Lake City</option>
<option/>
</select>
Any help would be great. Any suggestions to improve this code would be great also. Thanks.

Here is your problem:
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "<option/>";
Here is your solution:
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "</option>";

The option tag is closed wrong in your JavaScript, you have <option/>. It looks like the browser is trying to correct it and failing.

Related

access dropdown value generating on runtime

I am using C# asp.net. On button click I am generating a dropdown by using Javascript.
<scripttype="text/javascript">
var counter = 0;
function AddFileUpload() {
//debugger;
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '"Type="file"/>' +
'<select id="Droplist' + counter + '" name="droplst"/>' +
'<option value="SCR">Student Count request</option>' +
'<option value="DRO">Documents recieved from others</option>' +
'<option value="TE">total estimates</option>' +
'<option value="PRE">Presentation</option>' +
'<option value="PRI">Pricing</option>' +
'<option value="Quest">Questions to student</option>' +
'<option value="RelvExp">RelevantExperience-Case Studies</option>' +
'<option value="ResReq">Resource requests</option>' +
'<option value="SSP">Student submitted paper</option>' +
'<option value="WIP">WIP</option>' ;
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
</script>
I am accessing the dropdown values in page behind like this
string val = Request.Form["droplst"];
It is working fine,but what I am receiving is option value. Like "SCR" when "Student Count request" is selected. is there any way to access the selected value like "Student Count request" instead of getting the option value?
Please let me know if the question is vague and further clarification is required.
Are the values of the options necessary? The easiest change to make would be to remove the values. E.g:
<option>Student Count request</option>
If you do require the values, then it's a bit more tricky: you have added the dynamic control to the page using JavaScript, so the code behind won't be able to find it easily. You could add an ASP HiddenField control to the page, then when a dropdown is selected, populate that hiddenfield with the text value using JQuery/JavaScript. Then in the code behind you can access the value of the hidden field (which will be the dropdown selected text).
Do you understand? You can read further here which is a duplicate of this question and has already been answered: How to access dropdown text (not value) using Request.Form()?

how to implement search inside json data with javascript ajax jquery

I have one search box ,in that search json data should append.
here is my html code
<input type="search" id="merchantName" name="merchant" placeholder="enter merchant name"></input>
I have json data which contains merchant name. I want to append this merchant name on this search box in list form.how can I do..?this is my js function but here data is not appended in search box.
$(responseObj.merchants).each(function() {
var output = "<ul><li>" + this.merchantName + " " +"</li></ul>";
$('#list').append(output);
});
Try this, if responseObj.merchants is an array:
for (var i = 0; i < responseObj.merchants.length; i++) {
var output = "<li>" + responseObj.merchants[i].merchantName + " " +"</li>";
$('#list').append(output);
}
This should work or the other approach would be use for loop
$.each( responseObj.merchants function(index, value){
var output = "<ul><li>" + value + " " +"</li></ul>";
$('#list').append(output);
})
Explanation:
For each merchant value we iterate over its value and append it to the output list.
But always, API documentation read is a must.
The page contains examples and explanation to what you need.
http://api.jquery.com/jquery.getjson/

Trying to connect a dynamically created select element (tag) with options to a dynamically created table row

The first block of code is a working example of what I want the variable select to do. the var Select is there to be a td in the variable tr. the variable tr is used 2 times in this code. once to to append the tr when the table has html and another time when it doesn't have any html. the reason is because if doesn't have html it should append the header and the row with the select element and the rest of the data that's supposed to be on the row and if does have html it should only append the row to prevent repetition of the header. so I would like a nice clean variable named tr that will be append every time the users invokes it. jsfidle if you click on the drop down you could select the item and the new row will appear.
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var select = " <select class = 'select'><option value='volvo>Volvo</option> <option value='saab'>Saab</option> <option value='mercedes'>Mercedes</option> <option value='audi'>Audi</option> </select>"
var tr = "<tr><td>"+ suggestion.value + "</td><td>" +select +"</td></tr>"
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
The thing is I want the select element to be made up dynamically so i tried something and I cant figure out why it wont work. It's not recieving the variable. Am i implementing the varable wrong with the $.each?
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var selectValues = { "3": "2", "2": "1" , "1": "..."};
var select = $.each(selectValues, function(key, value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
var tr = "<tr><td>"+ suggestion.value + "</td><td><select class ='select'>" + select + "</select></td></tr>";
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
},
maxHeight:100,
width:600
});
thanks for your help
Why use object if you use only value?
if you realy don't need key juste create an array :
var selectValues = ["2", "1", "..."];
var value;
var select = selectValues.forEach(function(value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
// or if you want more compatibility
for (var i = 0, len = selectValue.length; i < len; i++) {
value = selectValue[i];
$('.select').append($('<option>', {value: value}).text(value));
});
Edit:
i make some mistake sorry.
first forEach will return nothing so it's can't work.
I test with your fidle. try this (replace by old for loop if you don't want to use map).
var select = selectValues.map(function(value){
return "<option value=" + value + ">" + value + "</option>";
// <option value='volvo>Volvo</option>
}).join('');
first you do not have to append from $('.select') because this dom not exist at this moment
and you can't concate an array in a string like this.

javascript, selection option using for loop that return the selected value

I'm pretty new to javascript so please bear with me. I'm trying to create a drop down list of age choice from 1-100, with option 20 show as default. I also need to get the return value of the choice user selected so i can use to calculate the years. Here is the code i'm playing around with so far.
function createAgeList()
{
var myAgeOptions;
for (cntr=1; cntr<100; cntr++)
{
myAgeOptions = myAgeOptions + "<option value=" + cntr + ">" + cntr + "</option>";
}
var myAgeSelect = document.getElementById('agelist');
myAgeSelect.innerHTML = myAgeOptions;
}
HTML code:
<form name="yearsleptform" id="yearsleptform" method="post">
<select size="1" id="agelist" name="agelist">
</select>
</form>
document.yearsleptform.agelist.value
This is going to return you the value they have selected.
To set the default option:
function createAgeList()
{
var myAgeOptions;
for (cntr=1; cntr<100; cntr++)
{
myAgeOptions = myAgeOptions + "<option value=" + cntr + " "+(cntr===20?"selected=selected":"")+ ">" + cntr + "</option>";
}
var myAgeSelect = document.getElementById('agelist');
Live Demo
myAgeSelect.innerHTML = myAgeOptions;
}
to get the selected value:
document.yearsleptform.agelist.value
Live Demo

Javascript selected item value not pulling correctly

I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};

Categories

Resources