1
resposta

[Dúvida] Campo se altera dinamicamente conforme caixa de seleção

Olá a todos. Estou com uma dúvida de como fazer que um campo se alterar dinamicamente conforme caixa de seleção. Eu tenho meu arquivo form.blade.php, de forma que se o Input Type for "Select Field" ele mude o texto do campo "Input Description" para "Enter options separated by a comma" e no campo "Enter Description Here" que está Enter Description Here se altere para a string "Option 1, Option 2,Option 3". Abaixo segue meu código

                <div class="mb-20">
                    @if($template!= null)
                        <?php $question_i = 1; ?>
                        @foreach(json_decode($template->questions) as $question)
                            <div class="user-input-group input-group control-group flex-col !p-5 mb-[20px] relative border border-solid rounded-[--tblr-border-radius]" data-input-name="{{$question->question}}" data-inputs-id="{{$question_i}}">
                                <div class="mb-[20px]">
                                    <label class="form-label">
                                        {{__('Select Input Type')}}
                                        <x-info-tooltip text="{{__('Input fields for short texts and Textarea fields are good for long text.')}}" />
                                    </label>
                                    <select class="form-select input_type">
                                        @foreach($input_types as $input_type)
                                        <option value="{{$input_type->getType()}}" {{$question->type == $input_type->getType() ? 'selected' : null}}>{{$input_type->getName()}}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="mb-[20px]">
                                    <label class="form-label">
                                        {{__('Input Name')}}
                                        <x-info-tooltip text="{{__('Unique input name that you can use in your prompts later.')}}" />
                                    </label>
                                    <input type="text" class="form-control input_name" placeholder="{{__('Enter Name Here')}}" oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'');" value="{{$question->question}}">
                                </div>
                                <div class="mb-[20px]">
                                    <label class="form-label">
                                        {{__('Input Description')}}
                                        <x-info-tooltip text="{{__('A description for the input.')}}" />
                                    </label>
                                    <input type="text" class="form-control input_description" placeholder="{{__('Enter Description Here')}}" value="{{$question->description}}">
                                </div>
                                <button class="remove-inputs-group inline-flex items-center justify-center !w-6 !h-6 p-0 border-none rounded-md absolute !top-4 !end-5 bg-[transparent] text-red-700 transition-all hover:text-white hover:bg-red-600" type="button">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M9 12l6 0"></path> </svg>
                                </button>
                            </div>
                            <div class="add-more-placeholder"></div>
                            <?php $question_i++ ?>
                        @endforeach
                    @else
                        <div class="user-input-group input-group control-group flex-col !p-5 mb-[20px] relative border border-solid rounded-[--tblr-border-radius]" data-inputs-id="1">
                            <div class="mb-[20px]">
                                <label class="form-label">
                                        {{__('Select Input Type')}}
                                        <x-info-tooltip text="{{__('Input fields for short texts and Textarea fields are good for long text.')}}" />
                                    </label>
                                <select class="form-select input_type">
                                    @foreach($input_types as $input_type)
                                        <option value="{{$input_type->getType()}}">{{$input_type->getName()}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-[20px]">
                                <label class="form-label">
                                    {{__('Input Name')}}
                                    <x-info-tooltip text="{{__('Unique input name that you can use in your prompts later.')}}" />
                                </label>
                                <input type="text" class="form-control input_name" oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'');" placeholder="{{__('Enter Name Here')}}">
                            </div>
                            <div class="mb-[20px]">
                                <label class="form-label">
                                    {{__('Input Description')}}
                                    <x-info-tooltip text="{{__('A description for the input.')}}" />
                                </label>
                                <input type="text" class="form-control input_description" placeholder="{{__('Enter Description Here')}}">
                            </div>
                            <button class="remove-inputs-group inline-flex items-center justify-center !w-6 !h-6 p-0 border-none rounded-md absolute !top-4 !end-5 bg-[transparent] text-red-700 transition-all hover:text-white hover:bg-red-600" type="button" disabled>
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M9 12l6 0"></path> </svg>
                            </button>
                        </div>
                        <div class="add-more-placeholder"></div>
                    @endif

                </div>
                
1 resposta

Olá Luiz! Tudo bem?

Para fazer com que um campo se altere dinamicamente conforme a caixa de seleção, você pode utilizar JavaScript para manipular o conteúdo do campo de descrição e do campo de opções.

Primeiro, você precisa adicionar um evento de mudança à caixa de seleção. Por exemplo, você pode adicionar a classe "input_type" à caixa de seleção e utilizar o seguinte código JavaScript:

document.querySelectorAll('.input_type').forEach(function(select) {
  select.addEventListener('change', function() {
    var selectedOption = this.options[this.selectedIndex].value;
    var inputDescription = this.closest('.user-input-group').querySelector('.input_description');
    var enterDescriptionHere = this.closest('.user-input-group').querySelector('.enter_description_here');

    if (selectedOption === 'Select Field') {
      inputDescription.value = 'Enter options separated by a comma';
      enterDescriptionHere.value = 'Option 1, Option 2, Option 3';
    } else {
      inputDescription.value = '';
      enterDescriptionHere.value = 'Enter Description Here';
    }
  });
});

Esse código adiciona um evento de mudança a todas as caixas de seleção com a classe "input_type". Quando uma opção é selecionada, ele verifica se a opção selecionada é "Select Field". Se for, ele atualiza o valor do campo de descrição para "Enter options separated by a comma" e o valor do campo "Enter Description Here" para "Option 1, Option 2, Option 3". Caso contrário, ele limpa o campo de descrição e define o valor do campo "Enter Description Here" como "Enter Description Here".

Lembre-se de adicionar esse código JavaScript ao seu arquivo form.blade.php, de preferência antes do fechamento da tag </body>.

Espero ter ajudado. Caso tenha mais dúvidas ou problemas, estarei à disposição.

Abraços e bons estudos!

Caso este post tenha lhe ajudado, por favor, marcar como solucionado ✓.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software