Ominięcie następnego elementu po pustym inpucie

0

Witam, chciałbym żeby system nie podawał następnego elementu po inpucie który nie został wypełniony.

Skrypt działa bardzo dobrze jeśli autorzy mają wpisane inicjały jednak kiedy autorzy nie mają inicjałów, skrypt wyświetla o jedną spację i przecinek za dużo, np:
(J, , Kowalski. J, , Nowak. PWN, 123, 1990) - docelowo chciałbym żeby było napisane (J, Kowalski. J, Nowak. PWN, 123, 1990)

Jak mogę to usunąć?

Kod wygląda następująco:

    
    console.log(numberOfAuthors);
    
    var div = document.getElementById("readyorder");
        
    var firstAuthorName = document.getElementById("firstAuthorName");
    
    var firstCharacter =  firstAuthorName.textContent.slice(0,1);

    var firstAuthorInitials = document.getElementById("firstAuthorInitials");
    var firstAuthorSurname = document.getElementById("firstAuthorSurname");
    
    div.innerHTML = "(";
    
    div.innerHTML += firstAuthorName.value.charAt(0) + ", " + firstAuthorInitials.value + ", " + firstAuthorSurname.value + ". ";    
    
    
    for(var authorId = 0 ; authorId < numberOfAuthors ; authorId++ ){
        
        var authorName = document.getElementById("authorName"+authorId);
	    var authorInitials = document.getElementById("authorInitials" + authorId);
	    var authorSurname = document.getElementById("authorSurname" + authorId);
	  
	    div.innerHTML += authorName.value.charAt(0) + ", "+authorInitials.value+", "+authorSurname.value+". ";    
    }
    
    var publisher = document.getElementById("publisher");
    
    var page = document.getElementById("page");
    
    var pageOther = document.getElementById("pageOther");
    var pageOtherValue =  pageOther.value;
    
    if(pageOther.value!=""){
        pageOtherValue = "-" + pageOther.value;
    }else{
        pageOtherValue = "";
    }
    
    var year = document.getElementById("year");
    
    div.innerHTML += publisher.value + ", "+page.value + pageOtherValue + ", "+year.value;    
    
    div.innerHTML += ")"
0

Nadal trudno mi ogarnąć jak ma to działać, bo brakuje przykładowych wartości. Spróbuj pogrzebać tutaj:

div.innerHTML += firstAuthorName.value.charAt(0) + ", " + firstAuthorInitials.value + ", " + firstAuthorSurname.value + ". ";

Brakuje Ci warunków, że jeżeli puste to nie dołączaj przecinka itd.. Jak zastąpisz czymś takim to powinno działać:

div.innerHTML += [firstAuthorName.value.charAt(0), firstAuthorInitials.value, firstAuthorSurname.value].filter(i => i).join(', ') + ". ";

To samo zrób wewnątrz pętli for w Twojej funkcji getText Dlaczego to działa? Bo:

['foo', undefined, 'bar'].filter(i => i).join(', ');
// "foo, bar"
['foo', 'asdasd', 'bar'].filter(i => i).join(', ');
// "foo, asdasd, bar"

1 użytkowników online, w tym zalogowanych: 0, gości: 1