July 23, 2013

How to get value from text input on blur of field

Sehummel’s Question:

I’m trying to write some Javascript to get the value from two text inputs, which should be fairly straightforward. But something is amiss. Here is my code:

<script>
    jQuery(function() {
        jQuery('#fromPicker, #toPicker').datepicker({ dateFormat : 'yy-mm-dd' });

        jQuery('#submit').attr('disabled', 'disabled');

        jQuery('#toPicker').on('blur', function() {
            var fromDate = jQuery('#fromPicker').val();
            var toDate = jQuery('#toPicker').val();
            console.log(toDate);

            if (fromDate !== '' && toDate !== '') {
                if (isValidDate(fromDate) && isValidDate(toDate)) {
                    jQuery('#submit').removeAttr('disabled');
                } else {
                    alert('You must enter dates in the format "yyyy-mm-dd"');
                }
            } 
        });
    });

    function isValidDate(dt) {
        if (dt.match(/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/)) {
            return true;
        }
    }
</script>

When I console.log(toDate) however, I get an empty string. But if I do another blur event again (focus and unfocus the field with the data still in it), I get the correct value. Any ideas why it doesn’t work the first time?

The two text inputs have IDs of #fromPicker and #toPicker and are jQueryUI datepickers.

SOLUTION:

What ultimately did what I wanted was this:

jQuery(function() {
jQuery(‘#fromPicker, #toPicker’).datepicker({
dateFormat : ‘yy-mm-dd’
});

    jQuery('#submit').on('click', function() {
        var fromDate = jQuery('#fromPicker').val();
        var toDate = jQuery('#toPicker').val();

        if (fromDate !== '' && toDate !== '') {
            if (isValidDate(fromDate) && isValidDate(toDate)) {
                // do nothing
            } else {
                alert('You must enter dates in the format "yyyy-mm-dd"');
                return false;
            }
        } else {
            return false;
        }
    });
});

function isValidDate(dt) {
    if (dt.match(/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/)) {
        return true;
    }
} </script>

I dont see any reason for your code not to work but instead of blur event, try onselect event of the datepicker instead

jQuery('#toPicker').datepicker( {
    onSelect: function(date) {
        alert(date);
        // Do other stuff
    },
    // ....
);
March 7, 2013

Reload parent dialog content when child dialog is closed

Question by user1277546

I have a large jQuery dialog window that opens up many more dialog windows inside when buttons are clicked in the parent dialog window for updating the database.

I want to update the parent window when the child dialogs are closed.

I can see how to do this with event close and load(url) but how do I make the association between child and parent without specifying each and every ID.

Answer by Starx

Without some markup structures, I cannot understand how your child dialogs resides inside parent.

jQuery has a function called .closest() that travel up the DOM tree to find the nearest matching selector, so you can use this by giving a class to the parent dialog. And select them, when you want to use it like.

$(this).closest(".parent").html("Updated Content");
// ^ Represent your child dialog as you want
August 31, 2012

jquery slide out from record

Question by Matthew

I am looking for some advice on an idea which i am unsure if i can do it or not…

i am loading records out of a database and listing them in individual divs and adding an id number from the databse to the divs,the divs are about 100px wide and right across the screen..

i am wondering if i can use some kinda of plugin by jquery so that if i click on the record a tab would slide out from the right hand side with more data on that individual record from the database.. and then i could close it and it would side back so i can only see the records again..

i have had a bit of a look at the jquery ui page with all the demos but i didnt really find anything…

any help or pointers would be great.. even if u know of something simllar ill be happy to look into it…

thanks in advance for any help

Answer by ComputerArts

Ok so here’s my fiddle

HTML (standard containers, etc)

<div id="container">
    <div id="buttons-container"></div>
    <div id="record">
        <div id="record-content"></div>            
        <a href="#" id="bt-close" onclick="closeRecord(); return false;">Close</a></div>
</div>

CSS

a.bt-record {
    display:block;
    width:100px;
    height:100px;
    background:#999999;
    color:#000;
    line-height:100px;
    text-align:center;
    float:left;
    margin:0 10px 10px 0;
    text-decoration:none;
}

a { color:#fff; }

#container {
    width:100%;
    height:100%;
    overflow:hidden;
    position:relative;
}

#record {
    position:absolute;
    right:-240px;
    top:100px;
    width:200px;
    height:200px;
    background:#000;
    padding:20px;
    color:#fff;
    z-index:1;
}

