Semantic UI dynamic dropdown reinitialize issue - javascript

I use semantic UI dropdown plugin. active the plugin on load by
$(function () {
$('select.dropdown').dropdown();
});
in my code there is two dropdown one's date is dependen on other. on change first dropdown I populate other's value.
$('.city').on('change', function () {
var id = $(this).val();
if (id != '') {
$.get('ajax/town/' + id).done(function (result) {
var div = '';
$.each(result, function (i, e) {
div += '<option value="' + e.id + '">' + e.town + '</option>';
});
$('.town').html(div);
$('select.dropdown.town').dropdown('refresh');
});
}
});
But the dropdown doesnot reinitialize, but show a list in a div. How to solve this issue.

The problem solved. by changing...
$('.town').html(div);
$('select.dropdown.town').dropdown('refresh');
to
$('.town select').html(div).dropdown();

Related

jQuery Custom AutoComplete

I am trying to make an autocomplete suggestion for countries listed in my database. I managed to get the list and I am trying to bind click event for entries for each country. Although I believe this is the way to do it, code is always using the last item's value and placing it to the input field.
Suggestions is my autocomplete container and the text field that I want to update is the box.
$('#box').on('input', function (){
var typedLocation = { 'location' : $(this).val() };
var key;
$.post( "/suggestions.php", typedLocation, function( data ) {
$('#Suggestions').html('').show();
for (key in data) {
$('#Suggestions').append('<div id="suggest' + key + '" >' + data[key] + '</div>');
$('#Suggestions').find('#suggest' + key).click(function (){
$('#Suggestions').hide();
$('#box').val(data[key]);
});
}
});
});
Instead of using the variable for setting the value of input field, I have used $(this).html() in the click function.
Adopting it to Joe's example (as it seems more elegant):
var $elem = $('<div>' + data[key] + '</div>');
$elem.click(function () {
$('#Suggestions').hide();
$('#box').val($(this).html());
});
$('#Suggestions').append($elem);

Double click on added select option not working

