01. Travel Agency

JS Advanced Final Exam - 27 June 2021,
mail@pastecode.io avatar
unknown
javascript
2 years ago
2.6 kB
1
Indexable
Never
function solution() {
    //Select elements
    let inputData = document.querySelectorAll('#form div input');
    const infoPreview = document.querySelector('#infoPreview');
    const sumbimtBtn = document.querySelector('#submitBTN');
    const editBtn = document.querySelector('#editBTN');
    const contBtn = document.querySelector('#continueBTN');

    sumbimtBtn.addEventListener('click', submitElements)
    //Submit input values
    function submitElements(e) {
        e.preventDefault();

        let name = inputData[0].value.trim();
        let email = inputData[1].value.trim();
        //let mobile = inputData[2].value;
        //let address = inputData[3].value;
        //let code = inputData[4].value;

        //Validate input 
        if (name == '' || email == '') {
            return
        }
        //Create li element and append to infoPreview
        inputData.forEach(element => {
            let liElements = document.createElement('li');
            liElements.textContent = element.value;
            infoPreview.appendChild(liElements);
        });
        //Set button as required
        sumbimtBtn.disabled = true;
        editBtn.disabled = false;
        contBtn.disabled = false;
        //Clear input
        inputData.forEach(input => {
            input.value = '';
        });

        editBtn.addEventListener('click', editInput);
        contBtn.addEventListener('click', cont);
        
    }

    //Edit input data function
    function editInput(e) {
        let editData = [];
        const toEdit = document.querySelectorAll('#infoPreview li');
        toEdit.forEach(el => {
            editData.push(el.innerText);
        });
        //return the values to input fields
        inputData[0].value = editData[0];
        inputData[1].value = editData[1];
        inputData[2].value = editData[2];
        inputData[3].value = editData[3];
        inputData[4].value = editData[4];
        //remove new li elements from infoPreview
        toEdit.forEach(el => {
            el.remove();
        });
        //set buttons as required
        sumbimtBtn.disabled = false;
        editBtn.disabled = true;
        contBtn.disabled = true;

    }

    //Confirm reservation funtion
    function cont(e) {
        const divBlock = document.querySelector('#block');
        divBlock.innerHTML = '';
        const reservation = document.createElement('h3');
        reservation.textContent = 'Thank you for your reservation!';
        divBlock.appendChild(reservation);
    }
}