Избавится от ID в поле input
Добрый день!
Есть такая форма: https://jsfiddle.net/m6vxq34u/20/ Когда прикрепляешь файл, то JS выводит имя файла + его размер. С первым файлом все ок, отрабатывает как нужно, но у второго ID тот же что и у первого и по этому не отрабатывает. Как переписать, что бы не привязываться к ID input!? Спасибо! |
Что-то не видно нескольких полей. Можно и по имени, только нужно экранировать:
$('body').on('change', 'input[name="files\\[\\]"]', ....
|
Нажмите "Добавить еще файл" появится еще одно поле!
Обновил ссылку: https://jsfiddle.net/m6vxq34u/20/ |
Цитата:
Ну в общем по имени можно как написано, можно и по классу, если добавить его, обработка делегируется. ID удалить. |
Если бы я был на столько силен в знаниях JS как вы!
Поможете в решение задачи? Можно прям там и ссылку сюда, или тут показать, как поправить. Спасибо! |
ID my-file-name заменены на классы (в стилях также изменить). Обработка делегируется ближайшему родителю div class="row", которому добавлен ID files-group. В этом случае, коли полей в форме иных нет, достаточно имя тега в качестве селектора.
<div class="application-project">
<div class="container">
<div class="row" id="files-group">
<div class="col-md-6 form-group">
<div class="file-upload">
<label>
<div class="form-file-box">
<span class="status">Выберите файл</span>
</div>
<input type="file" name="files[]" value="" />
</label>
<div class="my-file-name"></div>
<div class="my-file-size"></div>
</div>
</div>
<div class="col-lg-12 form-group">
<div class="button-file"><span><i class="fa fa-plus" aria-hidden="true"></i> Добавить еще файл</span>
</div>
</div>
</div>
</div>
</body>
$(document).ready(function () {
// Добавить еще один файл
$('.button-file').on('click', function() {
$(this).closest('.row')
.children()
.first()
.clone()
.insertBefore($(this).parent())
.find('input')
.val('')
.end()
.find('[class|=my]')
.text('');
});
// Загрузка файла
$('#files-group').on('change', 'input', function(){
var f = $(this), file, fileSize;
if (!f.val()) {
f.prev().addClass('disabled');
f.prev().find('.status').text('Файл выбран');
return;
}
file = this.files[0];
fileSize = file.size > 1024 * 1024 ? Math.round(file.size * 100 / (1024 * 1024)) / 100 + 'MB'
: Math.round(file.size * 100 / 1024) / 100 + 'KB';
f.closest('.file-upload')
.find('[class|=my]')
.first()
.text('Имя: ' + file.name)
.end()
.last()
.text('Размер: ' + fileSize);
});
});
Если это форма и есть другие поля ее, то добавьте полю file класс, который использовать как селектор, здесь:
$('#files-group').on('change', '.имя_класса_поля_выбора_файла', function(){
Примечание: чего этим хочется добиться if (!f.val()) .... 'Файл выбран' не понятно, но такое проверяется не здесь. |
Вот это круто ))) То, что доктор прописал!
|
Цитата:
То есть события onchange не возникнет и проверка if (!f.val()) в обработчике этого события мягко говоря бред. |
Скажите, я могу вместо этого куска
// Добавить еще один файл
$('.button-file').on('click', function() {
$(this).closest('.row').children().first().clone().insertBefore($(this).parent()).find('input').val('').end().find('[class|=my]').text('');
});
Свой старый использовать? Я понимаю, что это более красивое решение, но он копирует все + новые классы. т.е. у меня есть украшательство: Когда выбрали файл, он меняет статус лейбла и пишет, что файл выбран
// Форма обратной связи | Статус файла
$('body').on('change', 'input[name="files[]"]', function(){
if ($(this).val() != '') {
$(this).prev().addClass('disabled');
$(this).prev().find('.status').html('Файл выбран');
}
});
Проще, вот временная ссылка на работу: https://svetliygrad.ru/res Выберите файл, посмотрите как изменится кнопка, потом добавьте еще поле, что бы прикрепить файл |
RGBPlus,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">.application-project {
background: #ececec;
margin: 3rem auto;
display: block;
width: 800px;
padding: 3rem 2rem;
}
.application-project .h4 {
font: 600 16px/16px Helvetica,Arial,sans-serif;
color: #2C3E50;
margin: 2rem 0 1rem 0;
}
.application-project .h4.form-title {
color: #16A085;
padding: 0 0 1.3rem 0;
border-bottom: 1px solid #16A085;
}
.application-project label {
display: block;
font: 300 16px/16px pragmatica,Helvetica,Arial,sans-serif;
padding: 0;
margin: 0.8rem 0;
}
.application-project label span.sure,
.form-information span.sure {
color: #C0392B;
}
.application-project .select,
.application-project .select-tags {
width: 100%;
}
.application-project .select2-selection {
border: 1px solid #c3d3e4;
box-shadow: 0 1px 1px 1px #ececec inset;
border-radius: 4px;
font: 300 15px/15px pragmatica,Helvetica, Arial, sans-serif;
height: 35px;
padding: 0.4rem 0 0 0.3rem;
}
.application-project .select2-selection .select2-selection__arrow b {
border-color: #2C3E50 transparent transparent transparent;
margin-left: -9px;
margin-top: 1px;
}
.application-project input,
.application-project textarea {
font: 300 15px/15px pragmatica, Helvetica, Arial, sans-serif;
border: 1px solid #c3d3e4;
border-radius: 5px;
margin: 0;
box-shadow: 0 1px 1px 1px #ececec inset;
width: 100% !important;
}
.application-project input {
height: 33px;
padding: 0 1rem;
}
.application-project textarea {
padding: 1rem;
}
.application-project .button-file span {
color: #16A085;
font: 600 16px/16px Helvetica,Arial,sans-serif;
display: inline-block;
cursor: pointer;
padding: 0.2rem 0;
border-bottom: 1px dashed;
margin: 1rem 0;
}
.application-project .button-file span i {
font-weight: normal;
font-size: 15px;
color: #2C3E50;
}
.application-project .file-upload {
position: relative;
overflow: hidden;
width: 100%;
height: 65px;
}
.application-project .file-upload label {
display: block;
position: absolute;
top: 0;
left: 0;
margin: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
.application-project .file-upload label .form-file-box {
background: #16A085;
color: #fff;
cursor: pointer;
text-transform: uppercase;
padding: 0.7rem 0 0.5rem 0;
font: 300 14px/14px pragmatica,Helvetica,Arial,sans-serif;
width: 100%;
text-align: center;
}
.application-project .file-upload label .form-file-box:hover,
.application-project .file-upload label .form-file-box.disabled {
background: #1ABC9C;
}
.application-project .file-upload label .form-file-box.disabled {
cursor: not-allowed;
}
.application-project .file-upload input[type="file"] {
display: none;
}
.application-project .my-file-name {
margin: 2.2rem 0 0 0;
}
.application-project .my-file-name,
.application-project .my-file-size {
font: 300 11px/13px pragmatica, Helvetica, Arial, sans-serif;
padding: 0.2rem 0 0 0;
}
.form-group {
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
function d(a) {
return a.on("change", 'input[name="files[]"]', function() {
a.addClass("disabled");
$(".status", a).text("Файл выбран");
var c = this.files[0],
b = 1048576 < c.size ? Math.round(100 * c.size / 1048576) / 100 + "MB" : Math.round(100 * c.size / 1024) / 100 + "KB";
$(".my-file-name", a).text("Имя: " + c.name);
$(".my-file-size", a).text("Размер: " + b)
})
}
var b = $(".col-md-6.form-group");
b = d(b).clone();
$(".button-file").on("click", function() {
$(".col-md-6.form-group:last").after(d(b.clone()))
})
});
</script>
</head>
<body>
<div class="application-project">
<div class="container">
<div class="row">
<div class="col-md-6 form-group">
<div class="file-upload">
<label>
<div class="form-file-box">
<span class="status">Выберите файл</span>
</div>
<input type="file" name="files[]" value="" />
</label>
<div class="my-file-name"></div>
<div class="my-file-size"></div>
</div>
</div>
<div class="col-lg-12 form-group">
<div class="button-file"><span><i class="fa fa-plus" aria-hidden="true"></i> Добавить еще файл</span>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|
| Часовой пояс GMT +3, время: 00:32. |