Changing the text displayed after a checkbox is checked

I am currently working on creating a form that includes both checkboxes and text entry fields. The goal is to have related text appear next to each checkbox when it is checked. However, my current code does not seem to be functioning as expected: HTML:

<input type="checkbox" class="box1" onchange="showHide()"> Option 1
<div class="hid box1">
    <select name="option1">
        <option value="yes">Yes</option>
        <option value="no">No</option>
     </select>
    Comments: <input type="text" name="option1Comment">
</div>

CSS:

.hid {
    display: none;
}

JavaScript:

function showHide() {
    var checkBox = document.getElementByClassName(this);
    var text = document.getElementByClassName(this "hid");
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
        text.style.display = "none";
    }
}

Answer №1

If you want to improve your code, there are a couple of suggestions.

Firstly, consider updating the function call on the <input> element from onchange="showHide()" to onchange="showHide(this)"

Next, ensure that the syntax of getElementByClassName in your function is correct or replace it with querySelector to target only the desired Node.

To hide or show your <div>, you can use a function like this:

function showHide(element) {
    let checkboxClass = element.classList[0];
    let div = document.querySelector("div.hid." + checkboxClass);
    div.style.display = (element.checked) ? "block" : "none";
}

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

Creating a gallery that adjusts to different screen sizes is a valuable

Hello fellow programmers, I'm currently facing a challenge. I'm trying to create a gallery using HTML, CSS, and Bootstrap (I have a good grasp of JavaScript and still learning). I'm aiming to make it fully responsive, but I'm strugglin ...

Creating a service in AngularJS 1.8 with ES6 modules that acts as a bridge to a class based API interface

As I continue to enhance a codebase that originally consisted of a mix of different versions of AngularJs and some unstructured code utilizing various versions of a software API, I encounter an interesting quirk. It appears that this API is accessible thro ...

One way to target a span inside a label element when a checkbox is checked using React Material UI createStyles is by using CSS selectors in combination with

I need help targeting the span element within a checkbox label in order to change its background color when the checkbox is checked. <div className={classes.container}> <input type="checkbox" id="checkboxid" /> <lab ...

What is the best way to create a time delay between two consecutive desktop screenshot captures?

screenshot-desktop is a unique npm API that captures desktop screenshots and saves them upon request. However, I encounter the need to call the function three times with a 5-second delay between each call. Since this API works on promises, the calls are e ...

"Utilizing the flex box feature in IE 10 for efficient text trunc

.container { background: tomato; width: 100px; display: flex; } .text-left { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .text-right { } <div class=container> <div class="text-left"> title title title ...

How can you use angularjs to dynamically adjust the style of an element based on the height of another element?

$('#reply').css("padding-top", $('.post:visible').height()-35 + "px" ); In this snippet, I am adjusting the CSS padding-top property of the element with the ID #reply to match the height of the visible .post element. While this approa ...

Utilizing JSON to display multiple markers on a Google Map

How can I display multiple markers on a Google Map using JSON data? I have successfully added a single marker, but I'm facing issues with adding multiple markers. Below is the code for a single marker (which is working): var lat=position.coords.lati ...

Confirm the data within an HTML table and apply color coding to the cells appropriately

Currently, I have an HTML table used to automatically validate data collected from soil pollutants analyses. Here is a snippet describing the table structure: <table id="table1"> <thead class="fixedHeader"> <tr><input type="submit" ...

Circle of Progress Completion

I am currently working on developing a methodology or formula to complete a circle based on a given percentage. My progress so far can be seen in the following images: https://i.stack.imgur.com/nr21h.png I aim for the circle to fill up based on an incre ...

Encountered a problem when attempting to instantiate an array of objects in Angular using TypeScript

Encountering an Angular object-array creation error. The structure of the data I need to display is as follows: stats : [ { name : 'x', age : 20 }, { name : 'y', age : 10 }, ]; In my A ...

Why isn't Meteor.call functioning in the stub?

As I delve into the realm of async JavaScript coding, I have encountered a gist that has left me puzzled: https://gist.github.com/dariocravero/3922137 Specifically within client_save.file.js - there are parts of this code snippet that baffle me: fileRead ...

Enhancing form validations in Rails using Ajax and error_message_on

I'm currently working on implementing ajax validations in my form, but I've encountered some difficulties. Within my form, I have code similar to the following: <% form_for @user, :html => { :id => 'user_form', :multipart =&g ...

When using DataTables ajax.reload with pagination enabled, the table content jumps to the bottom of the page

I am currently using jQuery DataTables with ajax sourced data. To ensure that the data remains up to date every 30 seconds without requiring a page refresh, I have been utilizing the ajax.reload() function. To achieve this, I have placed the ajax.reload() ...

Unable to access the contents of an array (React JS)

After fetching the content as an array and viewing its contents with console.log, I noticed that despite the array being populated, it has a length of 0, making it impossible to retrieve its elements using map. What could be causing this issue? https://i. ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

Select the Date Month Year on the Calendar

However, all I am able to manage is to trigger an alert displaying the complete date and time. $(function() { $('#popupDatepicker').datepick(); $('#inlineDatepicker').datepick({onSelect: showDate}); }); function showDate(date) ...

Can you import folders containing *.vue files in your project?

Repeating code is my least favorite thing. Currently, I am importing vue files in a repetitive manner in my main.js file. import Default from '../../src/components/default.vue'; import Home from '../../src/components/home.vue&apo ...

How can I alter the display of table rows and columns using responsive design techniques?

Currently utilizing bootstrap, I have a drinks menu displayed in the following layout when viewed in Firefox. The mobile view of this menu is functioning properly. However, I am encountering issues with the desktop view as the columns are not aligning cor ...

Tips for successfully passing a variable as props within the confines of a different function's component

Is there a way to pass the variable id to the onConfirm event in this code snippet? Currently, it seems like the function is being called by another function within setAlert. How can I achieve this? const confirmationPrompt = (id) => { setAlert( ...

"An error has occurred in the file system, make sure to handle it when

I am encountering an issue with submitting a form using jQuery's ajaxSubmit() function. The problem arises when the file selected in the form is renamed, deleted, or made inaccessible before submission, leading to potential discrepancies in whether th ...