Roukmoute
Roukmoute

Reputation: 789

Optimize jQuery code?

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.

Upvotes: 0

Views: 148

Answers (2)

Mr.J4mes
Mr.J4mes

Reputation: 9266

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>

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817128

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.

Upvotes: 3

Related Questions