Merge text inputs to preview content prior to form submission

I've been on the hunt for a solution to display the collective values entered into multiple text box fields as they are being typed. Currently, I have 6 text boxes (description1, description2, description3, description4, description5, description6) which are concatenated using PHP into a "final_description" that is then stored in the database. My objective is to provide users with a preview of what the final_description will look like when all 6 fields are combined, before submitting the form and processing it through PHP. The kind of code I'm seeking is akin to the functionality seen here on StackOverflow where typing adds content below for visual output. I simply want to merge the input from multiple text boxes into one preview.

Answer №1

If you have the following elements:

<input class="desc" id="desc1" />
<input class="desc" id="desc1" />
<input class="desc" id="desc1" />
<input class="desc" id="desc1" />

<div id="final_desc" />

You can make it work like this:

window.onload = function(){
   function forEach(arr, fun){ return Array.prototype.forEach.call(arr, fun); };
   var inputs = document.querySelectorAll(".desc");
   function updateFinalDesc(){
       var finalDescription = "";
       forEach(inputs, function(inp){ finalDescription += inp.value + "<br/>"; });
       document.getElementById('final_desc').innerHTML = finalDescription;
   };
   forEach(inputs, function(input){
       input.addEventListener('keypress', updateFinalDesc);
       input.addEventListener('change', updateFinalDesc);
   });
}

I hope this explanation is helpful. Cheers!

Answer №2

For those utilizing the knockout.js data binding framework, here is a solution for your specific scenario:

<div id="content">
    <input type="text" data-bind="value: detail1" />
    <input type="text" data-bind="value: detail2" />
    <input type="text" data-bind="value: detail3" />
    <input type="text" data-bind="value: detail4" />
    <input type="text" data-bind="value: detail5" />
    <input type="text" data-bind="value: detail6" />
    <span data-bind="text: combined"></span>
</div>

<script type="text/javascript">
function myDataModel()
{
    var self = this;
    self.detail1 = ko.observable("");
    self.detail2 = ko.observable("");
    self.detail3 = ko.observable("");
    self.detail4 = ko.observable("");
    self.detail5 = ko.observable("");
    self.detail6 = ko.observable("");

    self.combined= ko.computed(function() {
    return self.detail1() + " " + self.detail2()+ " " + self.detail3()+ " " + self.detail4()+ " " + self.detail5()+ " " + self.detail6();
    }, self);
}

ko.applyBindings(new myDataModel(), document.getElementById("content"));
</script>

To ensure proper functionality, remember to integrate the knockout.js library into your webpage.

Answer №3

My approach might not be perfect, but it gets the job done:

var desc1 = document.getElementById('description1');
var desc2 = document.getElementById('description2');
var desc3 = document.getElementById('description3');
var desc4 = document.getElementById('description4');
var desc5 = document.getElementById('description5');
var desc6 = document.getElementById('description6');
desc1.onkeyup = desc1.onkeypress = function(){
document.getElementById('description1preview').innerHTML = this.value;
}
desc2.onkeyup = desc2.onkeypress = function(){
document.getElementById('description2preview').innerHTML = this.value;
}
desc3.onkeyup = desc3.onkeypress = function(){
document.getElementById('description3preview').innerHTML = this.value;
}
desc4.onkeyup = desc4.onkeypress = function(){
document.getElementById('description4preview').innerHTML = this.value;
}
desc5.onkeyup = desc5.onkeypress = function(){
document.getElementById('description5preview').innerHTML = this.value;
}
desc6.onkeyup = desc6.onkeypress = function(){
document.getElementById('description6preview').innerHTML = this.value;
}

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

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Problem with laravel ajax request

I've spent the entire weekend trying to figure this out, but I can't seem to make it work. It works fine with the 'get' method, but not with 'post'. I'm using Laravel 4 and jQuery. Here's how my JavaScript looks: $ ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

jQuery Ajax consistently returns the data type of an 'object'

I'm currently working on a validation system for a form using Prototype, but I need to integrate a jQuery ajax function to verify if a username already exists in the database. However, I've run into an issue where the value returned by jQuery is ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...

Is it possible to preserve the query parameters from the previous page using Vue Router's Navigation guard feature?

Hey there! So, I'm looking to pass a query from the current page to the next one without manually coding it into all of my push functions. I was wondering if there's a way to do this through Navigation guard or some hooks? I did some research an ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

Cannot extract the 'name' property from 'e.target' because it is not defined

I encountered an error message stating that I cannot destructure the property 'name' of 'e.target' because it is undefined within the createform() method. Despite highlighting the line causing the error, I am still unable to comprehend ...

Modifying the page header content using JavaScript

There's this snippet of code that alters the image on another page: <div class="imgbx"> <button onclick="window.location.href='index.html?image=images/xr-black.jpg&tit=XR-black'" >Invisible ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...

Can a JavaScript function be used with images to operate across multiple elements?

How can I make a function work on multiple elements? let image = document.getElementById("opacityLink"); image.onmouseover = function() { image.style = "opacity:0.9"; }; image.onmouseout = function() { image.style = "opacity:1"; }; <div class=" ...

PHP: How to send checkbox value in conjunction with textbox values

I have implemented a contact form on my website using ajax/php/jquery. The form includes checkboxes named 'selection[]' that I am struggling to get the values of and include in the email text. Currently, when I use an implode statement, the che ...

Retrieve the city ID from an AJAX call that populates a dropdown menu with cities, and pass it back

My registration form on the website requires users to provide various details for registration. Among these elements, there are two select boxes for users to choose their district and city. To achieve this functionality, I have implemented an AJAX feature ...

Issue with Google Charts where the label does not show outside of the bar if the bar is too small

I am encountering an issue with my Google Bar Chart where the bar label is not displaying outside of the bar when it is too large to fit inside. This behavior should be the default, but my charts are not working as expected. The problem can be seen in rows ...

Unable to access the data once CORS is disabled

After enabling cors, I successfully loaded the data. However, when I disabled it, I encountered issues retrieving the data. Is there a way to bypass this without turning on cors? An error message I received is: createHttpLink.js:96 Refused to connect to & ...

Attempting to resolve the Bootstrap issue, currently in search of a suitable solution

Today I made the decision to utilize bootstrap to create a menu, but unfortunately, I've encountered a strange bug or conflict involving jQuery, potentially the UI, and Bootstrap. If you'd like, you can take a look at the picture provided in the ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

Retrieve the latest inserted ID in a Node.js application and use it as a parameter in a subsequent query

I am currently working with an SQL database that consists of two tables, namely club and players. These tables are connected through a one-to-many relationship. Although the query in my node.js code is functioning properly, I am facing an issue retrieving ...