Javascript

//your data in a array of objects (could be something else)
var data = {
    1 : {name:'Record 1', text:'This is the text 1', options:'Anything 1'},
    2 : {name:'Record 2', text:'This is the text 2', options:'Anything 2'},
    3 : {name:'Record 3', text:'This is the text 3', options:'Anything 3'},
    4 : {name:'Record 4', text:'This is the text 4', options:'Anything 4'},
    5 : {name:'Record 5', text:'This is the text 5', options:'Anything 5'},
    6 : {name:'Record 6', text:'This is the text 6', options:'Anything 6'},
    7 : {name:'Record 7', text:'This is the text 7', options:'Anything 7'},
    8 : {name:'Record 8', text:'This is the text 8', options:'Anything 8'},
    9 : {name:'Record 9', text:'This is the text 9', options:'Anything 9'}
};

$(document).ready(function() {
    populateEntries();        
});

//dynamically populate the entries
function populateEntries() {
    for (entry in data){
console.log(entry);       
        $('#buttons-container').append('<a class="bt-record" href="#" onclick="showRecord(' + entry + '); return false;">' + data[entry].name + '</a>');
    }
}

//show the record
function showRecord(id) {
    //create the html
    var html = '';
    html += '<p>Name : ' + data[id].name + '</p>';
    html += '<p>Text : ' + data[id].text + '</p>';
    html += '<p>Name : ' + data[id].options + '</p>';
    $('#record-content').html(html);
    $('#record').animate({right:0}, 500);
}

function closeRecord() {
    $('#record').animate({right:-240}, 500);
}

In this example, I populate the records dynamically, but if you want a SEO friendly way of doing it, you can create the HTML in the page directly. Let me know if you have questions.

Answer by Starx

Sure, let me show you a simple example. It is rather very easy

<table>
    <tr class="recordrow" id="row-1"> <!-- row-X will be the unique way to identify the row -->
       <td>...</td> <!-- The record field -->
       <td>...</td>
       ....
    </tr>
</table>

<!-- Now we create the details Div, but as reference to the `row-X` -->
<div class="details" id="details-1">
   ... More details of the records
</div>

then a simple jQuery snippet like this will get the job done:

$(".recordrow").click(function() {
    var divid = "details-" + $(this).attr('id').split("-")[1]; //Create the id of the div
    $("#"+divid).show().animate({ "left": '200px'}); //Bring the div from right to left with 200px padding from the screen
});

Demo

July 22, 2012

how to navigate from one tab to other by clicking on a hyperlink using jquery ui tabs

Question by Hardworker

Could any one help me on how to navigate from first tab to second tab by clicking a hyperlink in first tab using JQUERY UI tabs?

Answer by Shant

You can refer the jQuery UI Tabs documentation for your problem, its very well mentioned

var $tabs = $('#example').tabs(); // first tab selected

$('#my-text-link').click(function() { // bind click event to link
    $tabs.tabs('select', 2); // switch to third tab
    return false;
});

Answer by Starx

You can switch between tabs freely by following the indexes using select method.
An example:

$("#tabs").tabs('select', 1);

Attach this snippet to the click handler of the link on the content of first tabs.

Example:

For a link like this:

<a href="some.html" id="nextTab">Go to Next Tab</a>

jQuery:

$("#nextTab").click(function() {
     $("#tabs").tabs('select', 1);
});
April 29, 2012

Serializing Jquery-ui sortable with dynamically updated content

Question by nbu

I have a sortable list that updates my database when items are shifted around. However, there’s also a feature where users can add new items to the list dynamically. When these items are added, for some reason, sortable acts as if they don’t exist when updating the item positions in the database.

Is there a way to essentially serialize the sortable list after an item is added so it is essentially ‘live’ on the page?

I’ve looked into the .refresh() code but that doesn’t seem to work…Thanks!

Answer by Starx

