Home > Web Front-end > JS Tutorial > body text

How to Dynamically Update Div Content with JavaScript: A Guide Using Radio Buttons

Mary-Kate Olsen
Release: 2024-10-27 08:47:03
Original
978 people have browsed it

How to Dynamically Update Div Content with JavaScript: A Guide Using Radio Buttons

How to Change Div Content with JavaScript

Modifying the content of a div element using JavaScript is a common task in web development. This article will guide you through the steps involved, even if the div lacks a "value" attribute.

Imagine you have the following HTML code:

<code class="html"><div id="content"></div>
<input type="radio" name="radiobutton" value="A" onClick="changeDivContent()">
<input type="radio" name="radiobutton" value="B" onClick="changeDivContent()"></code>
Copy after login

You want to be able to change the content of the div element by selecting either the "A" or "B" radio buttons.

Since there isn't a "value" attribute for the div, you can use the innerHTML property of the element to set its content.

The following JavaScript function accomplishes this:

<code class="js">function changeDivContent() {
  let selectedValue = document.querySelector('input[name=radiobutton]:checked').value;
  document.getElementById("content").innerHTML = selectedValue;
}</code>
Copy after login

Here's a breakdown of the code:

  • document.querySelector('input[name=radiobutton]:checked') gets the currently selected radio button.
  • value gets the value of the selected radio button.
  • document.getElementById('content').innerHTML = selectedValue sets the content of the content div to the selected radio button's value.

By clicking on either "A" or "B," this function will update the text inside the div element.

The above is the detailed content of How to Dynamically Update Div Content with JavaScript: A Guide Using Radio Buttons. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!