Изменить требуемый статус поля в соответствии с выбором переключателя

Дело обстоит так: у меня есть 2 переключателя, которые показывают/скрывают 2 других блока кода через javascript при выборе. HTML-код, который показывает/скрывает, содержит другие обязательные поля. Поэтому я просто скрываю их с помощью display:none в соответствии с выбором переключателя. В любом случае, в этом случае моя форма не может быть запущена, потому что я должен заполнить обязательные поля, которые в любом случае скрыты от пользователя в соответствии с выбором переключателей. Итак, что мне нужно, так это удалить/добавить «требуемое» состояние, обратное выбору радио.

Как я мог это сделать?

<form action="./assets/php/sendmail.php" class="form common_font" method="post">
    <div class="choosecontact">
        <input type="radio" id="radio01" name="radio" value="telefonopref" required />
        <label for="radio01"><span></span>Contattatemi per <b>telefono</b></label>
        <br>
        <input type="radio" id="radio02" name="radio" value="emailpref" />
        <label for="radio02"><span></span>Contattatemi per <b>e-mail</b></label>
    </div>

    <div id="telefonopref">
        <label class="selectcustom">
            <select class="dropdown" required>
                <option value="saab">Chiamatemi tra 8.30 - 12.30</option>
                <option value="vw">Chiamatemi tra 14.30 - 18.30</option>
            </select>
        </label>

        <div class="field inline-block name">
            <label for="input_text" class="field-label common_font regular medium_font_size form_color">Numero di telefono</label>
            <input id="input_text" name="TEXT" class="field-input" type="text" required>
        </div>
    </div>

    <div id="emailpref" class="field inline-block email">
        <label for="input_email" class="field-label common_font regular medium_font_size form_color">Indirizzo Email (consiglio: email personale che controlli)</label>
        <input id="input_email" name="EMAIL" class="field-input" type="EMAIL" required>
    </div>


    <div id="otherformpart">
        <div class="field msg">
            <label for="input_msg" class="field-label common_font regular medium_font_size form_color">Vuoi aggiungere qualcosa? Scrivilo qui.</label>
            <input id="input_msg" name="TEXT" class="field-input" type="text">
        </div>

        <div class="inline-block row">
            <div class="col-xs-2">
                <input id="input_privacycheck" name="PRIVACYCHECK" class="privacycheck" type="checkbox" required>
            </div>
            <div class="col-xs-10">
                <label for="input_checkprivacy" class="privacyconsent">Acconsento al trattamento dei dati personali come indicato nella Privacy Policy ai fini di questo servizio.</label>
            </div>
        </div>

        <button type="submit" class="send-btn center common_element_color common_font medium body_font_size white"><span class="fa fa-chevron-right"></span> Invia richiesta</button>
    </div>
</form>

И это мой javascript для отображения/скрытия частей HTML в соответствии с выбором кнопки readio:

$('input[type=radio][name=radio]').change(function () {
    $('#emailpref').css("display","none");
    $('#telefonopref').css("display","none");
    console.log($(this).val());
    var fieldToShow = $(this).val();
    $("#" + fieldToShow).css("display","block");
});

$('input[type=radio][name=radio]').change(function () {
    $('#otherformpart').css("display","none");
    console.log($(this).val());
    var fieldToShow = $(this).val();
    $("#otherformpart").css("display","block");
});

person Francesco    schedule 27.07.2017    source источник


Ответы (2)


Вы можете удалить требуемый атрибут с помощью функции removeAttr. Но на всякий случай лучше отключить пропс.

попробуйте ниже.

$('input[type=radio][name=radio]').change(function () {
   $('#emailpref').css("display","none").removeAttr('required').prop('required', false );

    $('#telefonopref').css("display","none");
    console.log($(this).val());
    var fieldToShow = $(this).val();
    $("#" + fieldToShow).css("display","block").css("display","block").attr('required', 'true').prop('required', true);
});

$('input[type=radio][name=radio]').change(function () {   
  
  $('#otherformpart').css("display","none").removeAttr('required').prop('required', false);
    console.log($(this).val());
    var fieldToShow = $(this).val();
    $("#otherformpart").css("display","block").attr('required', 'true').prop('required', true);
});

person serdar.sanri    schedule 27.07.2017
comment
Не могли бы вы также добавить объяснение, чтобы предотвратить программирование карго-культа? - person Kevin; 27.07.2017
comment
Это было довольно понятно, и вопрос был очевиден, поэтому я не думал, что пара предложений вверху this is how you do it необходима. Но обновил ответ. - person serdar.sanri; 27.07.2017

Я решил себя таким образом. Небольшое редактирование HTML-кода и новый скрипт.

HTML-код:

<form action="./assets/php/sendmail.php" class="form common_font" method="post">
    <div class="choosecontact">
        <input type="radio" id="radiotel" name="radio" value="telefonopref" required />
        <label for="radiotel"><span></span>Contattatemi per <b>telefono</b></label>
        <br>
        <input type="radio" id="radioemail" name="radio" value="emailpref" />
        <label for="radioemail"><span></span>Contattatemi per <b>e-mail</b></label>
    </div>

    <div id="telefonopref">
        <label class="selectcustom">
            <select id="orariotel" class="dropdown" required>
                <option value="saab">Chiamatemi tra 8.30 - 12.30</option>
                <option value="vw">Chiamatemi tra 14.30 - 18.30</option>
            </select>
        </label>

        <div class="field inline-block name">
            <label for="input_tel" class="field-label common_font regular medium_font_size form_color">Numero di telefono</label>
            <input id="input_tel" name="TEXT" class="field-input" type="text">
        </div>
    </div>

    <div id="emailpref" class="field inline-block email">
        <label for="input_email" class="field-label common_font regular medium_font_size form_color">Indirizzo Email (consiglio: email personale che controlli)</label>
        <input id="input_email" name="EMAIL" class="field-input" type="EMAIL" required>
    </div>


    <div id="otherformpart">
        <div class="field msg">
            <label for="input_msg" class="field-label common_font regular medium_font_size form_color">Vuoi aggiungere qualcosa? Scrivilo qui.</label>
            <input id="input_msg" name="TEXT" class="field-input" type="text">
        </div>

        <div class="inline-block row">
            <div class="col-xs-2">
                <input id="input_privacycheck" name="PRIVACYCHECK" class="privacycheck" type="checkbox" required>
            </div>
            <div class="col-xs-10">
                <label for="input_checkprivacy" class="privacyconsent">Acconsento al trattamento dei dati personali come indicato nella Privacy Policy ai fini di questo servizio.</label>
            </div>
        </div>

        <button type="submit" class="send-btn center common_element_color common_font medium body_font_size white"><span class="fa fa-chevron-right"></span> Invia richiesta</button>
    </div>
</form>

JS-код:

/*---------------------------
    required/not required according to radio selection
----------------------------*/
$('#radiotel').change(function () {
    if(this.checked) {
        $('#input_email').prop('required', false);
        $('#input_tel').prop('required', true);
        $('#orariotel').prop('required', true);
        } else {
        $('#input_email').prop('required', true);
        $('#input_tel').prop('required', false);
        $('#orariotel').prop('required', false);
    }
});

$('#radioemail').change(function () {
    if(this.checked) {
        $('#input_email').prop('required', true);
        $('#input_tel').prop('required', false);
        $('#orariotel').prop('required', false);
        } else {
        $('#input_email').prop('required', false);
        $('#input_tel').prop('required', true);
        $('#orariotel').prop('required', true);
    }
});
person Francesco    schedule 28.07.2017