Bootstrap Select with callback function - javascript

I have 2 Bootstrap Select dropdowns, one is a list of countries, and another is a list of states. The country list is static and is populated on page load. The list of states is only populated via the Bootstrap Change event and loads states based upon the country.
I need to be able to populate both these values at the same time. So the problem is I'm trying to set the state value when its undefined ,or hasn't loaded its options yet. I've tried doing a callback function within the ajax call, but that doesn't appear to work. I think another problem is that there is the initial change binding that is goofing it up.
I've written a fiddle for my foundation on where I'm experiencing the problem.
https://jsfiddle.net/jeffbeagley/DTcHh/37843/
The user is presented with a blank form that allows them to select the values, but the user can also load a saved form from the database ( hence the function labled as "select_data" ).
$(document).ready(function() {
$( "#country" ).on( 'changed.bs.select', function(e) {
change_country($( this ).val());
});
$( "#load" ).click(function() {
select_data();
});
});
This function is called anytime the user selects a country, the actual ajax call goes out to the database and returns all the appropriate states. I tried passing the state into this function and selecting it that way, but setting the country first would still fire the country change event and override it.
function change_country(country_id) {
$.ajax({
type: 'GET',
cache: false,
url: '/echo/jsonp/',
success: function(response) {
$( "#state" ).empty();
if(country_id == 1) {
$( "#state" ).append( "<option value=1>Oklahoma</option" );
$( "#state" ).append( "<option value=2>Missouri</option" );
} else {
$( "#state" ).append( "<option value=1>Ontario</option" );
$( "#state" ).append( "<option value=2>Quebec</option" );
}
$( "#state" ).selectpicker( "refresh" );
}
});
}
This is the function that grabs the saved form from the database and populates the values. With the way that its set, the expected outcome would be to select the country Canada, and the state Quebec
function select_data() {
var country_id = 2
var state_id = 2
$( "#country" ).selectpicker('val', country_id);
$( "#state" ).selectpicker('val', state_id);
}
Thanks for any help!

Might've figured it out.. sometimes you just need to strip out your code and simplify it to find an answer..
I replaced the code to populate the states outside of the event being called from the country being changed. Then I declared a callback function within this new function on success. I then moved the logic to select the country into the populate_state function ( this may not be appropriate )
You can see the updated fiddle here,
https://jsfiddle.net/jeffbeagley/DTcHh/37849/
So now the function select_data is as follows
function select_data() {
var country_id = 2
var state_id = 2
populate_states(country_id, function() {
$( "#state" ).selectpicker('val', state_id);
});
}
Edit ----
So with this, I ran into a call stack issue as it was still applying the original change event. So when the function select_data() is called, I unbind any events attached to the country selector, and rebind within the callback.
function select_data() {
var country_id = 2
var state_id = 2
$( "#country" ).off( 'changed.bs.select');
$( "#country" ).selectpicker('val', country_id);
populate_states(country_id, function() {
$( "#state" ).selectpicker('val', state_id);
$( "#country" ).on( 'changed.bs.select', function(e) {
change_country(e,$( this ).val());
});
});
}

Related

Passing value to anonymous function in jQuery

I just updated the code and below is the full version of the code
If data returns 0 I want to get the text value of the selected option and append it to a div. Now data returns 0 and the div with class iconSuccess shows up but the value of $a cannot be gotten. I try to alert($a) or even alert(1) in the if condition statement but nothing happens. I need to get the value of $a in the if condition statement. How can I pass the value to the function that return data?
below is the full version of the code
$('#categoryList').change(function () {
$a = $("#categoryList option:selected").text();
$( ".iconSuccess" ).hide();
$("#categoryList5,#categoryList4,#categoryList3,#categoryList2" ).hide();
$.post( "/trobay/categories/default/lists?parent_id="+$(this).val(), function(data) {
if(data !=='0'){
$( "select#categoryList1" ).show();
$( "select#categoryList1" ).html( data );
}else{
$("#categoryList5,#categoryList4,#categoryList3,#categoryList2,#categoryList1" ).hide();
$( ".iconSuccess" ).show();
$( ".mydiv" ).append($a);
alert(1);
alert($a);
}
//alert($a);
});
});
The below image is a screenshot of the message i got back from the server and the green icon only shows up when data return "0"
I hope this put more light on the question and any help will be apppreciated

Firefox won't update value on second click

