Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Вывод результата в массив. (https://javascript.ru/forum/misc/79467-vyvod-rezultata-v-massiv.html)

Малик 13.02.2020 06:26

Вывод результата в массив.
 
Доброе утро всем!
Я в программировании новичок, так что многих вещей еще совсем не понимаю.
Вот смотрите, есть html со скриптом для теста, где каждый вопрос появляется по очереди за предыдущим. Нужно чтобы после ответа на последний вопрос, результат этого теста выводился в массив results в формате JSON- строки. Как это сделать не подскажите?

Вот HTML:

<body>

    <form id="vote" action="#" method="POST">
        <div id="content">
            <div class="pattern form-5 form-group">
                <label class="question form-group ">{% question %}</label><br>
                <div class="answers"><br><br>
                    <div class="checkbox custom-control custom-checkbox form-control"><label><input type="checkbox" name="poll" value="{% answer.value %}">{% answer.title %}</label></div>
                </div>
            </div>
        </div>
        <div><button type="submit" class="btn btn-primary">Ответить</button></div>
    </form> 
   </body>        
<script>
    const data = [{
    "id": "1",
    "question": "Какие языки программирования Вы используете?",
    "answers": ["C#", "C++", "ASP.NET", "PHP"]
}, {
    "id": "2",
    "question": "С какими СУБД Вам приходилось работать?",
    "answers": ["MS-SQL Server 2000-2012/T-SQL", "Oracle", "MySQL", "PostgreSQL"]
}, {
    "id": "3",
    "question": "С какими системами контроля версий Вы работали?",
    "answers": ["GIT", "CVS", "Subverion", "Mercurial"]
}];

const content = document.getElementById('content');
const patternNode = content.querySelector('.pattern');

patternNode.classList.remove('pattern');
const pattern = patternNode.outerHTML;
patternNode.parentNode.removeChild(patternNode);

data.forEach(function(question, index) {
    content.insertAdjacentHTML('beforeEnd', pattern.replace(/{%\s?question\s?%}/gim, question.question));
    const questionNode = content.lastChild;
    questionNode.dataset.index = index;
    questionNode.style.display = 'none';
    const answers = questionNode.querySelector('.answers');
    const answer = answers.querySelector('.checkbox').outerHTML;
    answers.innerHTML = question.answers.map(function(title, value) {
        return answer
            .replace(/{%\s?answer.title\s?%}/gim, title)
            .replace(/{%\s?answer.value\s?%}/gim, value);
    }).join("\n");
});

let currentQuestionIndex = 0;
const questions = [].slice.call(content.querySelectorAll('[data-index]'));
questions[0].style.display = 'block';

document.querySelector('#vote [type="submit"]').addEventListener('click', function(e) {
    questions[currentQuestionIndex].style.display = 'none';
    if (++currentQuestionIndex >= questions.length)
        return;

    e.preventDefault();
    questions[currentQuestionIndex].style.display = 'block';
});
 
</script>

рони 13.02.2020 08:20

опросник последовательный вывод вопросов из базы данных
 
Малик,
не плодите однотипные темы, пишите в одной и той же!!!
<!DOCTYPE html>
<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  </style>
</head>
<body>

    <form id="vote" action="#" method="POST">
        <div id="content">
            <div class="pattern form-5 form-group">
                <label class="question form-group ">{% question %}</label><br>
                <div class="answers"><br><br>
                    <div class="checkbox custom-control custom-checkbox form-control"><label><input type="checkbox" name="poll" value="{% answer.value %}">{% answer.title %}</label></div>
                </div>
            </div>
        </div>
        <div><button type="submit" class="btn btn-primary">Ответить</button></div>
    </form>
   </body>
<script>
    const data = [{
    "id": "1",
    "question": "Какие языки программирования Вы используете?",
    "answers": ["C#", "C++", "ASP.NET", "PHP"]
}, {
    "id": "2",
    "question": "С какими СУБД Вам приходилось работать?",
    "answers": ["MS-SQL Server 2000-2012/T-SQL", "Oracle", "MySQL", "PostgreSQL"]
}, {
    "id": "3",
    "question": "С какими системами контроля версий Вы работали?",
    "answers": ["GIT", "CVS", "Subverion", "Mercurial"]
}];

const content = document.getElementById('content');
const patternNode = content.querySelector('.pattern');

patternNode.classList.remove('pattern');
const pattern = patternNode.outerHTML;
patternNode.parentNode.removeChild(patternNode);

data.forEach(function(question, index) {
    content.insertAdjacentHTML('beforeEnd', pattern.replace(/{%\s?question\s?%}/gim, question.question));
    const questionNode = content.lastChild;
    questionNode.dataset.index = index;
    questionNode.style.display = 'none';
    const answers = questionNode.querySelector('.answers');
    const answer = answers.querySelector('.checkbox').outerHTML;
    answers.innerHTML = question.answers.map(function(title, value) {
        return answer
            .replace(/{%\s?answer.title\s?%}/gim, title)
            .replace(/{%\s?answer.value\s?%}/gim, value);
    }).join("\n");
});

let currentQuestionIndex = 0;
const questions = [...content.querySelectorAll('[data-index]')];
questions[0].style.display = 'block';

document.querySelector('#vote [type="submit"]').addEventListener('click', function(e) {
    e.preventDefault();
    questions[currentQuestionIndex].style.display = 'none';
    if (++currentQuestionIndex >= questions.length) {
    const total = questions.map((el,k) => ({[data[k].id] : [...el.querySelectorAll('input[type="checkbox"]')].map(({checked},i) => checked ? data[k].answers[i] : "").filter(a => a)}))
    this.parentNode.innerHTML = JSON.stringify(total, "", 4);
    return false;
    }
else questions[currentQuestionIndex].style.display = 'block';

});

</script>

</html>

Малик 13.02.2020 09:23

рони,
Извиняюсь, уже сделал по-другому все, просто не знаю можно ли удалять созданные тмы, но появился такой вопрос: Внизу я приложил html, в нем все такая же форма, в конце 2 массива выводятся в объект и появляются на странице последнего вопроса. И теперь вопрос, можно ли сделать так чтобы данные этих результатов формы выводились не как alert, а также на странице, типа "Страницы Результативности"

<body>
    <form>
        <div class=" container row col-md-4 mt-4" id="d1">
            <div>
                <label>Имя</label>
        <input type="text" id="FirstName" class="form-control" placeholder="First name">
    <label>Фамилия</label>
        <input type="text" id="LastName" class="form-control" placeholder="Last name">
    <label>Город</label>
        <input type="text" id="City" class="form-control" placeholder="City"> 
    <label>Телефон</label>
        <input type="tel" id="Phone" class="form-control" placeholder="Number" > 
    <label>Вакансия</label>
        <select class="form-control" id="Vacancy">
            <option selected>Choose...</option>
                <option value="Backend">Backend</option>
                <option value="Web-Design">Web Design</option>
                <option value="Frontend">Frontend Developer</option>
        </select>
            </div>
            <input type="button" value="Далее"  class="btn btn-primary"
            onclick="document.getElementById ('d1').style.display = 'none';
                     document.getElementById ('d2').style.display = 'block'">
        </div>
    <div id="d2" style="display: none;"> 
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="Какие языки программирования Вы используете?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck1" value="c#">
            <label class="custom-control-label" for=>C#</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck2" value="c++" >
            <label class="custom-control-label" for="CustomCheck2">C++</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck3" value="asp.net" >
            <label class="custom-control-label" for="CustomCheck3">ASP.NET</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck4" value="php" >
            <label class="custom-control-label" for="CustomCheck3">PHP</label><br>
        </div>
        <input type="button" value="Далее"  class="btn btn-primary"
                    onclick="document.getElementById ('d2').style.display = 'none';
                             document.getElementById ('d3').style.display = 'block'">
    </div><br>
    <div id="d3" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="С какими СУБД Вам приходилось работать?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck5" value="mssql">
            <label class="custom-control-label" for="CustomCheck5">MS-SQL Server 2000-2012/T-SQL</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck6" value="oracle" >
            <label class="custom-control-label" for="CustomCheck6">Oracle</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck7" value="mysql" >
            <label class="custom-control-label" for="CustomCheck7">MySQL</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck8" value="postgresql" >
            <label class="custom-control-label" for="CustomCheck8">PostgreSQL</label><br>
        </div>
        <input type="button" value="Далее"  class="btn btn-primary"
                    onclick="document.getElementById ('d3').style.display = 'none';
                             document.getElementById ('d4').style.display = 'block'">
    </div><br>
    <div id="d4" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="С какими системами контроля версий Вы работали?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck9" value="git">
            <label class="custom-control-label" for="CustomCheck9">GIT</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck10" value="cvs" >
            <label class="custom-control-label" for="CustomCheck10">CVS</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck11" value="subversion" >
            <label class="custom-control-label" for="CustomCheck11">Subverion</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck12" value="mercurial" >
            <label class="custom-control-label" for="CustomCheck12">Mercurial</label><br>
        </div>
        <input type="submit" value="Далее" class="btn btn-primary" onclick="convert_to_json()">
    </div><br>
        
    </form>
</body>
<script>

function convert_to_json() {
    const checArr = arr => arr.filter(({
        checked
    }) => checked).map(({
        value
    }) => value);
    profile = { 
         name: FirstName.value,
        lastname: LastName.value,
        city: City.value,
        phone: Phone.value,
        vacancy: Vacancy.value,
    };
    results = {
        Lang_list: checArr([CustomCheck1,
            CustomCheck2,
            CustomCheck3,
            CustomCheck4
        ]),
        SUBD_list: checArr([CustomCheck5,
            CustomCheck6,
            CustomCheck7,
            CustomCheck8
        ]),
        SystemControl_list: checArr([CustomCheck9,
            CustomCheck10,
            CustomCheck11,
            CustomCheck12
        ])
    };
    let json = JSON.stringify(results);
    let json2 = JSON.stringify(profile)
    alert("profile: " + json2 + "results: " + json);
}
</script>

рони 13.02.2020 09:34

Малик,
отправить результат на сервер и вернуть в необходимом виде

Малик 13.02.2020 09:37

рони,
Просто вы в своем коде, который вы написали до этого в этой теме, у вас результат как json строка потом появился отдельно на странице, а не как alert.
Заранее благодарю.

рони 13.02.2020 09:40

Малик,
так предусмотрите некий блок, скройте форму и выведите результат в этот блок, зачем вам ещё страница отдельно?

Малик 13.02.2020 09:45

рони,
Вот именно это и хотел у вас узнать, если я создам блок и скрою его, как потом туда поместить данные массива, вместо alert надо что то другое использовать?

Малик 13.02.2020 09:45

рони,
Еще раз извиняюсь за то что достаю, просто я еще совсем зеленый во всем этом, поэтому потихоньку пытаюсь понимать

рони 13.02.2020 09:48

Малик,
Цитата:

Сообщение от рони
this.parentNode.innerHTML

<div><button type="submit" class="btn btn-primary">Ответить</button></div>

в данном случае использован блок в котором была кнопка.
кнопка "стёрта" результатом

читать по теме
Изменение документа

рони 13.02.2020 09:51

Цитата:

Сообщение от Малик
вместо alert надо что то другое использовать?

innerHTML или append или insertAdjacentHTML, читать по ссылке выше

Малик 13.02.2020 11:12

Извиняюсь ребят, но я так и не врубаюсь как в данный скрипт добавить блок и сделать так чтобы он туда выводился вместо окна alert. Извиняюсь за тупняк)
[script]
function convert_to_json() {
const checArr = arr => arr.filter(({
checked
}) => checked).map(({
value
}) => value);
profile = {
name: FirstName.value,
lastname: LastName.value,
city: City.value,
phone: Phone.value,
vacancy: Vacancy.value,
};
results = {
Lang_list: checArr([CustomCheck1,
CustomCheck2,
CustomCheck3,
CustomCheck4
]),
SUBD_list: checArr([CustomCheck5,
CustomCheck6,
CustomCheck7,
CustomCheck8
]),
SystemControl_list: checArr([CustomCheck9,
CustomCheck10,
CustomCheck11,
CustomCheck12
])
};
let json = JSON.stringify(results);
let json2 = JSON.stringify(profile)
alert ("profile: " + json2 + "results: " + json);
}
[/script]

