user3437721
user3437721

Reputation: 2289

JQuery to check if textboxes are empty

I have the following code which fills out all the date picker textboxes when a date is selected.

So there may be 5 date pickers. Currently if the user selects a date in any of the date pickers, then ALL date pickers get populated with the selected date (so all 5 date pickers would have the same date)

    //populate all the  dates based on selected date
    $(".txtdatepicker").datepicker({
        onSelect: function (dateText, inst) {
            $(".txtdatepicker").val(dateText);
        }
    });

However, I want to change the code so that the selected date is only inserted into empty date pickers, i.e. the date picker does not already contain a value.

Would I use a .each for this?

EDIT:for some reason all my calendars are auto expanding, I have changed my code to this, is there any way to modify the following instead as it seesm to do the same as above?

$(".txtdatepicker").on("change", function(){

                     $(".txtdatepicker").val($(this).val());

             });

EDIT 2:

This is the solution used in the end:

$(".txtdatepicker").on("change", function(){ 
var date = $(this).val(); 
$(".txtdatepicker").each(function(){ 

if(!$(this).val()){ 
$(this).val(date); 

} 
}); 

});

Upvotes: 0

Views: 354

Answers (2)

bhavya_w
bhavya_w

Reputation: 10077

$(".txtdatepicker").datepicker({
    onSelect: function (dateText, inst) {
            $('.txtdatepicker').each(function(i,current){
                  if(!$(current).val()){ //empty string evaluates to false
                      $(current).val(dateText);
                }
            });               
    }

});

http://jsfiddle.net/dnjrvdaq/3/

Upvotes: 2

iambriansreed
iambriansreed

Reputation: 22241

You were close.

$(".txtdatepicker").datepicker({
    onSelect: function (dateText, inst) {
        $(".txtdatepicker").each(function(){ // each - you were right!
            if( !$.trim( $(this).val() ).length ) 
            // check if the trimmed value is not 0
                $(this).val(dateText);
        });
    }
});

Fiddle

http://jsfiddle.net/8249zoxr/

Upvotes: 2

Related Questions