I have two selects that both have use a function to add elements to the other select.
Here's what I have:
$("#lecturers option").dblclick(function ()
{
var element = $("#lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
and vice versa:
http://jsfiddle.net/VJAJB/
It somehow only works once, and the newly added elements don't trigger the function.
Any idea on how to fix this?
The issue is how you bind the dblclick function to the elements. The current selector only returns the option elements you have in your select element at the time of binding. To alter this, you can use delegated events.
$('#lecturers').on('dblclick', 'option', function() {
//Do stuff here
});
This makes sure that any option element you add to the select element will trigger this event when it is double clicked.
Here is an updated fiddle: http://jsfiddle.net/VJAJB/4/
Please note that other users have given you solutions that will work. However, best practice is to limit the number of events bound to the document itself. Whenever possible, you should bind delegated event listeners to the nearest non changing element.
This happens because the handler doesn't get bound to the new elements. You can do it like this, which will bind it to a descendant (in this case body) and specify the selector it will be applied to:
$('body').on('dblclick', '#lecturers option', function ()
{
var element = $("#lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
$('body').on('dblclick', '#selected_lecturers option', function ()
{
var element = $("#selected_lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
If both have a parent/descendant element that is present at the time of binding, you can use that instead of 'body' to improve performance.
Fiddle: http://jsfiddle.net/VJAJB/2/
You need to use on method instead. In latest jQuery versions is:
$( document ).on( "dblclick", "#lecturers option", function ()
Updated jsFiddle

How do you run a function after an element has been loaded?

I have tried to run the List_Sandbox functions after the each loop above has been ran and have to no avail figured it out. The each loop is selecting a group of checkboxes which then triggers a change event that renders other checkboxes that need to be selected. The List_Sandbox functions are doing the selection but the are running before my script can load the other new checkboxes. How can I see this through? I have tried, .load, .on, and livequery and neither is working. Please help...
$.each(zone_array, function(index, zone){
$("ul.zones li input[id='"+zone+"']").attr("checked", "checked").trigger("change");
});
List_Sandbox.select_districts_versions(district_array);
List_Sandbox.select_stores_versions(store_array);
function data_for_districts(zoneid) {
$.getJSON('/CampaignMgmt/GetDistrictsByZone', {'clientid': clientid, 'zone': zoneid }, function(data){
$.each(data, function(index, value){
$("span.notice_district").remove();
var zone = value.toString().substring(0, 1);
var li_tag = '<li zone="'+zoneid+'" class="'+ value +'"style="display: list-item; "><label><input id="'+value+'" data-id="'+value+'" data-parent-id="'+zone+'" type="checkbox" name="zone_101" value="' + value + '"><span>'+ value +'</span></label></li>';
$("ul.districts").append(li_tag);
$('ul.districts li input[id="'+value+'"]').change(function(){
Districts.selection(value);
Districts.count_districts();
});
});
});
}
It's not very clear what your code that appends the checkboxes is doing but you could try the following:
var arr_length = zone_array.length;
$.each(zone_array, function(index, zone) {
$("ul.zones li input[id='" + zone + "']").attr("checked", "checked").trigger("change");
/* run the List_Sandbox functions after last item */
if (index == arr_length - 1) {
List_Sandbox.select_districts_versions(district_array);
List_Sandbox.select_stores_versions(store_array);
}
});
EDIT: SHould use prop() method instead of attr() if using jQuery >= 1.6

Set the value to ID of the element on click event by jquery

I want to set the menu to active when click on it. This is what I've tried :
<script language="javascript" type="text/javascript">
var select;
$(document).ready(function () {
$.getJSON(url, function (data) {
$.each(data, function (index, dataOption) {
var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
$('a#' + dataOption.ID).click(function () {
select = "selected";
$('.level1').attr("id",select);
});
});
});
});
</script>
What I tried to do is to set the id of 'level1' to selected, when I click on that link. But my coding is set all the link to selected, even I click only 1 link.
Could anyone give me the solution please.
Thanks so much.
That happens because you are calling .attr() on all .level1 element instead of only the one being clicked by its child so,
change
$('.level1').attr("id",select);
to
$(this).parent().attr('id', select);
You also need to remove the "selected" id from the other <li>'s by
$('.level1').removeAttr('id');
So the complete code looks like:
$('a#' + dataOption.ID).click(function () {
$('.level1').removeAttr('id');
$(this).parent().attr("id", 'selected');
});
One suggestion though, class is usually used in situation like this when you want to have a selected type of a list of menu, if you are using class you'd do something like
$('a#' + dataOption.ID).click(function () {
$('.level1').removeClass('selected');
$(this).parent().addClass('selected');
}
Looks more concise that way, but I'll leave it up to you :)

How do I apply a jquery Click event to dynamic list elements?

My current setup loads a dynamic list at which point I create a click event via jquery like so:
$('#listReports li').click(function () {
var selected = $(this).text();
alert("List Item: " + selected);
});
I have code that lets a user save a report which gets appended to the list. The new item in the list doesn't trigger the click event until I call the function again. The problem with this is for the older items the event is getting triggered twice.
Here is how I append my list items and call then function again:
$("#save").click(function (e) {
if ($("#reportParams li").size()> 0) {
var fileName = $('#reportFileName').val();
if (!fileName) {
alert("You must enter a file name!");
}
else {
$('#listReports').append('<li>'+fileName+'</li>');
$('#listReports li').click(function () {
var selected = $(this).text();
alert("List Item: " + selected);
});
}
}
});
Is there a way to define the click event only once and have it effect new items appended to the list?
Instead of .click(), use .live():
$('#listReports li').live('click', function ()
{
var selected = $(this).text();
alert("List Item: " + selected);
});
or .delegate():
$('#listReports').delegate('li', 'click', function ()
{
var selected = $(this).text();
alert("List Item: " + selected);
});

Categories