Малик 13.02.2020 11:15

Извиняюсь ребят, но я так и не могу разобраться как правильно будет в данный скрипт вставить вместо alert, блок, который будет появляться с json строкой.
function convert_to_json() {
    const checArr = arr => arr.filter(({
        checked
    }) => checked).map(({
        value
    }) => value);
    profile = { 
         name: FirstName.value,
        lastname: LastName.value,
        city: City.value,
        phone: Phone.value,
        vacancy: Vacancy.value,
    };
    results = {
        Lang_list: checArr([CustomCheck1,
            CustomCheck2,
            CustomCheck3,
            CustomCheck4
        ]),
        SUBD_list: checArr([CustomCheck5,
            CustomCheck6,
            CustomCheck7,
            CustomCheck8
        ]),
        SystemControl_list: checArr([CustomCheck9,
            CustomCheck10,
            CustomCheck11,
            CustomCheck12
        ])
    };
    let json = JSON.stringify(results);
    let json2 = JSON.stringify(profile)
    alert ("profile: " + json2 + "results: " + json);
}

рони 13.02.2020 11:24

Малик,
медитировать строки: 100, 104, 108, 109, 142.

<!DOCTYPE html>
<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">

</head>
<body>
    <form>
        <div class=" container row col-md-4 mt-4" id="d1">
            <div>
                <label>Имя</label>
        <input type="text" id="FirstName" class="form-control" placeholder="First name">
    <label>Фамилия</label>
        <input type="text" id="LastName" class="form-control" placeholder="Last name">
    <label>Город</label>
        <input type="text" id="City" class="form-control" placeholder="City">
    <label>Телефон</label>
        <input type="tel" id="Phone" class="form-control" placeholder="Number" >
    <label>Вакансия</label>
        <select class="form-control" id="Vacancy">
            <option selected>Choose...</option>
                <option value="Backend">Backend</option>
                <option value="Web-Design">Web Design</option>
                <option value="Frontend">Frontend Developer</option>
        </select>
            </div>
            <input type="button" value="Далее"  class="btn btn-primary"
            onclick="document.getElementById ('d1').style.display = 'none';
                     document.getElementById ('d2').style.display = 'block'">
        </div>
    <div id="d2" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="Какие языки программирования Вы используете?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck1" value="c#">
            <label class="custom-control-label" for=>C#</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck2" value="c++" >
            <label class="custom-control-label" for="CustomCheck2">C++</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck3" value="asp.net" >
            <label class="custom-control-label" for="CustomCheck3">ASP.NET</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck4" value="php" >
            <label class="custom-control-label" for="CustomCheck3">PHP</label><br>
        </div>
        <input type="button" value="Далее"  class="btn btn-primary"
                    onclick="document.getElementById ('d2').style.display = 'none';
                             document.getElementById ('d3').style.display = 'block'">
    </div><br>
    <div id="d3" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="С какими СУБД Вам приходилось работать?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck5" value="mssql">
            <label class="custom-control-label" for="CustomCheck5">MS-SQL Server 2000-2012/T-SQL</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck6" value="oracle" >
            <label class="custom-control-label" for="CustomCheck6">Oracle</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck7" value="mysql" >
            <label class="custom-control-label" for="CustomCheck7">MySQL</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck8" value="postgresql" >
            <label class="custom-control-label" for="CustomCheck8">PostgreSQL</label><br>
        </div>
        <input type="button" value="Далее"  class="btn btn-primary"
                    onclick="document.getElementById ('d3').style.display = 'none';
                             document.getElementById ('d4').style.display = 'block'">
    </div><br>
    <div id="d4" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="С какими системами контроля версий Вы работали?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck9" value="git">
            <label class="custom-control-label" for="CustomCheck9">GIT</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck10" value="cvs" >
            <label class="custom-control-label" for="CustomCheck10">CVS</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck11" value="subversion" >
            <label class="custom-control-label" for="CustomCheck11">Subverion</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck12" value="mercurial" >
            <label class="custom-control-label" for="CustomCheck12">Mercurial</label><br>
        </div>
        <input type="submit" value="Далее" class="btn btn-primary" onclick="convert_to_json(event)">
    </div><br>

    </form>
    <pre></pre>
