Home  >  Article  >  Web Front-end  >  How to Dynamically Update Div Content with JavaScript: A Guide Using Radio Buttons

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 08:47:03979browse

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>

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>

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!

Statement:
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