Symfony 4如何使用jQuery向树枝添加属性?

时间:2019-03-14 14:06:58

标签: twig symfony4

我正在尝试用symfony 4制作表格。它工作正常。但是我有一个问题。 我有一个领域要写评论。默认情况下,它不是必需的。 但是,我想使用jquery更改它。 这就是我试图做的。

这是我的树枝:

 <div class="information" id="informationForm">

        {{ form_row(recordForm.category) }}
        {{ form_row(recordForm.information) }}


        {{ form_label(recordForm.comment) }}
        {{ form_widget(recordForm.comment, {'attr': {'class': 'comment'}}) }}
        {{ form_errors(recordForm.comment) }}

        <button id="add_information_button" class="btn btn-primary">Ajouter un renseignement</button>
        <button id="count_div" class="btn btn-primary">Compter</button>
        <button class="remove_information_button btn btn-primary">Supprimer un renseignement</button>

    </div>

这是javascript:

   $('.information')
    .on("change", ".record_to_information_form_information", function (event) {
        event.preventDefault();
        var $commentState = $(this).find('option:selected').data('comment')

        //Test: to know if i received the attribute
        console.log($commentState)

        if($commentState===false){
            //the field isn't required
           // {{ form_widget(recordForm.comment, {'attr': {'required': 'false'}}) }}
        }else{
            //the field is required
            // {{ form_widget(recordForm.comment, {'attr': {'required': 'true'}}) }}
        }

    })
;

您有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以从jQuery代码中切换所需的属性值。

我假设data-comment属性的类型为boolean且始终处于设置状态,因此您的toggle语句可以如下所示:

$('.information')
    .on("change", ".record_to_information_form_information", function (event) {
        event.preventDefault();
        var $commentState = $(this).find('option:selected').data('comment');

        //Test: to know if i received the attribute
        console.log($commentState);

        $('.comment').prop('required', $commentState);
    });

如果您需要在if-else语句中做其他事情,则可以按照示例中提供的条件进行操作:

if ($commentState === false) {
    //the field isn't required
    $('.comment').prop('required', false);
} else {
    //the field is required
    $('.comment').prop('required', true);
}