If simple enought, you can use the callback method of the adding sequence and update the database like that instead.

$("#newtab").appendTo("#sortableContainer", function() {
    //OK its time to update this addition to the database
});

How do I animate in jQuery without stacking callbacks?

Question by yuval

Let’s say I have three divs, and I’d like each to animate once the previous one is done. Currently, I write this:

$('div1').fadeOut('slow', function() {
    $('div2').fadeOut('slow', function() {
        $('div3').fadeOut('slow');
    });
});

Which is ugly, but manageable.

Now imagine I have 10 different animations that need to happen one after the other on different elements. Suddenly the code gets so clunky that it’s extremely hard to manage…

Here’s pseudocode for what I’m looking to do:

$('div1').fadeOut('slow' { delay_next_function_until_done: true } );
$('div2').fadeOut('slow' { delay_next_function_until_done: true } );
$('div3').animate({ top: 500 }, 1000 );

How do I achieve this?

Answer by Julian Aubourg

If you’re using a recent version of jQuery, use the animation promises:

$('div1').fadeOut('slow' ) ).promise().pipe(function() {
    return $('div2').fadeOut('slow' );
}).pipe(function() {
    return $('div3').animate({ top: 500 }, 1000 );
});

You can make it generic:

$.chain = function() {
    var promise = $.Deferred().resolve().promise();
    jQuery.each( arguments, function() {
        promise = promise.pipe( this );
    });
    return promise;
};

var animations = $.chain(function() {
    return $('div1').fadeOut('slow');
}, function() {
    return $('div2').fadeOut('slow');
}, function() {
    return $('div3').animate({ top: 500 }, 1000 );
});

$.when( animations ).done(function() {
    // ALL ANIMATIONS HAVE BEEN DONE IN SEQUENCE
});

Still a lot of function closures but that’s the very nature of Javascript. However, it’s much more natural and a lot more flexible using Deferreds/Promises since you avoid callbacks “inception”.

Answer by Starx

Callback is a friend, dont push it away. There are ways to simplify them. Here is one of them

$('div1').fadeOut('slow', div2)
function div3() { $('div3').fadeOut('slow'); }
function div2() { $('div2').fadeOut('slow', div3); }
April 23, 2012

How should I integrate both jQueryUI draggable and sortable in my project?

Question by chaonextdoor

I want to integrate both jQueryUI draggable and sortable in my project and distinguish them using the time difference between the starting time of mousedown and first mousemove events. Part of my code is as follows:

var deltaX = self.mouse.startX - event.pageX,
    deltaY = self.mouse.startY - event.pageY;
if (self.mouse.mousedownTime - self.mouse.mousemoveTime < 700){                   
                // Drag down
                if(Math.abs(deltaX) < Math.abs(deltaY) && deltaY < 0){
                    $(self.el).draggable({disabled: false});
                    $(self.el).sortable({disabled: true});
                    $(self.el).draggable({axis: 'y'});
                    $(self.el).draggable({revert: true});
 ....
}
// Sorting action
else {
            $(self.el).sortable({disabled: false});
            $(self.el).draggable({disabled: true}); // global dragging
            $(self.el).sortable({containment: $(self.el).closest('.content')});
        }

But things are not what I expected. Every time I start dragging the element, the html shown in firebug has the right draggable/sortable class setting but it’s not effective for current dragging events. For example, when you drag for the first time, the element is neither draggable nor sortable although the html has already had the corresponding class setting. It will be draggable or sortable the second time you drag it. And if you set the element draggable/sortable for current dragging event, it only works the next time you drag it.

In a word, the draggable/sortable event you expect for current event will only be effective for the next event. I wanna know if this is what the jQueryUI should be or there is sth wrong with my code. How should I fix it? How should I integrate both draggable and sortable in my project?

Answer by Starx

This is an expected behavior, to hook an plugin onto the element, it has to listen to when it will be dropped and where it will be dragged.

Normally these two plugin work side-by-side. So I dont think there is a way to do this, without making the element only draggable, since droppable would need to be dragged anyhow.

April 18, 2012

'div_element' is null or not an object in IE7

Question by nic

here i have get one error in java script ‘div_element’ is null or not an object.
i have given my code below

function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}

