2017-02-19 2 views
0

У меня есть форма, которая показывает дополнительные поля, если пользователь выбирает «да» из выбранного ввода. Эти дополнительные поля необходимы, если пользователь не выбирает «нет», и в этом случае поля скрыты, а необходимый атрибут удаляется. Он работает, однако я столкнулся с проблемой, когда пользователь выбирает «да», а затем возвращается к «нет», тогда форма не будет отправляться, по-видимому, потому, что она не удаляет требуемый атрибут и все еще ожидает, что поля чтобы быть заполненным. Если кто-то может помочь исправить это, мы будем очень признательны.HTML JavaScript - Проблемы с формой с дополнительными/необязательными полями

HTML:

<form id="auth_form" method="post" action="action.php"> 

    <div class="form-group"> 
    <label class="control-label">Defect?</label> 
    <select class="select form-control" id="defect" name="defect"> 
     <option id="No" value="No">No</option> 
     <option id="Yes" value="Yes">Yes</option> 
    </select> 
    </div> 

    <div id="extra" name="extra" style="display: none"> 

    <label class="control-label" for="desc">Description</label> 
    <input class="form-control" type="text" id="desc" name="desc" required disabled> 
    <br> 
    <div class="form-group has-feedback" name="auth_code" id="auth_code"> 
     <label for="auth_code10" class="control-label"> 
     Authorisation Code</label> 
     <input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required disabled> 
     <span class="form-control-feedback glyphicon" id="iconBad"></span> 
    </div> 

    </div> 

    <hr> 

    <div class="form-group"> 
    <button class="btn btn-info" id="submit" name="submit" type="submit">Submit 
    </button> 
    </div> 

</form> 

JavaScript:

$(document).ready(function() { 

    $("#defect").on("change", checkIfYes); 

    // Functions 

    function checkIfYes() { 
    if (document.getElementById('defect').value == 'Yes') { 

     // show extra fields & make them required 
     document.getElementById('extra').style.display = ''; 
     document.getElementById('auth_code_input').disabled = false; 
     document.getElementById('desc').disabled = false; 

     $('#auth_code_input').blur(function() { // validate the extra fields 
     if (!ValidateInput()) { 
      e.preventDefault(); 
     } 
     }); 

     $('#auth_form').on('submit', function(e) { // validate the extra fields 
     if (!ValidateInput()) { 
      e.preventDefault(); 
     } 
     }) 

    } else { // hide and disable extra fields so form can submit 
     document.getElementById('extra').style.display = 'none'; 
     document.getElementById('auth_code_input').disabled = true; 
     document.getElementById('desc').disabled = true; 
    } 

    } 

    function ValidateInput() { 
    var code = ['Foo', 'Bar']; // user must enter one of these 
    var IsValid = false; 
    var input = $('#auth_code_input').val() 

    if (code.indexOf(input) > -1) { // if input equals one of the codes in the array 
     $('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok'); 
     IsValid = true; 
    } else { 
     $('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove'); 
     IsValid = false; 
    } 

    return IsValid; 
    } 

}); 

JSFiddle

ответ

2

Ваша проблема здесь:

if (document.getElementById('defect').value == 'Yes') { 
//..... 
    $('#auth_form').on('submit', function(e) { // validate the extra fields 
    if (!ValidateInput()) { 
     e.preventDefault(); 
    } 
    }) 

, если пользователь нажмет да#auth_form привязывается к функции, которая препятствует отправке. Но после нажатия на NO нет способа изменить его обратно.

if (document.getElementById('defect').value == 'No') { 
    $('#auth_form').off('submit'); 
}); 
+0

Отлично, спасибо. – sinesine

+0

Вы приветствуете моего друга. –

Смежные вопросы