Введите текст в sweetAlert

Я использую пользовательскую версию sweetalert, чтобы запрашивать у пользователя input. Мне удалось заставить все работать, но есть странное поведение. Чтобы иметь возможность ввести текст в поле ввода, вы должны сначала щелкнуть экран:

swal({
    title: "Aggiornamento profilo",
    text: '<br /><form method="post" id="taxcode-update" name="taxcodeUpdate"><input id="admin-tax-code" minlength="3" class="form-control wedding-input-text wizard-input-pad" type="text" name="taxCode" placeholder="Codice fiscale"></form>',
    type: "warning",
    showCancelButton: false,
    confirmButtonText: "Aggiorna il mio profilo",
    closeOnConfirm: false
}, function () {
    swal("Deleted!", "Your imaginary file has been deleted.", "success");
});

Рабочий пример: https://jsfiddle.net/fvkppx06/


person DomingoSL    schedule 28.04.2015    source источник


Ответы (6)


Используйте Sweetalert2. Существует множество примеров запросов на ввод, которые можно найти здесь, все они используют современные методы async/await. конструкции. Если вы хотите по-старому, попробуйте следующее:

Swal.fire({
    title: "An input!",
    text: "Write something interesting:",
    input: 'text',
    showCancelButton: true        
}).then((result) => {
    if (result.value) {
        console.log("Result: " + result.value);
    }
});
person John Silence    schedule 29.04.2019

JSFiddle

Дайте input тег autofocus.

text: '<br /><form method="post" id="taxcode-update" name="taxcodeUpdate">'
    + '<input id="admin-tax-code" autofocus minlength="3" class="form-control wedding-input-text wizard-input-pad" type="text" name="taxCode" placeholder="Codice fiscale">'
    + '</form>',
person Albzi    schedule 28.04.2015
comment
Это решение будет работать только при первом вызове модального окна. Взгляните на эту модификацию, которую я сделал, чтобы продемонстрировать, что jsfiddle .net/fvkppx06/2 есть идеи? - person DomingoSL; 28.04.2015
comment
Я не знаю, извините! Хотя новейшая версия Sweet Alert допускает type:input, что может работать лучше? @ДомингоСЛ - person Albzi; 28.04.2015

Используемая переменная — «имя».

 const {value: name} = await swal({
  title: 'Input your name',
  input: 'text',
  inputPlaceholder: 'Enter here'
})

if (name) {
  swal('Entered name: ' + name)
}
person Mikeys4u    schedule 12.10.2018
comment
Обновленная версия находится здесь codehaven.co.uk/jquery/jquery-ajax/ - person Mikeys4u; 30.10.2020

Просто проверьте это

swal.withForm({
   title: 'Cool example',
   text: 'Any text that you consider useful for the form',
   showCancelButton: true,
   confirmButtonColor: '#DD6B55',
   confirmButtonText: 'Get form data!',
   closeOnConfirm: true,
   formFields: [
       { id: 'name', placeholder:'Name Field' },
       { id: 'nickname', placeholder:'Add a cool nickname' }
   ], function(isConfirm) {
   // do whatever you want with the form data
   console.log(this.swalForm); // { name: 'user name', nickname: 'what the user sends' }
})

https://github.com/taromero/swal-forms

person narsis fe    schedule 17.06.2015

Использовать это :

Swal.fire({
title: "An input!",
text: "Write something interesting:",
input: 'text',
showCancelButton: true ,
confirmButtonColor: 'green'
}).then((result) => {
if (result.value) {
    Swal.fire('Result:'+result.value);
}});
person Sasi    schedule 21.08.2019

person    schedule
comment
Потому что вы используете старую версию сладкого оповещения. У меня было то же самое, и я решил это, обновив библиотеку сладких предупреждений отсюда. lipis.github.io/bootstrap-sweetalert - person Mukesh Salaria; 05.11.2018