Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option?

By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options.

If text is typed into the input field, the displayed text will update to reflect what was entered.

Selecting another option will also change the displayed text accordingly and clear any input in the field.

<select id="font-sample-option">
  <option value="1" selected="selected">Aa Bb Cc Dd Ee...</option>
  <option value="2">The quick brown fox...</option>
  <option value="3">When zombies arrive...</option>
</select>

<span>Or</span>

<input id="font-sample-input" placeholder="Type here ..." maxlength="55" type="text">

// Display selected text from the select option or input field
<span class="font-sample-display">Aa Bb Cc Dd Ee...</span>

Answer №1

Utilize JavaScript to dynamically change HTML elements.

<select id="font-sample-option" onchange="selectChange(event)">
  <option value="1" selected="selected">Apple Banana Cherry Date Elderberry...</option>
  <option value="2">The quick brown fox jumps over the lazy dog.</option>
  <option value="3">When zombies arrive, quickly fax judge Pat.</option>
</select>
<span>Or</span>
<input id="font-sample-input" oninput="inputChange(event)" placeholder="Type here ..." maxlength="55" type="text">
<br /><br />
<span class="font-sample-display">Apple Banana Cherry Date Elderberry...</span> <br />
<span class="font-sample-display">Apple Banana Cherry Date Elderberry...</span> <br />
<span class="font-sample-display">Apple Banana Cherry Date Elderberry...</span>
<script>
  const selectDom = document.querySelector('#font-sample-option')
  const inputDom = document.querySelector('#font-sample-input')
  const contentDom = document.querySelectorAll('.font-sample-display')
  function selectChange(e) {
    const index = e.target.value
    const text = e.target[index - 1].innerText
    updateContent(text)
    inputDom.value = ''
  }
  function inputChange(e) {
    const text = e.target.value
    updateContent(text)
    selectDom.value = ''
  }
  function updateContent(text) {
    contentDom.forEach(dom => {
      dom.innerText = text
    })
  }
</script>

Answer №2

It seems like you're looking for something along the lines of:

//.html

<select id="font-sample-option">
      <option value="Aa Bb Cc Dd Ee..." selected="selected">Aa Bb Cc Dd Ee...</option>
      <option value="The quick brown fox...">The quick brown fox...</option>
      <option value="When zombies arrive...">When zombies arrive...</option>
</select>

<span>Or</span>

<input id="font-sample-input" placeholder="Type here ..." maxlength="55" type="text">
   
<span id="font-sample-display">Aa Bb Cc Dd Ee...</span>

//.js

window.addEventListener('load', () => {
  const selectEl = document.getElementById('font-sample-option');
  const inputEl = document.getElementById('font-sample-input');
  const spanEl = document.getElementById('font-sample-display');    
  selectEl.addEventListener('change', () => spanEl.innerHTML = selectEl.value);
  inputEl.addEventListener('keyup', () => spanEl.innerHTML = inputEl.value);    
});

Answer №3

To detect changes in the select element and text input element, you can listen for the change event on the select element and the input event on the text input element.

If the value of the select element is 4 (or any other value), the fieldset will become enabled, allowing the user to enter text into the text input field. You can hide the text input field using a CSS selector like

fieldset:disabled {display: none;}
. One advantage of disabled elements within a form is that they are not considered during the submit event.

document.forms.form01.font_sample_option.addEventListener('change', e => {
  let form = e.target.form;
  form.custom_fieldset.disabled = true;
  if(e.target.value == 4){
    form.custom_fieldset.disabled = false;
    form.selected_text.value = form.font_sample_input.value;
  }else{
    form.selected_text.value = e.target.selectedOptions[0].label;
  }
});

document.forms.form01.font_sample_input.addEventListener('input', e => {
  let form = e.target.form;
  form.selected_text.value = form.font_sample_input.value;
});
<form name="form01">
  <select name="font_sample_option">
    <option selected disabled>Select an option</option>
    <option value="1">Aa Bb Cc Dd Ee...</option>
    <option value="2">The quick brown fox...</option>
    <option value="3">When zombies arrive...</option>
    <option value="4">Custom text</option>
  </select>
  <fieldset name="custom_fieldset" disabled>
    <span>Or</span>
    <input name="font_sample_input" placeholder="Type here ..." maxlength="55" type="text">
  </fieldset>
  <span class="font-sample-display"><output name="selected_text"></output></span>