So I've taken over a project that is almost ready to launch, a site where you can lease cars. I've uploaded the main part of the service here: http://erikblomqvist.se/junk/car/
Everything works smoothly except for the color changing function (the colored boxes under the headline Färgalternativ). It's supposed to update the price on the colors from brown to light gray (#4 - #8) – those are a bit more expensive, since they are in metallic.
In Chrome, this works as planned, but in Firefox, if I first select a metallic color, then a non-metallic, and THEN a the same metallic again, the price won't change back. It changes correctly the first time, but not the second time I click that metallic color.
In Safari, the price doesn't change at all (I'm guessing that if the Firefox problem gets solved, Safari gets solved as well).
The function is based on a data-name on the color boxes, that gets checked with this function:
$( '#car-colors .color' ).each(function() {
$( this ).on( 'click', function() {
selected_color = undefined;
var color_name = $( this ).data('name');
$( '#car-colors .color' ).not( this ).removeClass('selected');
$( this ).addClass('selected');
$( 'option', color_select ).each( function() {
if( $( this ).val() == color_name ) {
color_select.find( 'option' ).removeAttr('selected');
$( this ).attr('selected', 'selected');
}
});
$( '.selected-color-name' ).fadeIn();
$( '.selected-color-name span' ).html( color_name );
var selected_color = color_select.children(':selected');
checkSelectedColor(selected_color);
});
});
The variable color_select is defined as $( '#order-color-select' ).
The function checkSelectedColor is defined here:
function checkSelectedColor(selected_color) {
if( selected_color.data('is-metallic') == 'yes' ) {
color_checkbox.prop('checked', true);
} else {
color_checkbox.prop('checked', false);
}
color_input.val( selected_color.val() );
calculatePrice();
}
I've added stuff like selected_color = undefined to make sure that the variable is reseted, but after a color that has an <option data-is-metallic="yes"> (inside of #order-color-select) is selected a second time, it handles the value as "no" instead of "yes".
I can't get my head around on why this is, especially only in Firefox/Safari.
I've included the beautified version of the car functions here: http://pastebin.com/i5bup5rx
Appreciate any kind of help that could lead me in the right direction of getting this solved!
Thanks
I think the error is in setting the selected option in the select element using .attr().
Instead you can just set the value of the select element like
$('#car-colors .color').on('click', function() {
var color_name = $(this).data('name');
$('#car-colors .color').not(this).removeClass('selected');
$(this).addClass('selected');
$('#order-color-select').val(color_name);
$('.selected-color-name').fadeIn();
$('.selected-color-name span').html(color_name);
var selected_color = color_select.children(':selected');
checkSelectedColor(selected_color);
});

How to restore jeditable functionality?

I try to figure out, how to restore Jeditable fields after removing cells from table?
I have table where are
rows with one cell (colspan)
rows with many cells (rows with ID-s)
Rows with ID have a cell which contains some text and editable span-element (with Jeditable). Now when I click on button, I want to remove from rows with ID all cells and replace it with cell which contains only the span-element (which should remain editable).
Problem is: I can't restore editability for those recreated spans.
I tried different approaches, most simple should running $( '.editable' ).editable('enable'), but I can't figure out, why it does not working.
One of my efforts is like this:
$(document).ready(function(){
$("#remove").click(function() {
$("table#original tr").each( function( index, row ) {
if ( $( row ).attr( 'id' ) ) {
var editabaleField = $( row ).children( 'td' ).children( 'span' ).text();
$( row ).children( 'td' ).remove();
$("<td colspan='3'><span class='editable'>" + editabaleField + "</span></td>").appendTo( row );
$( '.editable' ).editable('enable');
}
});
});
$('.editable').editable('echo.php', {
type : 'text',
tooltip : 'Just click...'
});
});
Made a Fiddle too, hope it helps to better understand my problem.
Problem
The issue seems to be that the editable object is being destroyed and when you attempt to re-enable it, it doesn't keep the same options so it fails.
Solution:
Abstract the options to a variable (for easier changes going forward)
var editableOptions = {
type : 'text',
tooltip : 'Just click...'
};
var editableURL = 'echo.php';
Update the .editable() call to use these new variables:
$(document).ready(function(){
$("#remove").click(function() {
$("table#original tr").each( function( index, row ) {
if ( $( row ).attr( 'id' ) ) {
var editabaleField = $( row ).children( 'td' ).children( 'span' ).text();
$( row ).children( 'td' ).remove();
$("<td colspan='3'><span class='editable'>" + editabaleField + "</span></td>").appendTo( row );
$( '.editable' ).editable(editableURL, editableOptions)
}
});
});
$('.editable').editable(editableURL, editableOptions);
});
Working JSFiddle
You don't need to recreate editable field in new td cell. In fact you should not remove it in the first place. Proper way of handling this from perspective of performance and optimization is to create new td and move already initialized editable element to it. In this case you don't have to worry about reinitizing it one more time.
So your code will become:
$(document).ready(function () {
$("#remove").click(function () {
$("table#original tr").each(function (index, row) {
if (row.id) {
var editableField = $(row).find('.editable');
var newTd = $("<td colspan='3'></td>").append(editableField);
$(row).empty().append(newTd);
}
});
});
$('.editable').editable('echo.php', {
type: 'text',
tooltip: 'Just click...'
});
});
Demo: http://jsfiddle.net/jxtnd1g4/
Or a little shorter variation for the same thing:
$("#remove").click(function () {
$("table#original tr[id]").html(function() {
var editable = $(this).find('.editable');
return $('<td colspan="3"></td>').append(editable);
});
});

