Как программно создать несколько текстовых полей на странице? На странице окно со скролом, а внутри располагаются несколько текстовых полей (см. скрин) Имеем - Страница 1 (содержит: поле для ввода количества создаваемых полей, кнопка); - Страница 2 (содержит: окно в котором предполагается создать поля); Сценарий: - вводим количество полей, которое нужно создать; - нажимаем кнопку; - На "Странице 2" создаётся необходимое количество полей; Или может сделать на одной странице... Смотря как целесообразнее с позиции кода.. Если это влияет...
Целесообразней смотреть на задачу в целом: что, для чего, какие могут быть промежуточные этапы и какая конечная цель. Просто создать N-ное количество элементов, можно и на JS без каких-либо переходов и задействования серверной части.
Сейчас быстро сделаю аналог на js, подумал я, сделав php вариант. Час боли. Лови кучку, конечно же это просто анархия) Открываешь index.php, выбираешь сколько колонок создать, и галка - создать, используя js на текущей странице или на следующей странице, используя php. Файл forms у меня лежал в подпапке phpru. HTML: // index.php <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <title>First</title> <style> #wrap, .row { margin-top: 10px; } </style> </head> <body> <div id="wrap"> <div class="container"> <div class="row"> <form action="/phpru/forms.php" method="get" onsubmit="return drawTables(event)"> <select name="colsNum" id=""> <option disabled selected>Количество полей</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select><br> <p style="display: inline-block">Создать с помощью js</p><input id="checkbox" type="checkbox"><br> <button type="submit">Создать</button> </form> </div> </div> </div> <script> function drawTables(e) { console.log(e.target); let isChecked = document.getElementById('checkbox').checked; if(isChecked) { alert('Create with js'); let selectElem = document.getElementsByTagName('select')[0]; let colsNum = selectElem.options[selectElem.selectedIndex].value; let row = document.createElement('div'); row.className = "row"; let bstrpCols = 12 / colsNum; let htmlLayout = ""; for(let i = 0; i < colsNum; i++) { htmlLayout += ` <div class="col-sm-${bstrpCols}"> <table border="1" width="100%" cellpadding="6"> <tr> <td>Dog</td> <td>Cat</td> </tr> <tr> <td>Banana</td> <td>Orange</td> </tr> <tr> <td>Cucumber</td> <td>Potato</td> </tr> <tr> <td>...</td> <td>...</td> </tr> </table> </div> `; } row.insertAdjacentHTML( 'beforeend', htmlLayout); document.getElementsByClassName('container')[0].appendChild(row); return false; } else { alert('Create with php'); } } </script> </body> </html> HTML: <?php if(empty($_GET['colsNum'])) die("Number of columns wasn't specified"); $colsNum = $_GET['colsNum']; $bstrpCols = 12 / $colsNum; ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <title>Forms</title> <style> #wrap, .row { margin-top: 10px; } </style> </head> <body> <div id="wrap"> <div class="container"> <div class="row"> <?php for($i=0;$i<$colsNum;$i++): ?> <div class="col-sm-<?=$bstrpCols?>"> <table border="1" width="100%" cellpadding="6"> <tr> <td>Dog</td> <td>Cat</td> </tr> <tr> <td>Banana</td> <td>Orange</td> </tr> <tr> <td>Cucumber</td> <td>Potato</td> </tr> <tr> <td>...</td> <td>...</td> </tr> </table> </div> <?php endfor; ?> </div> </div> </div> </body> </html>
Да. Просто создать N-ное количество элементов. Мне нужна следующая "конструкция" на странице: - окно со скролом; - внутри окна поля; - поля будут с текстовым редактором; - поля будут получать/отправлять текст в(из) базу данных - по средствам кнопки; или - автоматически; см. Гиф Кнопка может располагаться как на этой же странице или на отдельной странице. Хотя я могу быть некорректен в постановке задачи и это можно решить более рациональнее... Буду признателен, если поправите меняююю @виталий032 У меня создаются таблицы.... Или я что-то не правильно делаю? А хотелось бы - см. Гиф
Тогда, просто создадим Код (Javascript): const inputNum = document.querySelector('input'), output = document.querySelector('output'), template = `<div> <label></label> <textarea name="key[]"></textarea> <button>Save</button> </div>`; document.getElementById('generate').addEventListener('click', () => { output.innerHTML = template.repeat(+inputNum.value) });
Спасибо... Практически то, что надо.... 1. Не могли бы вы ещё сделать следующее: - textarea располагаются в одну линию; - "массив" textarea располагаются внутри специального окна со скролом (см. скрин "01.jpg", см. гиф "01.gif"); 2. Как эти два кода связать? Т.е. в файлах с каким расширением размещать?
Для родительского элемента, в который будете выводить textarea, добавьте CSS-свойства: Код (CSS): /* width или max-width с фиксированной шириной */ width: 200px; /* значение - определяете сами*/ white-space: nowrap; overflow-x: auto; /* auto или hidden */ overflow-y: hidden; /* опционально*/ Обычно - это .html
Прошу прощения за настойчивость, но опять почти "то", но "не то"... см. скрин. Скрин с результатом по ссылке - http://prntscr.com/j0o5vz Сделал один файл "index1.html". Код файла "index1.html" Код (Text): <head> <style> div { /* width или max-width с фиксированной шириной */ width: 200px; /* значение - определяете сами*/ white-space: nowrap; overflow-x: auto; /* auto или hidden */ overflow-y: hidden; /* опционально*/ } </style> </head> <input type="number" min="0" value="5"> <button id="generate">Go</button> <output></output> <script type="text/javascript"> { const inputNum = document.querySelector('input'), output = document.querySelector('output'), template = `<div> <label></label> <textarea name="key[]"></textarea> <button>Save</button> </div>`; document.getElementById('generate').addEventListener('click', () => { output.innerHTML = template.repeat(+inputNum.value) }); } </script> Буду признателен, если посоветуйте, как правильнее оформить код... Как всё таки привести к виду который продемонстрирован на gif? " 01.gif "
Сделал. Не подходит Получается скролл для каждого текстового поля... Код (Text): <head> <style> div { /* width или max-width с фиксированной шириной */ width: 200px; /* значение - определяете сами*/ white-space: nowrap; overflow-x: auto; /* auto или hidden */ overflow-y: hidden; /* опционально*/ display: inline-block; } </style> </head> <input type="number" min="0" value="5"> <button id="generate">Go</button> <output></output> <script type="text/javascript"> { const inputNum = document.querySelector('input'), output = document.querySelector('output'), template = `<div> <label></label> <textarea name="key[]"></textarea> <button>Save</button> </div>`; document.getElementById('generate').addEventListener('click', () => { output.innerHTML = template.repeat(+inputNum.value) }); } </script>
Штук 8 textarea добавьте, чтобы видно было скролл по горизонтали HTML: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> output { display: block; width: 800px; /* значение - определяете сами*/ margin-top: 30px; white-space: nowrap; overflow-x: auto; /* auto или hidden */ overflow-y: hidden; /* опционально*/ } output div { display: inline-block; margin-right: 20px; } </style> </head> <body> <input type="number" min="0" value="5"> <button id="generate">Go</button> <output></output> <script type="text/javascript"> { const inputNum = document.querySelector('input'), output = document.querySelector('output'), template = `<div> <label></label> <textarea name="key[]"></textarea><br> <button>Save</button> </div>`; document.getElementById('generate').addEventListener('click', () => { output.innerHTML = template.repeat(+inputNum.value) }); } </script> </body> </html> [Updated] Добавьте стиль: Код (CSS): output:not(:empty) { border: 1px solid green; }
@виталий032 Вроде то, что нужно... Буду испытывать пока... Можно ещё сделать, чтобы отображалась граница окна где располагаются текстовые поля? А то она сливается с фоном страницы.. см. скрин
@виталий032 Пост #13 сделал.. Добавил "output" добавил "outline: 2px solid #F3B53F;" Результат... Код (Text): output { display: block; width: 800px; /* значение - определяете сами*/ margin-top: 30px; white-space: nowrap; overflow-x: auto; /* auto или hidden */ overflow-y: hidden; /* опционально*/ outline: 2px solid #F3B53F; } Нормально? Или можно по другому? Может есть особенности?
А можно как-то для "output" изменить ширину или полностью размеры мышкой на странице? Т.е. изменить размер путём перетаскивания границ...
@inkom Самое простое, это добавить стиль: Код (CSS): output { resize: horizontal; } И ресайзить блок за квадратик в правом нижнем углу. Если нужна красота, то в инете есть готовые решения. Например, jquery ui.