Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mozew's avatar
Level 6

SyntaxError: redeclaration of const selectElement

How to display checkboxes where select option = category_id.

I tried for show the checkboxes , after I select a option.

And I want the same thing. But with Laravel and the database.

But why when I choose one, I'll get the page of browser white page for me?

Inspector in firefox

checkbox

index.blade.php

<form action="{{ route('computers.store') }}" method="post">
    {{ csrf_field() }}
    <div class="form-group">
        <select id="select" name="category_id" class="form-control" onchange="displayBoxes()">
            @foreach($categories as $category)
                <option data-description="{{ $category->description }}" value="{{ $category->id }}">{{ $category->name }}</option>
            @endforeach
        </select>
    </div>
    <div class="form-group">
        <p id="description"></p>
    </div>
    <div class="form-group d-none box17">
        <p></p>
        @foreach ($computers->where('category_id', 2) as $computer)
            <input type="checkbox" id="{{ $computer->latin }}">
            <label for="{{ $computer->latin }}">{{ $computer->name }}</label>
        @endforeach
    </div>
    <div class="form-group d-none box18">
        <p></p>
        @foreach ($computers->where('category_id', 3) as $computer)
            <input type="checkbox" id="{{ $computer->latin }}">
            <label for="{{ $computer->latin }}">{{ $computer->name }}</label>
        @endforeach
    </div>
    <div class="form-group d-none box19">
        <p></p>
        @foreach ($computers->where('category_id', 4) as $computer)
            <input type="checkbox" id="{{ $computer->latin }}">
            <label for="{{ $computer->latin }}">{{ $computer->name }}</label>
        @endforeach
    </div>
    <div class="form-group">
        <button class="btn btn-primary">ادامه</button>
    </div>
</form>

script.js

const selectElement = document.querySelector('#select');
selectElement.addEventListener('change', (event) => {
    let boxes = document.querySelectorAll('div');
    boxes.forEach(function(e) {
        e.classList.add('d-none');
    });
});
document.querySelector('.box' + selectElement.options[selectElement.selectedIndex].value).classList.remove('.d-none');

I get this error in console

SyntaxError: redeclaration of const selectElement

0 likes
24 replies
ftiersch's avatar

Where are you adding the script.js file to your code? in the HEAD tag or somewhere else?

mozew's avatar
Level 6

When I run this page. Returns a blank page & white page for me. and get an error in the console.

blank page

ftiersch's avatar

I think the "displayBoxes is not defined" error could be because the select fires an onchange event for the "initializiation". So basically it fires that event right away but you add the script file only afterwards which means at the moment of the event the function is not there yet.

Try adding the script.js in the head of your HTML or add the onchange event listener in the JavaScript after the function has been defined.

mozew's avatar
Level 6

I removed and tried change the codes but it did not solve my problem yet.

const selectElement = document.querySelector('#select');
selectElement.addEventListener('change', (event) => {
    let boxes = document.querySelectorAll('div');
    boxes.forEach(function(e) {
        e.classList.add('d-none');
    });
});
document.querySelector('.box' + selectElement.options[selectElement.selectedIndex].value).classList.remove('.d-none');

error

After I selected a option, Returns a blank page & white page for me.

Snapey's avatar

Its hard when you are just mashing other peoples code together and hoping it works without the basic understanding or any debugging capability.

1 like
mozew's avatar
Level 6

@SNAPEY - OK , I thank you all for helping me for one year so that I can be a programmer. Well, now you answer

Snapey's avatar

redeclaration of const selectElement

you have this line;

const selectElement = 

somewhere else on your page you have the same line again. As you don't share all the code we cannot help, but it should be easy for you to look and see where you have this twice

mozew's avatar
Level 6

@SNAPEY - web.php

Route::get('/computers', 'ComputerController@index')->name('computers');
Route::post('/computers/store', 'ComputerController@store')->name('computers.store');

ComputerController.php

<?php

namespace App\Http\Controllers;

use App\Category;
use App\Computer;
use App\Order;
use Illuminate\Http\Request;

class ComputerController extends Controller
{
    public function index ()
    {
        $computers = Computer::all();
        $categories = Category::where('parent_id', '=', 4)->get();
        return view('Home.computers', compact('categories', 'computers'));
    }