</body>
<script>

function convert_to_json(event) {
    event.preventDefault();
    const checArr = arr => arr.filter(({
        checked
    }) => checked).map(({
        value
    }) => value);
    profile = {
         name: FirstName.value,
        lastname: LastName.value,
        city: City.value,
        phone: Phone.value,
        vacancy: Vacancy.value,
    };
    results = {
        Lang_list: checArr([CustomCheck1,
            CustomCheck2,
            CustomCheck3,
            CustomCheck4
        ]),
        SUBD_list: checArr([CustomCheck5,
            CustomCheck6,
            CustomCheck7,
            CustomCheck8
        ]),
        SystemControl_list: checArr([CustomCheck9,
            CustomCheck10,
            CustomCheck11,
            CustomCheck12
        ])
    };
    let json = JSON.stringify(results,"", 4);
    let json2 = JSON.stringify(profile, "", 4);

    document.querySelector("pre").innerHTML = "profile: " + json2 + "\nresults: " + json
}
</script>

</html>

Малик 13.02.2020 13:32

рони,
А как можно стилизовать строку которая появляется? например сделать переносы строки и пробелы?
У меня получается такая сплошная строка:




profile: { "name": "asdasd", "lastname": "asdasd", "city": "Oskemen", "phone": "+77779870000", "vacancy": "Frontend" }results: { "Lang_list": [ "asp.net" ], "SUBD_list": [ "oracle", "mysql", "postgresql" ], "SystemControl_list": [ "mercurial" ] }

