Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox:

<div class="checkbox">
    <label>
        <?= Html::checkbox('chocolate', false) ?>
        Chocolate
    </label>
</div>

In addition to that, I also have a span tag:

<span>I enjoy all things chocolate.</span>

I am looking to incorporate either the onchange JavaScript function or jQuery (as I am fairly new to using jQuery) to display the span when the user checks the checkbox.

Initially, I need to retrieve the value of chocolate. However, it is not JavaScript code, it is PHP code:

<?= Html::checkbox('chocolate', false) ?>
.

Answer №1

To enhance the functionality, I recommend assigning a class to your span element. Then, you can implement a change event listener for your checkbox to switch the display style between none and block.

To incorporate the script into your view, simply insert it at the end of your view within the script tags:

 <script>
    document.querySelector('.checkbox [type="checkbox"][name="chocolate"]').addEventListener('change', function(e) {
        console.log(this.checked);
        document.querySelector('span.chocoLike').style.display = (this.checked) ? 'block' : 'none';
    })
</script>

document.addEventListener("DOMContentLoaded", function(e) {
    document.querySelector('.checkbox [type="checkbox"][name="chocolate"]').addEventListener('change', function(e) {
        console.log(this.checked);
        document.querySelector('span.chocoLike').style.display = (this.checked) ? 'block' : 'none';
    })
})
.chocoLike {
    display: none;
}
<div class="checkbox">
    <label>
        <input type="checkbox" name="chocolate">
        Chocolate
    </label>
</div>
<span class="chocoLike">I like all chocolates.</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the object currently being dragged be chosen using JQueryUI Draggable?

Working with JQueryUI draggable, I am interested in applying styling to the draggable element while it is being dragged. Various attempts have been made using code like this: $(".ui-widget-content").draggable({ drag: function(event, ui) { $(this).cs ...

Tips for implementing this code for effective DAO and CRUD operations

As I venture into coding CRUD operations for the first time, I encountered an issue while testing the update functionality: The error message "Dao.get() missing 1 required positional argument: 'id'" is puzzling me. Where could I have gone wrong? ...

Using SetInterval function in conjunction with jQuery's .each() method

I'm looking to cycle through a group of divs and perform random actions at various intervals. I'm trying to use the function below, but the console.log always returns the same object and integer for each iteration. What would be the correct way t ...

On a medium-sized screen, a collapsible button unexpectedly appears amidst the various links

Can anyone help me with sorting out the order of navbar elements? I'm facing an issue where on small screens, the collapse button appears above the links, but on medium screens, it shows up before the last link in the menu. Any suggestions on how to f ...

Building a custom dialog box using Angular Material with HTML and CSS

I've been exploring different approaches to create a customized angular material dialog with a unique header using CSS/SCSS and the TailwindCSS framework. I am aiming for a specific visual effect, similar to what is shown in the figure below. desired ...

Ways to automatically divide lists into various div elements

Hey there! I currently have a list of categories on my page that is subject to change. I'm looking for assistance in creating a loop that will divide my lists into groups of 5 items per div. For example: foreach($categories as $cat) <label> ...

Utilize the provided parameter within a JavaScript function

<script type="text/javascript"> function updateTrackName(trackNum) { document.form1.track_(track_number)_name.value=document.form1.track_(track_number)_parent_work.value; } </script> To modify the line inside of the parent_wor ...

Request the generic password prior to revealing the concealed div

I want to implement a feature where a hidden div is shown once a user enters a password. The password doesn't need to be stored in a database, it can be something simple like 'testpass' for now. Currently, I have written some code using Java ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Using SQL to combine several IDs

First Set of Data |product_name | category_ids | |---------------------------------| |- red_apple | 1, 2 | |- green_apple | 1, 3 | Second Set of Data |category_id | category_name | |---- ...

Showing content in a way that spaces out below the text

Could someone assist me with a CSS problem I'm having? I understand CSS, but debugging is not my strong suit. When I use display: inline-block for both my Academic Information and Personal Information, I'm getting extra white space below (above " ...

Performing subtraction operation on a selected floating-point value from a database using PHP

I am facing an issue with my code where I need to subtract a float value selected from the database and update the subtracted values in the database table. Below is my code snippet: $AmountGiven = $_POST['AmountGiven']; $conn = mysqli_connect("l ...

Utilizing the arr.push() method to replace an existing value within an array with a new object, rather than simply adding a new

Seeking help to dynamically render a list of components that should expand or shrink based on values being added or removed from an array of custom objects. However, facing an issue where pushing a value into the array only replaces the previous value inst ...

Identifier for md-radio-group

In my Angular 4 Material application, I have a set of radio buttons grouped together: <md-radio-group fxLayout fxLayoutAlign="center center" fxLayoutGap="30px"> <md-radio-button value="1">Date</md-radio-button> <md-radio-butto ...

Splitting a foreach loop isn't functioning correctly

My coding expertise allows me to sort the list of cities by country: <?php $pdo = new PDO(...); $cities = $pdo->query('SELECT `city`, `country` FROM `cities` ORDER BY `id` ASC'); $cities->execute(); $data = array(); foreach($cities as $ ...

Utilizing arrays in the label field of Chart.js

Creating a straightforward bar chart using Chartjs 3.x The process involves fetching JSON data from the server, parsing it, and storing specific parts in arrays. See the code snippet below: serverData = JSON.parse(http.responseText); console.log(serverDa ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

What new post status can WordPress generate?

In Wordpress, there are pre-existing post statuses such as Published, Draft, and Pending Review. Is it feasible to incorporate additional post types by registering them through the function.php file of the current theme? Moreover, can the labels of the Pu ...

No data appears to be populating the Javascript data list, yet no errors are being displayed in

I'm facing an issue where I have data that I'm using to create two arrays, but they both end up empty without any errors in the console. Below is the data: mydata = { "id": "661", "name": "some name", "description": "some desc", ...