0

This is pretty basic stuff, but I cant figure this out. I'm using jQuery's DatePicker. My goal is to display some text with the selected date. If the user chooses a date passed today's date, I'm changing the text to too late. When the user re-chooses a future date, I want to set the divs text to something and add the selected date inside a span which sits inside this div. All works except the future date is not appearing. Why?
What is the best practice when it comes to changing content of some element? Can I use jQuerys remove and then append?

HTML:

<p>Date: <input id="datepicker" type="text"></p>
<p id="we_will_start">starting at: <span id="start_date"></span></p>

JQUERY:

$('#datepicker').datepicker({
    onSelect: function(dateText, inst){ 
    var dateAsString = dateText;
    var selectedDateAsObject = $(this).datepicker('getDate');
    console.log("date object=" + new Date+ " jquery date=" + selectedDateAsObject);
    console.log(dateAsString);
    if(selectedDateAsObject < new Date){
        console.log("bad date. cant start yesterday fool");
         $("#we_will_start").text("too late!");
    }else{
        $("#we_will_start").text("will start at ");
         document.getElementById("start_date").innerHTML = dateAsString;
        }
    }
});

fiddle

1
  • 2
    your jquery html(). have a separate span for that and update it. Eg: <p id="we_will_start"><span id="notifyText">starting at: </span><span id="start_date"></span></p> $("#notifyText").html("will start at "); Commented May 7, 2015 at 9:48

1 Answer 1

1

Try this, just concatenate the date string in your text.

$('#datepicker').datepicker({
    onSelect: function(dateText, inst){ 
    var dateAsString = dateText;
    var selectedDateAsObject = $(this).datepicker('getDate');
    console.log("date object=" + new Date+ " jquery date=" + selectedDateAsObject);
    console.log(dateAsString);
    if(selectedDateAsObject < new Date){
        console.log("bad date. cant start yesterday fool");
         $("#we_will_start").text("too late!");
    }else{
        $("#we_will_start").text("will start at " + dateAsString);
        }
    }
});

For the span, after you change the text to "too late" you overwritten all the elements inside the paragraph.

Sign up to request clarification or add additional context in comments.

1 Comment

I cant believe it was so simple.. Thanks a lot for the input. Thats what I was missing, didnt realize I was overwriting the elements as well. When its best to use remove and append?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.