Show the user's input within a clickable button

I'm trying to create a functionality where I have an input field and a button next to it. When I type something in the input field and click on the button, I want the result to be displayed in another button. Here is what I have attempted so far:

function add_keyword() {
  var keyword_value = (document.getElementById("keyword").value);
  var result = keyword_value;

  document.getElementById("btnresult").value = result;
}
#btnresult{
  display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>

<div class="input-group">
  <input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>

<button type="button" id="btnresult" class="btn btn-default">Result will show here</button>
    

Answer №1

Check out this link for more details

It seems like the solution you are looking for...

Here is a simplified version of the code snippet:

<div class="container">
  <input type='button' value='Click Me' data-action='add' /><br>
  <input type='text' data-input='text' />
</div>

<ul class='list-buttons' data-list='buttons'>
  <!-- where should these buttons go? -->
</ul>


The original question included jQuery as one of the tags, so I incorporated it into the solution

// caching elements for reuse
var $container = $('.container');
var $clickButton = $container.find('[data-action="add"]');
var $textInputField = $container.find('[data-input="text"]');

var $buttonList = $('[data-list="buttons"]');

$clickButton.on('click', function() { 
  var inputValue = $textInputField.val(); 
  $buttonList.append('<li><button>' + inputValue + '</button></li>'); 
  $textInputField.val(''); 
});

Answer №2

You're on the verge of success, just remember to reveal the button you initially hid and update the innerHTML property instead of setting a value for the button. Buttons display text between their tags, not values.

Here are the changes I made:

function add_keyword() {
    var keyword_value = (document.getElementById("keyword").value);
    var result = keyword_value;
    // Changed from .value to .innerHTML
    document.getElementById("btnresult").innerHTML = result;
    // Changed style display to 'block'
    document.getElementById("btnresult").style.display = "block"
}
#btnresult{
    display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
    <input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
    

Furthermore, there are areas in your code that could use enhancement, as described below:

function add_keyword() {
    // No need for parentheses around the document.getElement function.
    var keyword_value = document.getElementById("keyword").value;
    // You can directly assign the value without creating a new variable, but it's good practice to store elements in variables for reuse.
    var btn = document.getElementById("btnresult");
    btn.innerHTML = keyword_value;
    btn.style.display = "block"
}

EDIT: To meet OP's objective of creating a new button with the input content, here is an updated version that generates a new button for each input.

function add_keyword() {
    var keyword_value = document.getElementById("keyword").value;
    // Create a new button element.
    var btn = document.createElement("button");
    // Set its content to the keyword from the input.
    btn.innerHTML = keyword_value
    // Append it to the body.
    document.body.appendChild(btn);
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
    <input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>

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

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

Guide to implementing a DataTable in MVC4 UI using jQuery

Looking to set up a DataTable using jQuery similar to the one shown in this image: https://i.stack.imgur.com/DNUcd.png I'm not very comfortable with jQuery, so please be patient and avoid asking me what I've tried. I don't know how to stru ...

Is it possible to execute a function within an HTML page simply by clicking on it?

As someone who is new to the world of HTML, CSS, and JS, I'm currently facing a challenge: On my website's page1.html, I have implemented a feature that allows users to sort different articles on the page by selecting a sub-menu from the navigat ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

What is the method for producing an li and anchor tag using a list object?

Here is the response I received from my web service, and now I need to transform it into a list item tag: {"d":[{"name":"ttt","url":"bbbb"},{"name":"uuu","url":"ppp"}]} How can I create li tags based on the above output? This is the desired format for t ...

Disable browser autocomplete for Material-UI TextField

I am currently using Material UI version 0.20.0 and I am facing an issue where I need to prevent the password from being saved for a user in a TextField. I tried adding props to the TextField with autocomplete='nope' since not all browsers suppor ...

What is the best way to utilize this resulting value as an input?

I am trying to generate a random number using math.random and use that value in the following script: let bday = Math.floor( Math.random() * (30 - 1 + 1) + 1 ); await test.page.select('select[name="day_select"]',bday); However, I am ...

The margin-bottom property does not cause the element to shift or re

Need help with creating a 3-line effect using div and before/after selectors. When applying margin-top in the after selector, the line moves down properly. However, when trying to move the line up using margin-bottom in the before selector, it's not w ...

How can I delete the global styles defined in _app.js for a particular component in Next.js?

While working with NextJs and TailwindCSS, I encountered an issue where all the extra styles in my globals.css file were causing some trouble. Although it is recommended to import it at the top level in the _app, I tried moving it down to the "layout" comp ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

A website with two distinct pages, where only the first page is refreshed

I have split the content of my HTML page into 2 separate subpages, based on the references provided below: Multiple distinct pages in one HTML file This is how my code is structured: ... <script> function show(shown, hidden) { document.getEle ...

The framework of AngularJS modules

As I delve into structuring multiple modules for our company's application, I find myself at a crossroads trying to design the most optimal architecture. Research suggests two prevalent approaches - one module per page or a holistic 'master' ...

Incorporating an SVG Element into a design while ensuring its responsive functionality

I tried adding an SVG wave type picture to my background and making it responsive, but encountered some issues. I wanted to enhance the look of my existing background image by incorporating a wave design. However, when I zoomed in on the website, the new a ...

What is the best way to incorporate async and await into my functions within a Node.js environment?

I attempted to implement asynchronous functionality into my code, however, I encountered some difficulties. What steps should I take next? Below are the functions in question: 1. router.post('/urls', (req, response) => { count = 2; webUrl ...

UI-Select fails to display the already selected value

Does anyone have a solution for binding a UI-Select control to a Class[] list? The filling up part works fine, but I'm having trouble getting the selected item to display. Any suggestions on how to fix this? Below is my ui-select code: <ui-select ...

Managing touch devices and animations when hovering

Is there a way to remove or prevent all hover effects on a touch device? I've tried various scripts, but none seem to work for me. How can I test it with dev tools? I attempted this script but received an error: Cannot read property 'addEventList ...

Experiencing issues with the redirect button on the navigation bar of my website

Video: https://youtu.be/aOtayR8LOuc It is essential that when I click a button on my navigation bar, it will navigate to the correct page. However, since the same nav bar is present on each page, it sometimes tries to redirect to the current page multiple ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Leveraging Javascript to generate universal HTML content for various Javascript files

Present Situation: I have a timesheet feature that enables users to input their leave, TOIL, and sick days along with the respective hours. Additionally, there is a table that dynamically adds a new row every time the plus button is clicked using the foll ...