jQuery getting value of updated select input - javascript

I update the value of a select input like so:
$('.filter').change(function() {
$.post('/schedules', { sid: $(this).val() }, function(result) {
$.each(result, function(k, v) {
var least = 0;
if(v.sort_c > least) {
$('.filter2').append('<option value="' + v.id + '.' + 'test_value' + '">' + v.name + '</option>');
least = v.sort_c;
}
});
});
});
After this jQuery runs I need to then get the value of $('.filter2'). When I try to do $('.filter2').val() it returns nothing.
Why is this happening?

You probably want to find the value of the selected option inside your select named filter2. Try this:
$('.filter2 option:selected').val();

After this jQuery runs seems to imply that you're not taking into account the asynchronous(AJAX) request involved. The following should give you the correct value of .filter2:
$('.filter').change(function() {
$.post('/schedules', { sid: $(this).val() }, function(result) {
$.each(result, function(k, v) {
var least = 0;
if(v.sort_c > least) {
$('.filter2').append('<option value="' + v.id + '.' + 'test_value' + '">' + v.name + '</option>');
least = v.sort_c;
}
});
console.log( $('.filter2').val() ); //<========
});
});
However, since I don't see you setting any of the new options with a selected attribute, I wonder what value you expect to get that you would not get before the change.

Related

JS Error with JSON Response Nodes

