0

I just want me to know how is it possible to optimize this code snippet?

$('#datedebut').change(function() {
    if (Date.parse($('#datefin').val()) - Date.parse($(this).val()) <= 0) {
        alert('Impossible');
    }
});

$('#datefin').change(function() {
    if (Date.parse($(this).val()) - Date.parse($('#datedebut').val()) <= 0) {
        alert('Impossible');
    }
});

I think it is repeating the same thing, but I do not know how to find something that is optimized and of course simple.

Thank you in advance for your proposal.

2 Answers 2

3

If you don't mind looking up the elements again, you could simply do

$('#datedebut, #datefin').change(function() {
    if (Date.parse($('#datefin').val()) - Date.parse($('#datedebut').val()) <= 0) {
        alert('Impossible');
    }
});

Of course you can also select the elements once and keep references to them...

However, it is not optimization in terms of performance.

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

1 Comment

I can't really see a better way to do it! No matter what, both elements will need to be looked up in order to make the comparison. I can imagine a way to cache each lookup so that it's only done once, but then the resulting code is more verbose than it needs to be. Unless it's an iterator running thousands of times, not much need to optimize performance on a trivial function.
0

You can try this one:

<input type="text" id="datefin" onchange="validateChange()" />
<input type="text" id="datedebut" onchange="validateChange()" />

<script type="text/javascript">
    function validateChange(){
        if (Date.parse($('#datefin').val()) - Date.parse($('#datedebut').val()) <= 0) {
            alert('Impossible');
        }
    });
</script>

1 Comment

Inline event handlers are generally good to avoid these days.

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.