    public function store(Request $request)
    {
        $this->validate(request(), [
            'category_id' => 'required'
        ]);

        $order = Order::findOrFail(request('category_id'));

        if(auth()->user()->checkOrder($order)) {
            alert()->error('you ordered this order already','warinng')->persistent('ok');
            return redirect()->back();
        } else  if (auth()->check()) {
            $order = new Order($request->all());
            $order->category_id = $request->category_id;
            $order->user_id = auth()->user()->id;
            $order->status = 0;
            $order->save();
            alert()->success('it saved.', 'ok');
            return redirect()->back();
        } else {
            alert()->warning('you should register.', 'warning');
            return redirect()->back();
        }
    }
}

User.php

public function checkOrder($category)
{
    return !! Category::where('user_id' , $this->id)->where('category_id' , $category->id)->first();
}

computers.blade.php

<form action="{{ route('computers.store') }}" method="post">
    {{ csrf_field() }}
    <div class="form-group">
        <select id="select" name="category_id" class="form-control" onchange="displayBoxes()">
            @foreach($categories as $category)
                <option data-description="{{ $category->description }}" value="{{ $category->id }}">{{ $category->name }}</option>
            @endforeach
        </select>
    </div>
    <div class="form-group">
        <p id="description"></p>
    </div>
    <div class="form-group d-none box17">
        <p></p>
        @foreach ($computers->where('category_id', 2) as $computer)
            <input type="checkbox" id="{{ $computer->latin }}">
            <label for="{{ $computer->latin }}">{{ $computer->name }}</label>
        @endforeach
    </div>
    <div class="form-group d-none box18">
        <p></p>
        @foreach ($computers->where('category_id', 3) as $computer)
            <input type="checkbox" id="{{ $computer->latin }}">
            <label for="{{ $computer->latin }}">{{ $computer->name }}</label>
        @endforeach
    </div>
    <div class="form-group d-none box19">
        <p></p>
        @foreach ($computers->where('category_id', 4) as $computer)
            <input type="checkbox" id="{{ $computer->latin }}">
            <label for="{{ $computer->latin }}">{{ $computer->name }}</label>
        @endforeach
    </div>
    <div class="form-group">
        <button class="btn btn-primary">save</button>
    </div>
</form>

script.js

function displayBoxes() {
    let option = document.querySelector('#select');
    let boxes = document.querySelectorAll('div');
    boxes.forEach(function(el) {
        el.classList.add('d-none');
    });
    document.querySelector('.box' + option.options[option.selectedIndex].value).classList.remove('.d-none');
}

I send complete my codes.

Snapey's avatar

Javascript...Javascript...Javascript...Javascript...Javascript...Javascript...Javascript...

Javascript... Javascript... Javascript... Javascript... Javascript... Javascript... Javascript...

mozew's avatar
Level 6

Javascript...

(function($) {
    "use strict"; // Start of use strict

    // Smooth scrolling using jQuery easing
    $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 54)
                }, 1000, "easeInOutExpo");
                return false;
            }
        }
    });

    // Closes responsive menu when a scroll trigger link is clicked
    $('.js-scroll-trigger').click(function() {
        $('.navbar-collapse').collapse('hide');
    });

    // Activate scrollspy to add active class to navbar items on scroll
    $('body').scrollspy({
        target: '#mainNav',
        offset: 50
    });

})(jQuery); // End of use strict

AOS.init({
    easing: 'ease-in-out-sine'
});

$('#logout-button').on('click', function(e) {
    e.preventDefault();
    $('#logout-form').submit();
});


function displayBoxes() {
    let option = document.querySelector('#select');
    let boxes = document.querySelectorAll('div');
    boxes.forEach(function(el) {
        el.classList.add('d-none');
    });
    document.querySelector('.box' + option.options[option.selectedIndex].value).classList.remove('.d-none');
}

$('#select').change(function() {
    var $selected = $(this).find(':selected');
    $('#description').html($selected.data('description'));
}).trigger('change');

getSelectorFromElement: function getSelectorFromElement(element) {
    var selector = element.getAttribute('data-target');

    if (!selector || selector === '#') {
        var hrefAttr = element.getAttribute('href');
        selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : '';
    }

    return selector && document.querySelector(selector) ? selector : null;
}