I have a page that generates a dropdown of options based on a prior selection. Once the parent dropdown is selected, that triggers a AJAX call which returns a JSON response of the child options.
function fetchLines(line) {
// Define vars we will use in this function
var dropdown = '';
// AJAX call to lines/sublines
$.ajax({
url: baseURL + "index.php/Project/fetchLines",
type: 'POST',
cache: false,
dataType: "json",
data: {
lineType: line
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
dropdown += '<option></option>';
$(data.lines).each(function() {
dropdown += '<optgroup label="' + this.line + '">';
if (this.sublines.options) {
$(this.sublines.options).each(function() {
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
dropdown += '</optgroup>';
});
$('[name=line]').empty().append(dropdown).select2("enable", true).trigger('change');
}
});
}
The issue I am running into is that there are some times no sublines in the JSON response which is causing the function to error out and not show results at all.
TypeError: this.sublines is undefined
JSON Response:
[
{
"line":"Business",
"sublines":{
"options":[
{
"subLine":"Accounts"
}
]
}
},
{
"line":"Consumer",
"sublines":{
"options":[
{
"subLine":"Cause"
},
{
"subLine":"Financial Services"
}
]
}
},
{
"line":"Risk"
}
]
Is there a way I can prevent a missing node subLines from breaking the function?
Ok, don't take it wrong, but it looks like you have no idea what you're doing. Just trying to use variables like they would be magically there.
I think this is what you're trying to do:
var dropdown = '<option></option>';
// iterate over your lines
$.each(data, function(i, line) {
// check id there's sublines (may be needed to check if there's options too)
if (line.sublines) {
// start an opt group only if there's sublines
dropdown += '<optgroup label="' + line + '">';
// iterate over it's options
$.each(line.sublines.options, function(j, option) {
// add the option to the html
dropdown += '<option value="' + option + '">' + option + '</option>';
});
// close the opt group
dropdown += '</optgroup>';
}
});
// replace the select content and trigger a change
$('[name="line"]').html(dropdown).select2('enable', true).trigger('change');
Check if subLine exists previously:
if (this.sublines.options) {
$(this.sublines.options).each(function() {
if (this.subLine)
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
Clearly in your JSON response not all objects from the array have the property sublines. And this is the line which is make the code to fail.
if (this.sublines.options) {
I'd suggest improving it to the following by checking if it has the property or not:
if (this.sublines && this.sublines.options) {
Check for sublines first...
if (this.sublines) {
if (this.sublines.options) {
$(this.sublines.options).each(function() {
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
}
I think you want to achieve something like this:
Fiddle: https://jsfiddle.net/a3bx77vm/3/
var dropdown = '';
for(var i = 0; i < data.length; i ++)
{
dropdown += '<option></option>';
var eachdata = data[i];
dropdown += '<optgroup label="' + eachdata.line + '">';
if(eachdata.sublines)
{
if (eachdata.sublines.options) {
$(eachdata.sublines.options).each(function() {
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
}
dropdown += '</optgroup>';
}
$("#dropdown").append($(dropdown));
The parsing was wrong because the data you get is an array, and it doesn't have property called lines.

JSON multi-value

i need help parsing the following:
{
"data": [
{
"Function": "Administration",
"SubFunction": "Facilities,Maintnce,Bldg Svcs,Other,Secretary"
},
{
"Function": "Communications",
"SubFunction": "Internal Communications,Marketing Comm,Other"
},
{
"Function": "Customer_Services",
"SubFunction": "Customer Engineer,Dispatcher,NonQuota Acct Supp Mgr,Other,PreSales-Network,Process and Systems,Quota Acct Supp Mgr,Remote Support Services,Rework,Service Offer Development,Services Logistics,Services Planning,Technology Consultant"
}
]
}
My jQuery code is:
$select3.html('');
$select4.html('');
$.each(data.data, function(key, val){
$select3.append('<option id="' + val.Function + '">' + val.Function + '</option>');
$.each(this.SubFunction, function(){
$select4.append('<option id="' + val.SubFunction + '">' + val.SubFunction + '</option>');
})
})
What should happen: The first option box should be filled with the "Function" and the second with the "SubFunction" upon the "Function" selection.
What is happening: The first option box does load up the "Function" values correctly, but the second drop down has all of the "Subfunction" from all "Function" with multiple instances of them.
Please help.
Thank You.
You need a change handler for this. This should do the job:
$select3 = $('#select3');
$select4 = $('#select4');
$.each(data.data, function() {
addOption($select3, this.Function);
});
$.each(data.data[0].SubFunction.split(','), function() {
addOption($select4, this);
});
$select3.on('change', function() {
$select4.html('');
$.each(data.data, function() {
if ($select3.val() === this.Function) {
$.each(this.SubFunction.split(','), function() {
addOption($select4, this);
});
}
});
});
function addOption($target, value) {
$target.append('<option id="' + value + '">' + value + '</option>');
}
http://jsfiddle.net/m88u76eL/
DEMO
Here is how to do it. You could use a data attribute to store the options for each function in the the option elements of select3, then when each of these options is selected, the value in the data attribute is read and parsed and used to populate select4 on-the-fly.
$select3.empty();
$.each(data.data, function(key, val){
$select3.append(
$('<option/>',{id:val.Function,text:val.Function,'data-sub-function':val.SubFunction})
);
});
$(function() {
$select3.on('change',function() {
$select4.empty();
$.each($('option:selected', this).data('sub-function').split(','), function(i,val){
$select4.append(
$('<option/>', {id:val,text:val})
);
});
})
.change();
});
You are already looping in data Object why are you doing a extra $.each ?
$select3.html('');
$select4.html('');
$.each(data.data, function(key, val){
$select3.append('<option id="' + val.Function + '">' + val.Function + '</option>');
$select4.append('<option id="' + val.SubFunction + '">' + val.SubFunction + '</option>');
});
This just work just find? Not tested tho just a quick post to help out

search with an array associate with javascript?

I want to do a search by name and surname with an array javascript, and the results in a div. for example: I write Ali in input, an it shoul show me Alison and Alibaba.
this is my code, but it's giving errors; are there other ways to do it?:
<input type='text' id='filter' placeholder='search'>
<div id='output' style='margin-top:50px '></div>
my array
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#output');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
console.log( item[0].toLowerCase().indexOf(val));
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item[0] + ' ' + item[1] + '</li>');
}
});
$result.html( $fragment.children() );
});
http://jsfiddle.net/henrykend/ChpgZ/4/
The main problem with your code is that you're trying to reference fields in the object by ordinal position rather than name. There is nothing automagic in JavaScript which will read item.Name (or item["Name"]) from item[0].
There is also no need to build up a "false element" (in your case $fragment) and then append its children to the output area - you may as well do this in one go (remembering to .empty() it between calls).
Your corrected code:
var $result = $('#result');
$('#output').on('keyup', function () {
$result.empty();
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$result.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
});
And a live example: http://jsfiddle.net/ChpgZ/6/
You had couple of problems in your code.
Names of the elements we're wrongly placed (which you've fixed with the edit)
In the .each, you've used item[0] instead of item.Name (also surname)
See the following code
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#result');
$('#output').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {console.log( item.Name.toLowerCase().indexOf(val) );
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
$result.html( $fragment.children() );
});

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

Another jQuery autocomplete issue

So, i have read at least 20-30 auto complete problems here on so and i cannot find any solutions. For some odd reason i keep getting value = undefined. Here is my code.
//Cycles through each input and turns it into a person searcher.
$.each(settings.input, function() {
var input = $(this);
input.autocomplete({
delay: 70,
minLength: 2,
source: function(req, add) {
var val = input.val();
$.post(VUI.SITE_URL + "scripts/autocomplete/_AutoComplete.php", {q: val, display_count: settings.displayCount, action: "user"}, function(data) {
data = eval("(" + data + ")");
if (data.length > 0) {
var results = new Array(data.length);
$.each(data, function(key, value) {
results[key] = {desc: value, value: value.firstname + " " + value.lastname};
});
add(results);
} else {
add(["No results..."]);
}
});
},
select: function(event, ui) {
alert(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
}
}) // end auto complete.
.data("autocomplete")._renderItem = function($ul, item) {
var $li = $("<li></li>"),
$inner = $("<div class='st-display side-content clearfix'style='padding-top:6px'></div>"),
$a = $("<a></a>"),
$img = $("<div class='image fl'></div>").html(ST.Image.getImage({
uid: item.desc.uid,
type: ST.ST_IMAGE_TYPE_THUMBNAIL_SMALL
})),
$content = $("<div class='content fl'></div>").html(
item.desc.firstname + " " + item.desc.lastname + "<br/>" +
"<span class='color:#979797;font-weight:bold'>" + item.desc.city + ", " + item.desc.state + "</span>"
);
$inner.append($img).append($content);
$a.append($inner);
$li.append($a);
$ul.append($li);
return $ul;
} // end _renderItem */
I tried to make it so that its very straight forward. But it wont work! (its facebook like auto complete). The auto complete displays properly (item does not equal undefined at that point), but when i highlight it, item becomes undefined so item.value (line 6347 of jquery.ui.1.8.13) throws exception!
Anyone see problems?
Here is something interesting... When i do not use data("autocomplete")._renderItem (for custom completion) the selecting works! ... So why does overriding the custom rendering cause issues? I am even returning the UL.
The only thing in your code that's different from a working version I've got of something very similar is that I initialise $li with:
var $li = $( '<li></li>' ).data('item.autocomplete', item);
That attaches the data to the list item which I think the autocomplete plugin uses to get the value at selection time.
Hope it helps

Categories