</form>

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

What are the potential ways in which an html IMG tag can disrupt the functionality of this

For years, I have been using this form code without any issues. The code functions perfectly and all the tags are correct. However, whenever I include an image tag, it displays a failure message and prevents the mail function in PHP from working. The hea ...

Connecting the v-model in a Vue.js child component to update the parent value

I've encountered an issue with a vue component where I'm trying to link a text input in the child template to a variable in the parent using v-model, but it doesn't seem to be working. How can I make this work? Currently, I am using Vue.js ...

Tips for enhancing the fluidity of animations after removing an item from a list

I'm working on a project where I have a list of elements that are removed with an animation when clicked. However, I noticed that when one element is removed, the rest of the elements just jump up instead of smoothly transitioning. Is there a way to m ...

Locating a Guild Member using their Alias

I need help locating a GuildMember using their nickname. The nickname is linked to their Roblox name upon joining the server, and I've configured a webhook to transmit a message in a specific channel containing their username and other related details ...

Enhance the "text" attribute of IXMLDOMElement to enable functionality in Chrome

The web application I am currently working on was developed approximately 10 years ago and is only compatible with Internet Explorer. My goal is to make it functional in Chrome as well. I am facing a challenge regarding the "text" property of IXMLDOMEleme ...

Have you considered retrieving POST parameters using Ajax POST in jQuery?

Below is the code snippet: $.ajax({ type: "POST", url: "http://localhost:3000/rcm/global_config/update", data: {k: 'sdfa', v: 'dsfas'}, success: function(data, textStatus, XMLHttpRequest){ alert("Data ...

Make sure to always display the browser scrollbar in order to avoid any sudden page

Question: How can I ensure the scrollbar is always visible in a browser using JavaScript? I've noticed that some of my web pages have a scrollbar while others do not, causing the page to jump when navigating between them. Is there a way to make t ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be a ...

The lightbox is triggered by clicking on a different div to display its content

Great news - my lightbox is up and running! Each image on my website corresponds to a different organization, and clicking on the image opens a specific lightbox. My question is: how can I have a lightbox configured so that only the trigger image is displ ...

Converting a Class Component to a Functional Component: Step-by-Step Guide

Recently, I have been transitioning from working on class components to function components in React. However, I am facing some issues with my functional component code after converting it from a class component. In my functional component code, there is ...

Embed a service within an Angular 1.5 component

I'm struggling with initializing a test.service.js file from an angular1.5 component and I'm not entirely sure how to accomplish it. Below is the structure I have used for my angular components: var testComponent = { templateUrl: "app/compo ...

Implementing jQuery form validator post anti-SPAM verification?

I am facing what seems like a straightforward JavaScript issue, but my knowledge in this area is still limited. Following a successful implementation of basic anti-SPAM feature that asks the user to solve a simple math problem, how can I integrate jQuery& ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

Integrating dynamic PHP echo strings from a database into an established CSS layout

I am currently exploring PHP and MySQL databases, and I have managed to develop a basic search engine for my website. However, I am facing an issue that I am struggling to resolve: Is there a way to integrate the PHP echo output (search results) into the ...

When the jQuery document is ready, it typically returns null, but the console can still access and display

I have encountered an issue while working on a solution within a CMS (EPiServer). When I utilize console.log to check my object, it displays a null value. $(document).ready(function () { console.log("$('.EPiRequester').html() =" + $('. ...

Detailed enrollment procedure

I am facing an issue with the code in my HTML that validates input types. The system detects empty fields and prevents proceeding to the next step. How can I disable this validation as some of the fields are not required? For instance, the input type < ...

Setting line height as a pixel value does not yield the desired result

$(element).css(options.css).attr(options.attr).addClass(options.class) //ensure line-height is correctly assigned if($(element).is('p') && _.isString(options.css['line-height'])){ console.log('line-height assigned: &apos ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

What could be causing the absence of the ID definition?

Whenever I send a DELETE request, I receive an error message stating ReferenceError: id is not defined at Object.removeOne (...\services\user.js:16:38. I am unsure about the role of 'id' in \services\user.js and why it is not ...