рони 13.02.2020 13:47

Цитата:

Сообщение от Малик
например сделать переносы строки и пробелы?

смотрите код выше снова

Малик 17.02.2020 06:06

рони,
Доброго Вам Утра, хотел поинтересоваться, а как в данном коде, появляющайсе страке дать стилизацию? То есть добавить лейблов, дивов и т.д.
Заранее благолдарю за ответ!

рони 17.02.2020 07:51

Малик,
JSON.stringify заменить на свою функцию, читать про шаблонизатор и вывод данных из json.

Малик 18.02.2020 06:39

рони,
Про шаблонизатор я почитал, нно не могу понять по поводу функции и вывода данных, не можете немного направить?

рони 18.02.2020 10:19

Малик,
пишите как должен выглядеть результат html/css

Малик 18.02.2020 10:56

рони,
Нужно разместить результат по блокам с лейблами внутри них, первый блок с данными профиля(имя, фамилия и т.д.) Второй блок уже с результатами вопросов. Стилей конкретных к использованию от меня не требовали, все на свое усмотрение, главное чтобы не было обычной строкой, как до этого. Заранее благодарю за помощь.

рони 18.02.2020 12:15

опросник дерево из обьекта
 
Малик,
:-? ...
<!DOCTYPE html>
<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  ul.ar{
      display: flex;
      list-style: none;
  }
  ul.ar:before{
      content: "[";
  }
  ul.ar:after{
      content: "]";
  }
  ul.ar li{
      color: rgba(0, 0, 255, 1);
      margin: 3px;
  }

  ul.ar li:after {
      content: ",";
  }
  ul.ar li:last-child:after {
      content: ""
  }
  ul.obj{
       font-weight: bold;
  }
  ul.str{
      color: rgba(34, 139, 34, 1);
      list-style:  none;
  }
  ul.str li:before{
      content: open-quote;
      quotes: "\00ab" "\00bb";
      color: rgba(255, 69, 0, 1);
  }
  ul.str li:after{
      content: close-quote;
      quotes: "\00ab" "\00bb";
      color: rgba(255, 69, 0, 1);
  }
  </style>