what do you mean? Is Javascript a problem?

Snapey's avatar

Your problem is javascript. You know that yes? You appreciate the difference between PHP and javascript?

And despite previously posting 'this is all code' you then post some more javascript and still this is not the code you posted earlier where selectElement was being declared.

1 like
mozew's avatar
Level 6

master.blade.php

<div id="app">
    @include('Home.layouts.header')
    @yield('content')
    @include('Home.layouts.footer')
</div>
@yield('script')

footer.blade.php

<script src="{{ asset('themes/js/jquery-3.3.1.slim.min.js') }}"></script>
<script src="{{ asset('themes/js/jquery.min.js') }}"></script>
<script src="{{ asset('themes/js/popper.min.js') }}"></script>
<script src="{{ asset('themes/js/bootstrap.min.js') }}"></script>
<script src="{{ asset('themes/js/jquery.easing.min.js') }}"></script>
<script src="{{ asset('themes/js/aos.js') }}"></script>
<script src="{{ asset('themes/js/script.js') }}"></script>
<script src="{{ asset('themes/js/sweetalert.min.js') }}"></script>
@include('sweet::alert')
mozew's avatar
Level 6

I changed before line

const selectElement = document.querySelector('#select');

selectElement.addEventListener('change', (event) => {
    let boxes = document.querySelectorAll('div');
    boxes.forEach(function(e) {
        e.classList.add('d-none');
    });
});
document.querySelector('.box' + selectElement.options[selectElement.selectedIndex].value).classList.remove('.d-none');
mozew's avatar
Level 6

@SNAPEY

Which one should I use?

$('#select').change(function() {...

or

const selectElement = document.querySelector('#select');...

jlrdw's avatar

I am just trying to help, I believe you should really take some jQuery and or javascript tutorials.

1 like
jlrdw's avatar

I work with radio and ckeckboxes often, but have had tutorials and lessons. It's hard to teach javascript and HTML in just a forum post. It takes months of practice projects. Many here have suggested you take more tutorials. Just trying to help by suggesting that.

Example:

But when bringing up data from database, you have to find out via a query if a "1" or "0" is stored for a checkbox.

If a one then

$('#mycheck').prop('checked', true);

Of course if a zero then false. But some jquery tutorials would help you learn this.

Snapey's avatar

@jlrdw I know you are trying to help, but this question is not even about checkboxes.

Its about javascript. Its about knowing that you cannot have a const declared twice in your code. Its about knowing what javascript is being loaded and why. Its about learning to debug your own code to find conflicting information. Just real basic javascript stuff.

The sort of problem we have all struggled through in the past taking code snippet from tutorial A, mashing it with tutorial B then just generally moving the bits around until it hopefully works.

Most of us get through that by sitting back and considering the possibilities. By googling. By process of elimination...

Some others though seem to think its ok to just post half a question and then go and get on with cobbling something else together whilst we get on with solving it.

You know the movie Oliver, where he stands there with his bowl and says "sir, I'd like some more" - well I'm at the point of replying to Oliver, you've been here a year now piss off and find your own food.

1 like
jlrdw's avatar

@SNAPEY - Thanks, I only added that because he had

How to display checkboxes where select option = category_id

But I think part of it is OP has trouble conveying meaning. I admit I try to figure out what is needed.

And @irankhosravi seriously some jquery practice tutorials would help you.

Learn yes, but don't copy and paste from several tutorials and expect things to work.

Learn the stuff well so you know in your mind the how and why.

Like a Doctor doing neurosurgery, they aren't guessing, they trained and studied for many many years.

1 like
messhias's avatar

Well, almost everyone talked here, your problem isn't even a PHP problem it's a JavaScript problem.

You cannot redeclare a constant, for example

const test = "foo";
const test = "bar"'; // -> this is wrong!!!! You cannot do that

Another example:

const foo = "bar";
foot = "foo"; // => this is wrong also.

The @snapey example describes very well what you doing, don't be Oliver and stop flood the Laravel Group in telegram with your problems and promises of payment and study more.

Thank you.

Please or to participate in this conversation.