Задать вопрос

Как добавить скрытый input в форму через js?

Здравствуйте. Помогите пож-та добавить скрытый input c параметром data-otkuda в форму через js. Есть html копки, по клику на неё через js формируется форма. Так вот в эту форму и нужно добавить скрытый input. Не очень силен в js, поэтому прошу помощи.
<a href="javascript:void(0)" class="btn btn-turq d-md-inline-block d-none popUpForm" data-title="Закажите звонок" data-fields="name,phone" data-bform="И наш менеджер перезвонит Вам в ближайшее время" data-button="Заказать звонок" data-otkuda="Заявка на заказ обратного звонка">Заказать звонок</a>

и js
$(document).on('submit', '.normalForm', function (e) {
	

	e.preventDefault();
	var title = $(this).data('title');
	var form = $(this);

	var phone = form.find('input[name=phone]').val();
	if (!phone) {
		alert('Укажите Ваш телефон');
		form.find('input[name=phone]').focus();
	   // animate(form);
		return false;
	}
	var formData = new FormData(form[0]);
	$(form).find('input[type=file]').each(function () {
		formData.append(this.name, this.value);
	});
	
	$.ajax({
		url: '/sendMail.php?title=' + title,
		type: 'post',
		enctype: 'multipart/form-data',
		data: formData,
		processData: false,
		contentType: false,
		success: function (data) {
			form.trigger('reset');
			successForm();
			/*$('.modal').modal('hide');
			 $.fancybox.close();
			 form.trigger('reset');*/
		}
	});


});
$('.popUpForm').click(function (e) {
        e.preventDefault();
		
        printForm($(this));
    });
function initPhone(){
	var _container = jQuery('input[name=phone]');
	if (_container.length > 0) {
_container.each(function () {
			var _t = jQuery(this);
			var _this_form = _t.parents('form');
			
			 _t.inputmask("+7(999) 999-99-99",{
					completed:function(){
						setValue($(this));
							$(this).parents('form').find('input[type=submit]').removeClass('disabled_phone'); 
							$(this).parents('form').find('button[type=submit]').removeClass('disabled_phone');
							$(this).parents('form').removeClass('disabled_phone');
							if($(this).parents('div').hasClass("wrap-form-bottom")){
								$(this).parents('div').find('#sendInform').removeClass('disabled_phone'); 
							}
							if($(this).parents('div').hasClass("form-calc-ceny_form")){
								$(this).parents('div').find('.sendCalk').removeClass('disabled_phone'); 
							}
							$(this).removeClass('disabled_phone');
						},
					"onincomplete": function(){
						$(this).parents('form').find('input[type=submit]').addClass('disabled_phone');
						$(this).parents('form').find('button[type=submit]').addClass('disabled_phone');
						$(this).parents('form').addClass('disabled_phone');
					
						if($(this).parents('div').hasClass("wrap-form-bottom")){
							$(this).parents('div').find('#sendInform').addClass('disabled_phone');
						}
						if($(this).parents('div').hasClass("form-calc-ceny_form")){
							$(this).parents('div').find('.sendCalk').addClass('disabled_phone');
						}
						$(this).addClass('disabled_phone');
					
					
					
						var typs = _this_form.attr('id');
					
						var dop_phone = $(this).val();
					
					},
					onKeyDown: function () {
						var value = $(this).val();
						var maskedValue = value.replace(/\D+/g, "");
						if(maskedValue.length<3){
							$(this).data('city', false);
						}
					
					}
					});
		
		});
    	
	}
}
function fancyForm(title, html) {
    var msg = '<div class="lightbox__form"><div class="lightbox__form-in">\
						<div class="lightbox__form-title-top"><div class="lightbox__header">' + title + '</div></div>\
						<div class="inp_wrap">'+html+'</div>\
						<div id="popup_error"></div>\
						</div></div>';
    if (!!$.prototype.fancybox) {
        $.fancybox.open(msg);
        initPhone();
    }
}

const Form = {
   /* name: '<div class="input__field"><input type="text" placeholder="Ваше имя" name="name"></div>',*/
    phone: '<div class="input__field"><input type="text"   autocomplete="off"  inputmode="numeric" name="phone" required placeholder="Ваш телефон" /></div>',
    comment: '<div class="input__field"><textarea name="comment" required placeholder="Ваш комментарий"></textarea></div>',
    time: '<div class="input__field"><select name="time"><option  value disabled selected>Когда Вам перезвонить?</option><option value="9-12 часов">9-12 часов</option><option value="12-17 часов">12-17 часов</option><option value="17-20 часов">17-20 часов</option></select></div>',
    date: '<div class="input__field"><input name="date" type="date"></div>',
    agreement: '<div class="form-label-ligtbox"><label class="form-agreement-yes d-flex justify-content-center align-items-center"><input class="agreement-yes-input" name="is_allowed_personal" checked="checked" value="1" type="checkbox"><span class="agreement-yes-custom"><img src="/templates/nova/images/check.svg"></span><span class="agreement-yes-text">Соглашаюсь с <a href="/privacy.html" target="_blank">условиями</a> обработки персональных данных</span></label></div>'
};



function printForm(_form) {
    const buttton_title = $(_form).data('button') || 'Отправить';
    const title = $(_form).data('title') || 'Заказать звонок';
	const custom = $(_form).data('custom') || false;
    const filedsData = $(_form).data('fields');
	
	
	const beforeForm = $(_form).data('bform') ? '<div class="beforeForm">'+$(_form).data('bform')+'</div>' : '';
	const afterForm = $(_form).data('aform') ? '<div class="afterForm">'+$(_form).data('aform')+'</div>' : '';
	
	
	
      let html = '<form class="normalForm" data-title="'+title+'">'+beforeForm;

    html += filedsData.split(',').map(function (i) {
        return  Form[i];
    }).join('');

    html += Form['agreement'];
    html += '<div class="text-center"><button type="submit" class="btn btn-yellow d-inline-block btn-x-20"><span>'+ buttton_title +'</span></button></div>';
    html += afterForm+'</form>';
	if(custom){
		fancyForm(custom, html);
	}else{
		fancyForm(title, html);
	}
   
	const callback = $(_form).data('callback') || false;;
	if(callback){
		
		if (typeof window[callback] === 'function') {
			setTimeout(function(){
				window[callback].call()
				console.log(callback)
			}, 100);
			
		}
	}
}
  • Вопрос задан
  • 87 просмотров
Подписаться 1 Средний 9 комментариев
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы