Problem with break in if

3

If I put a break in the first loop if , it just does not work or execute anything .. It seems like break is read first, even without entering% with%. What's the problem?

function verifynasc(field) {
    var nascimento = field.value;
    alert(nascimento);
    if (nascimento.length > 10) {
        alert("entrou no if");
    }
    nascimento = nascimento.replace('/', '');
    var dia = '';
    var mes = '';
    var ano = '';
    for (var i = 0; i < nascimento.length; i++) {
        if (i < 2) {
            var dia = dia + nascimento.charAt(i);
            continue
        } else if (i < 4) {
            var mes = mes + nascimento.charAt(i);
            continue
        } else {
            var ano = ano + nascimento.charAt(i);
        }
    }
    var data = ano + "-" + mes + "-" + dia;
    document.getElementById('date').value = data;
}
    
asked by anonymous 20.10.2014 / 23:45

2 answers

3

Your code could be improved, restructure these if s so you do not need return , which you thought to be continue .

The problem is that break and continue are for LOOPS, not for IF

Instead of continuing, you would use return in if .

The break command "jumps out" of a loop.

The continue command "just jumps" a loop interaction.

function verifynasc(field) {
    var nascimento = field.value;
    alert(nascimento);
    if (nascimento.length > 10) {
        alert("entrou no if");
    }
    nascimento = nascimento.replace('/', '');
    var dia = '';
    var mes = '';
    var ano = '';
    for (var i = 0; i < nascimento.length; i++) {
        if (i < 2) {
            dia = dia + nascimento.charAt(i);
        } else if (i > 3 && i < 4) {
            mes = mes + nascimento.charAt(i);
        } else {
            ano = ano + nascimento.charAt(i);
        }
    }
    var data = ano + "-" + mes + "-" + dia;
    document.getElementById('date').value = data;
}
    
21.10.2014 / 00:06
1

Assuming I read your code well, you're trying to make sure that:

  • A date entered with / is then sent with - ;
  • A date in the "DD-MM-YYYY" format is then sent to "YYYY-MM-DD".

Something simpler could be:

Example in JSFiddle

HTML

<input value="" onblur="formatDate(this)" onkeyup="this.value=this.value.replace(/\-/g,'/')">

JS

function formatDate (field) {
    var date = new Date(field.value);
    var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    field.value = year + "-" + month + "-" + day;   
}

The idea is to have the event blur to call the function that will format the date, while we have the event keyup to change the - to / so that the formatting function works correctly. p>

In this way avoid cycles and checks via IF~ELSE .

    
21.10.2014 / 01:13