How to disable functionality that takes place after a click event using jQuery

I have a button on my page which, when clicked, listens for another button being clicked and then performs an AJAX call. For example:
$( 'button#a' ).click( function() {
$( 'button#b' ).click( function() {
// Perform an AJAX call here.
});
});
Here is a demo of my code so far:
DEMO
I want to disable the ajax call functionality if a third button button#c is clicked at any time during the time that the page is loaded. I'm at a loss at how this can be done. Hoping someone can suggest an approach.
Should not code click event inside click, but after modifying in your code.
var third_click= false;
$(document).ready(function() {
$( 'button#c' ).click( function() {
third_click = true;
})
$( 'button#a' ).click( function() {
$( 'button#b' ).click( function() {
if( !third_click ) {
// Perform an AJAX call here.
alert( 'ajax call in progress' );
} else {
alert( 'Can\'t call ajax' );
}
});
});
})
here is demo.
What if you used button a to hide button b until a is clicked and then show button b and so fourth until your results are displayed as you with.
example:
$('.btnB').hide();
$('.btnA').on('click', function() {
$('.btnB').toggle();
});
Unless it needs to all display at one time this method wouldn't be able to work in that type of situation
You can just remove the click events from #a and b# when clicking on #c with:
$('#c').click(function () {
$('#a,#b').off('click')
})
jsFiddle example

jQuery mobile nested-list plugin bug going back

I'm using the 'nested-list' plugin for jQuery Mobile, this one:
The problem is that when you use more than one level the plugins fails going back. For example, in the fiddle I have created I can go to 'Test 1.2.1' without problem, If I going back 1 level it works fine and I go to 'Test 1.2', but then if I tried to go up one level more (it was 'Test1') it goes up 2 levels (to 'Test').
I have checked the plugin code but I can't find the problem and I have left a message in the Git forum with no answer. Maybe someone could help me here.
Thanks in advance!
Fiddle
Looking at the plugin code, it is only designed for one level deep nesting. This is because the developer chose to remove created subpages each time you click on a parent LI. So when you get to the second level of depth, its parent has been removed from the DOM and you have to click the back button twice to get to the original page.
I have made some changes to the plugin code that should solve this problem:
In _attachBindings, I have commented out the line that removes previously created subpages:
_attachBindings: function() {
this._on({
"click": "_handleSubpageClick"
});
this._on( "body", {
"pagechange": function(){
if ( this.opening === true ) {
this.open = true;
this.opening = false;
} else if ( this.open === true ) {
//Don't remove the old LI
//this.newPage.remove();
this.open = false;
}
}
});
},...
Then in _handleSubpageClick, I check if the subpage already exists in the DOM (via data attribute added when creating the page). If not, we go through the existing code that creates the subpage, and then in the end I store the created subpage id in a data attribute on the parent LI. If it does exist we just navigate to that page.
_handleSubpageClick: function( event ) {
if( $(event.target).closest( "li" ).children( "ul" ).length == 0 ) {
return;
}
this.opening = true;
//see if we already created the subpage
var $li = $(event.target).closest( "li" );
var pid = $li.data("nextpageid");
if (pid && pid.length > 0){
this.pageID = pid;
} else {
this.newPage = $( this.options.page ).uniqueId();
this.nestedList = $( event.target ).children( "ul" )
.clone().attr( "data-" + $.mobile.ns + "role", "listview" )
.css( "display", "block" );
this.pageName = (
$( event.target.childNodes[0] ).text().replace(/^\s+|\s+$/g, '').length > 0 )?
$( event.target.childNodes[0] ).text() : $( event.target.childNodes[1] ).text();
this.pageID = this.newPage.attr( "id" );
// Build new page
this.newPage.append(
$( this.options.header ).find( "h1" ).text( this.pageName ).end()
).append(
$( this.options.content )
).find( "div.ui-content" ).append( this.nestedList );
$( "body" ).append( this.newPage );
//save subpage id as data attribute of the LI
$li.data("nextpageid", this.pageID);
}
$( "body" ).pagecontainer( "change", "#" + this.pageID );
}...
Here is your updated FIDDLE
I removed the external link to the plugin and instead copied all the code into the javascript pane and made the edits. You should be able to copy that code directly and use as the updated plugin. (Of course I did this quickly and have not rigorously tested it, so make sure it works for you).

Categories

Resources