Below is the following code that works perfectly for dynamic loading of a select drop down. The code is called in the documents ready function to pre-load data into a page. The code works just fine. However, I got puzzled over the fact that it seems "undefined" in the DOM. ie.. .change event etc...when I attempt to select a value....
In the HTML, the is set simply:
<select id="optionsChaa" name="chaa_id" class="largewidth"></select>
The jquery code is as follows. It works. Feel free to use it in your codes
var optionsValues = '<select id="optionsChaa" name="chaa_id" class="largewidth">';
optionsValues += '<option value=""></option>';
$.each(result, function() {
optionsValues += '<option value="' + this.chaa_id.val + '">' + this.chaa_name + '</option>';
});
optionsValues += '</select>';
var options = $('#optionsChaa');
options.replaceWith(optionsValues);
$('#optionsChaa').change(function() {
// Alert returns undefined...
alert($(this).val() );
});
So why is it "undefined" after the DOM?
I think there's something wrong with the this.chaa_id.val part. In each, "this" refers to the "current" element (i.e. a member of the results array).
Could you show what's in your result variable?
I tried your code setting result as:
var result = [
{ 'chaa_id' : { 'val' : 1 }, 'chaa_name' : 'name1'},
{ 'chaa_id' : { 'val' : 2 }, 'chaa_name' : 'name2'}
]
And the alert() seems to work.
Related
This is in reference to dynamically change options in a list by another list. Unfortunately, it all works except if the project name has a " or a #. Eg. Project name: '10" Centerline #3 Pipe'
I am a newbie to this and I have been cut/paste (learning) as I go along. If someone can help, it will be great. I am seen some things about escaping and encoding URI stuff but not sure where to put it in. The other problem is just understanding what happens past the onchange event.
I can get the list of project names from a previous list and it shows up in my HTML page. However, when I select the choices that have a ( " ) or a ( # ), the next populated list breaks.
Thanks in advance. I really, really appreciate the time if someone puts in a response.
Here is the javascript portion:
project_name_select.onchange = function(){
project_name = project_name_select.value;
fetch('/sr/new/project/' + project_name).then(function(response){
response.json().then(function(data) {
var areaHTML = '<option value="See List">Select Area</option>';
for (var state of data.project_area) {
areaHTML += '<option value="' + state.project_area + '">' + state.project_area + '</option>'
}
project_area_select.innerHTML = areaHTML;
});
});
}
Here is the flask portion:
#surveys.route("/sr/new/project/<get_project_name>")
def project(get_project_name):
project_dict, dict_type = choice_project_dict(get_project_name)
project_areaArray = []
for proj in project_dict:
ownerObj = {}
ownerObj['id'] = proj['company_name']
ownerObj['owner_company'] = proj['company_name']
ownerArray.append(ownerObj)
return jsonify({'project_area': project_areaArray})
I have an input field with datalist options, which has it's suggestions updated via AJAX after chhange of other field.
I tried to add new options to the datalist as other questions proposed:
$("#add_option").change(function(){
var _opt_opt_name_val = $(this).val();
var opt_name_url=_url+"?opt_name="+escape(_opt_opt_name_val);
var _values_datalist_id = $("#opt_values").attr("list")
var _value_html = "";
$.get(opt_name_url,function(data){
$(_values_datalist_id).empty();
$.each(data, function(key, v){
_value_html += '<option value="' + v.value + '"></option>';
});
$(_values_datalist_id).append(_value_html);
console.log("added code: "+$(_values_datalist_id).html());
});
});
As it didn't work, I'd like to check (read) what was appended via this javascript. tried $("#element").text() and .html(). Both return undefined.
How could I retrieve the datalist contents in this (or any) case? For debugging, I mean.
Again, after 3 days fiddling with this problem, I had an insight for doing it:
I mixed JQuery for the Ajax part and Vanilla Javascript for adding the new options. Not much elegant, but worked so far:
$("#add_option").change(function(){
var _opt_opt_name_val = $(this).val();
var opt_name_url=_url+"?opt_name="+escape(_opt_opt_name_val);
var _values_datalist_id = $("#opt_values").attr("list")
$.get(opt_name_url,function(data){
var _datalist=document.getElementById(_values_datalist_id);
_datalist.innerHTML = "";
$.each(data, function(key, v){
_datalist.innerHTML += '<option value="' + v.value + '"></option>';
});
});
});
and this solved my present problem today. Maybe this can help anyone with a similar problem? (I still don't know how to get the datalist options via jQuery though).
Hi guys i been trying to figure out for a long time but i suck at this, i found this code on google and i added it adn changed what i need but still doesnt work i really need this for my site: http://www.balkan-party.cf/
I found code here: http://www.samkitson.co.uk/using-json-to-access-last-fm-recently-played-tracks/
My last.fm username i need in js: alicajdin AND
Api key: 24f6b03517ad9984de417be5d10e150b
This is what i did:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=alicajdin&api_key=24f6b03517ad9984de417be5d10e150b&limit=2&format=json&callback=?", function(data) {
var html = ''; // we declare the variable that we'll be using to store our information
var counter = 1; // we declare a counter variable to use with the if statement in order to limit the result to 1
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
} // close the if statement
counter++ // add 1 to the counter variable each time the each loop runs
}); // close each loop
$('.listening-to h5').append(html); // print the information to the document - here I look for the h5 tag inside the div with a class of 'listening-to' and use the jQuery append method to insert the information we've stored in the html variable inside the h5 tag.
}); // close JSON call
});
I created that file and i tried to add on head section, footer section but it wont show recent tracks.
And yea i have scroblr installed on google crome
below </script> add the following code:
<div class="listening-to"></div>
then remove "h5" on
"$('.listening-to h5').append(html);"
so your code like this:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOUR_USERNAME&api_key=YOUR_API_KEY&limit=2&format=json&callback=?", function(data) {
var html = '';
var counter = 1;
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
}
counter++
});
$('.listening-to').append(html);
});
});
</script>
<div class="listening-to"></div>
Hope you can help. Sorry, my English is very Bad (Google Translate)
I am having some trouble using the chosen.js plugin on my dropdown.There are a few related questions on here that I have worked through but still no luck on my code.
I have 4 dynamically created and populated select elements.
var dropdownArray = [];
function initDropdown() {
var id = "list";
var classy= "chzn-select";
var html = "";
for ( var idcount = 0; idcount < 4; idcount++) {
var dropdownHTML = "<select class=\""+classy+"\" id=\"" + id
+ "\" onchange= selectfunc(this) >" +
"<option selected=\"selected\">Make Selection... </option>" +
"</select>";
dropdownArray.push(id);
html += dropdownHTML;
id += "0";
}
$("#dropdowns").html(html);
$(".chzn-select").chosen();
};
I have tried to use this line to apply Chosen.js to the elements by their class name chzn-select:
$(".chzn-select").chosen();
However I am getting the error :
Uncaught TypeError: Object #<Object> has no method 'chosen' .
Sorry about the messy code, I am new to this.
any help would be much appreciated.
From your comments, you were trying to create a single SELECT with 4 options using chosen.js. Check out JSFiddle 1 for result.
From your question, you were trying to create 4 SELECT dynamically using chosen.js. Check out JSFiddle 2. The reason for error is you missed to point the right id (dropHolder).
try this $("#list").trigger("chosen:updated");
got it from here
I have a survey-type form that's being populated from a web database on the client. I can populate the questions fine, but then I try to go through and trigger the click event where there is an existing answer (edit scenario), I'm finding that the new elements are not yet in the DOM so this doesn't work. Here's the code:
$(function() {
var db = openDatabase(...);
db.transaction(function(tx) {
tx.executeSql("select ....", [surveyId], function(tx, results) {
var items = "", answers = [];
for (var i = 0; i < results.rows.length; i++) {
var id = results.rows.item(i).id;
items += "<div><input type='radio' name='q-" + id + "' id='q-" + id + "-1' /><label for='q-"+id+"-1'>Yes</label><input type='radio' name='q-" + id + "' id='q-" + id + "-2' /><label for='q-"+id+"-2'>No</label></div>";
if (result.rows.item(i).answer) {
answers.push('#q-'+id+'-'+results.rows.item(i).answer);
}
}
$('#questions-div').append(items);
$.each(answers, function(i, e) { $(e).click(); });
});
});
});
Any tips how I can make this work, or better generally?
I think here:
answers.push('#q-'+id+'-'+result);
You meant to push this:
answers.push('#q-'+id+'-'+result.rows.item[i].answer);
Otherwise you're getting '#q-XX-[object Object]' as a selector, where I think you're after the 1 or 2 version of '#q-XX-1'.
I suspect this is actually a race condition. My bet is that if you execute your each statement after a tiny delay, things will work as expected. Is so, the reason for this is that you can't be 100% sure when the browser will actually get around to updating the DOM when you programmaticallly insert new elements. I'm not sure what the best solution would be: if you were attaching events, I'd say you should do it at the same time you are building the elements; but if you are triggering the clicks, I'm leaning toward just continually testing for the existance of the elements and then triggering the clicks as soon as you know they are there.
So I came up with a solution:
I replaced the line items += "<div> ...." with
var item = "<div><input type='radio' name='q-" + id + "' id='q-" + id + "-1' ";
if (results.rows.item(i).answer == 1) item += "checked ";
item += "/><label for='q-"+id+"-1'>Yes</label><input type='radio' name='q-" + id + "' id='q-" + id + "-2' ";
if (results.rows.item(i).answer == 2) item += "checked ";
item += "/><label for='q-"+id+"-2'>No</label></div>";
items += item;
... which means I no longer need the answers array or to trigger click events on the radio buttons.
I was hoping for something a bit neater, but this seems to work OK. Thanks #Nick Craver & #Andrew for helping me arrive at it!