</head>
<body>
    <form>
        <div class=" container row col-md-4 mt-4" id="d1">
            <div>
                <label>Имя</label>
        <input type="text" id="FirstName" class="form-control" placeholder="First name">
    <label>Фамилия</label>
        <input type="text" id="LastName" class="form-control" placeholder="Last name">
    <label>Город</label>
        <input type="text" id="City" class="form-control" placeholder="City">
    <label>Телефон</label>
        <input type="tel" id="Phone" class="form-control" placeholder="Number" >
    <label>Вакансия</label>
        <select class="form-control" id="Vacancy">
            <option selected>Choose...</option>
                <option value="Backend">Backend</option>
                <option value="Web-Design">Web Design</option>
                <option value="Frontend">Frontend Developer</option>
        </select>
            </div>
            <input type="button" value="Далее"  class="btn btn-primary"
            onclick="document.getElementById ('d1').style.display = 'none';
                     document.getElementById ('d2').style.display = 'block'">
        </div>
    <div id="d2" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="Какие языки программирования Вы используете?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck1" value="c#">
            <label class="custom-control-label" for=>C#</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck2" value="c++" >
            <label class="custom-control-label" for="CustomCheck2">C++</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck3" value="asp.net" >
            <label class="custom-control-label" for="CustomCheck3">ASP.NET</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck4" value="php" >
            <label class="custom-control-label" for="CustomCheck3">PHP</label><br>
        </div>
        <input type="button" value="Далее"  class="btn btn-primary"
                    onclick="document.getElementById ('d2').style.display = 'none';
                             document.getElementById ('d3').style.display = 'block'">
    </div><br>
    <div id="d3" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="С какими СУБД Вам приходилось работать?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck5" value="mssql">
            <label class="custom-control-label" for="CustomCheck5">MS-SQL Server 2000-2012/T-SQL</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck6" value="oracle" >
            <label class="custom-control-label" for="CustomCheck6">Oracle</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck7" value="mysql" >
            <label class="custom-control-label" for="CustomCheck7">MySQL</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck8" value="postgresql" >
            <label class="custom-control-label" for="CustomCheck8">PostgreSQL</label><br>
        </div>
        <input type="button" value="Далее"  class="btn btn-primary"
                    onclick="document.getElementById ('d3').style.display = 'none';
                             document.getElementById ('d4').style.display = 'block'">
    </div><br>
    <div id="d4" style="display: none;">
        <div class="form-5 form-group">
            <label for="Question" class="question">Вопрос:</label>
            <input type="text" class="form-control" id="validationTextarea" placeholder="С какими системами контроля версий Вы работали?"> </div>
        <div class="custom-control custom-checkbox form-control form-6">
            <input type="checkbox" class="custom-control-input" id="CustomCheck9" value="git">
            <label class="custom-control-label" for="CustomCheck9">GIT</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-7">
            <input type="checkbox" class="custom-control-input" id="CustomCheck10" value="cvs" >
            <label class="custom-control-label" for="CustomCheck10">CVS</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-8">
            <input type="checkbox" class="custom-control-input" id="CustomCheck11" value="subversion" >
            <label class="custom-control-label" for="CustomCheck11">Subverion</label>
        </div>
        <div class="custom-control custom-checkbox form-control form-9" >
            <input type="checkbox" class="custom-control-input" id="CustomCheck12" value="mercurial" >
            <label class="custom-control-label" for="CustomCheck12">Mercurial</label><br>
        </div>
        <input type="submit" value="Далее" class="btn btn-primary" onclick="convert_to_json(event)">
    </div><br>

    </form>
    <output></output>