when i debugging my script so it’s working fine in other browser including IE 8. but it’s not working in IE 7.i don’t understand what exact issue occur in this script.

Thanks in Advance.

Answer by Starx

First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.

Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.

Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.

function showLoading(id) {

    div_element = $("#" + id);
    console.log(div_element); //check the console to see if it return any element or not
    div_element.html(loading_anim);

}
April 3, 2012

How can I have the user change options of the jQuery UI Slider?

Question by Sam Pellino

I have a jQuery UI slider on my page. It starts out with:

$( "#slider" ).slider({
    value: 6,
    min: 6,
    max: 120,
    step: 6
});

Which works fine.

I have a select element next to it with 6, 12, and 24 as options.
What I would like to accomplish is for the user to select 12, and the slider’s step, min, and value all go to 12 (same for 24). I have already tried to build a function:

$('#dropdown').change(function(){
    $( "#slider" ).slider( "option", "value", $(this).val() );
    $( "#slider" ).slider( "option", "min", $(this).val() );
    $( "#slider" ).slider( "option", "step", $(this).val() );
    $( "#slider" ).slider( "option", "max", 120 );
});

However all this does is make is go to value 12, then upon clicking the slider, it jumps all the way to the end (120) and just stays there.

Do I need to destroy the slider and make it again from scratch?

EDIT #1:

I did just download Firebug and check the slider with the console, and the values are all returning correct (min=12,value=12,step=12,max=120). Does anyone know why it’s being so stubborn and jumping/sticking to the end?

Answer by DigitalBiscuits

Found the issue.
You need to parse the value from the <select> to an int before you use it to change the options of the slider.

$('#dropdown').change(function()
{
    var currentVal =  parseInt($("#slider").slider("value"));
    var newOptions = parseInt($(this).val());
    $( "#slider" ).slider( "value", currentVal);
    $( "#slider" ).slider( "option", "min", newOptions );
    $( "#slider" ).slider( "option", "step", newOptions );
    $( "#slider" ).slider( "option", "max", 120 );
});

Working Example

http://jsfiddle.net/DigitalBiscuits/VSBCT/1/

Answer by Starx

Implementation is correct. But you can cache the results

$('#dropdown').change(function(){
    var val = this.value;
    $( "#slider" ).slider( "option", "value", val );
    $( "#slider" ).slider( "option", "min", val );
    $( "#slider" ).slider( "option", "step", val );
    $( "#slider" ).slidYou can er( "option", "max", 120 );
});
March 31, 2012

getting the child text from a div in a .each loop

Question by randy

this is just a couple of lines of code that i have in my page.
I am using the jquery ui drag and drop. These are two of the items of many

when the saved button is press i need to get all the IDs and the text in the group_name div

This function gets the ID ok but i can not figure out how to get the $(‘group_name’).text() from the current LI in the each loop.

   function saveChanges(){
        $("li.ui-state-default").each(function() {
            var $divitem = $( this );
            console.log($divitem.attr('id'));
        });
    }

this is the html snippet

<li id="5" class="ui-state-default">
<div class="group_name">Classes</div>
<div class="group_footer">
      <a title="Delete this group" class="mytrash-icon" href="#">
         <img border="0" src="trash.png" class="mytrash-img"></a>
      <a title="Manage Subfolders" class="subfolder" href="#">   
         <img border="0" src="Folder-Icon.png"></a>
    </div>
</li>
<li id="6" class="ui-state-default">
<div class="group_name">Coaching</div>
<div class="group_footer">
        <a title="Delete this group" class="mytrash-icon" href="#">
          <img border="0" src="trash.png" class="mytrash-img"></a>
        <a title="Manage Subfolders" class="subfolder" href="#">
          <img border="0" src="Folder-Icon.png"></a>
    </div>
</li>

Thanks for any help!

Answer by Starx

One way would be to use .find()

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($divitem.find(".group_name").text());
});​

Another would be to use .children()

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($divitem.children(".group_name").text());
});​

But the one I like is neither

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($(".group_name", $divitem).text());
});

...

Please fill the form - I will response as fast as I can!