</body>
<script>

function convert_to_json(event) {
    event.preventDefault();
    const checArr = arr => arr.filter(({
        checked
    }) => checked).map(({
        value
    }) => value);
    profile = {
         name: FirstName.value,
        lastname: LastName.value,
        city: City.value,
        phone: Phone.value,
        vacancy: Vacancy.value,
    };
    results = {
        Lang_list: checArr([CustomCheck1,
            CustomCheck2,
            CustomCheck3,
            CustomCheck4
        ]),
        SUBD_list: checArr([CustomCheck5,
            CustomCheck6,
            CustomCheck7,
            CustomCheck8
        ]),
        SystemControl_list: checArr([CustomCheck9,
            CustomCheck10,
            CustomCheck11,
            CustomCheck12
        ])
    };

   function recursiveList(data) {
    let newlist = document.createElement("ul"),
        item, children;
        newlist.className = "obj";
    if(Array.isArray(data)) {
       newlist.className = "ar";
       data.forEach(txt => {
       item = document.createElement("li");
       item.appendChild(document.createTextNode(txt));
       newlist.appendChild(item);
       })

    }
    else if(typeof data == "object") Object.keys(data).forEach(keys => {
    item = document.createElement("li");
    item.appendChild(document.createTextNode(keys));
    newlist.appendChild(item);
    children = recursiveList(data[keys]);
    item.appendChild(children)
    })
    else {
    newlist.className = "str";
    item = document.createElement("li");
    item.appendChild(document.createTextNode(data));
    newlist.appendChild(item);
    }
    return newlist
    };

    let json = recursiveList(results);
    let json2 = recursiveList(profile);

    document.querySelector("output").append(json, json2);
}
</script>

</html>

Малик 18.02.2020 12:59

рони,
Еще один вопрос, а как добавить стилизация ul и li, которые создаются? В скрипте отдельно прописывать что то? То есть, если быть конкретно, могу ли я обращаться к элементу li в css? И если да то как?

voraa 18.02.2020 13:19

В css написать классы для ul и li

.myul {
....
}

.myli {
...
}


после создания элементов, добавить им эти классы

let newlist = document.createElement("ul");
newlist.classList.add('myul');
.....
item = document.createElement("li");
item.classList.add('myli');

рони 18.02.2020 14:44

Цитата:

Сообщение от Малик
стилизация

смотрите пост #21 снова.


Часовой пояс GMT +3, время: 20:12.