Leveraging the power of Javascript to trigger 2 functions when a button is clicked

After receiving great answers to my previous questions, I am in search of more valuable insights.

The challenge at hand involves 9 buttons on a webpage with text inputs. Upon clicking a button, the text entered by the user is supposed to be transferred to another text box while also changing the color of the clicked button.

Here's a snippet of my HTML setup:

<input id="fbvalbox" type="text" placeholder="Your personal message" />
<input id="butval1" class="butz" type="button" name="design1" value="Choose Design" onclick="changeID(this);" />

This code represents one text box and a button. The goal is to move the entered message from this box to another designated box.

<input id="design_choice" type="text" value="" />

For the JavaScript part, here's the function responsible for transferring the message:

window.onload = function(){
    document.getElementById('butval1').onclick = function(){
    document.getElementById('design_choice').value = document.getElementById('fbvalbox').value;   
}

While the transfer works flawlessly, the challenge lies in changing the button color upon click. A separate JavaScript file has been included for this purpose but integrating both functionalities has proven to be tricky.

function changeID(elm){
    var NAME = elm;
    var currentClass = NAME.className;
        if (currentClass == "butz") { 
            NAME.className = "butzz";   
        } else {
            NAME.className = "butz";  
        }

Although each function operates correctly individually, I seek assistance in executing both actions simultaneously when the button is clicked. Any guidance would be greatly appreciated.

Thank you.

Answer №1

If you're already using the jQuery tag, why not take advantage of a jQuery solution instead?

<input id="messageBox" type="text" placeholder="Your message here" />
<input id="chooseDesignBtn" class="buttonStyle" type="button" name="design1" value="Select Design" />
<input id="chosenDesign" type="text" value="" />

Then:

function toggleButtonClass(element) {
    $(element).toggleClass('buttonStyle newButtonStyle')
}

jQuery(function($){
    $('#chooseDesignBtn').click(function(){
        $('#chosenDesign').val($('#messageBox').val())
    })
})

jQuery(function($){
    $('#chooseDesignBtn').click(function(){
        toggleButtonClass(this)
    })
})

Check out the demo: Fiddle

Answer №2

Give this a shot:

function modifyElementID(element){
    document.getElementById('design_choice').value = document.getElementById('fbvalbox').value;
var NAME = element;
var currentClass = NAME.className;
    if (currentClass == "butz") { 
        NAME.className = "butzz";   
    } else {
        NAME.className = "butz";  }
}

VIEW DEMO FIDDLE

DISCLAIMER: Adjust the textbox id's to fit your needs. Consider using jQuery for a more streamlined solution, as recommended by Arun P Johny.

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

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Error: Unable to access the value property because it is undefined (d is not defined)

I have tested out various versions of the react datepicker, but unfortunately, none of them worked for me. In case more code is needed, you can find it in the repository here: https://github.com/RodrigoAN97/revents Thank you. import React from 'reac ...

What is the functionality of the "respond_with_navigational" feature?

Currently, I am integrating Devise and DeviseInvitable to handle authentication in my application. However, I'm facing challenges when trying to incorporate AJAX functionality into InvitationsController#update. The structure of the controller in Devis ...

What is the best way to transfer state information from a hook to be displayed in the App component in React

Is there a way to transfer the state(data) of info to the App hook, in order to showcase the properties within div elements? The function setInfo(info) saves the data intended for display on the Map hook and inspecting console.log(info) within _onClick rev ...

Strategies for sending arguments to a TypeScript function from an HTML document

When I fetch my list of users as a JSONArray, I want to display the data of each user when their name is clicked. However, I am encountering difficulty passing the user's ID into the function. <ng-container *ngFor = "let user of users"> ...

How can I include multiple search forms on a single page in TYPO3 Ke_Search without any conflicts between them?

In the header of my website, I have a search form that is generated as a cObject from a content element containing a ke_search searchbox. When this form is submitted, it redirects to a /search page. In addition to this, I have subpages that are meant to se ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

The art of adjusting list padding and margin to fit varying screen sizes

When dealing with Roman numerals in lists, the width of the numeral can vary significantly from one <li> to another. For example, you may have II next to XVII. I am struggling to find the perfect padding for lists to ensure that wide "bullets" do n ...

Using ES6 Babel with multiple package.json files

For a large project, I am looking to break it down into multiple package.json files. This way, the dependencies for each part can be clearly defined and exported as separate entities. However, my goal is to compile all of these packages using webpack and ...

Disabling GPS with HTML5/phonegap: A step-by-step guide

Looking to create a function that can toggle GPS on and off for both iPhone and Android devices ...

Angular 5 combined with Electron to create a dynamic user interface with a generated Table

I am working on an Angular Pipe: import {Pipe, PipeTransform} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import * as Remarkable from 'remarkable'; import * as toc from 'markdown-toc&a ...

Tips for storing multiple pieces of text in HTML5 local storage

I have been working on creating functions and input boxes within a table to display data upon page reload. However, I am encountering difficulties in understanding how to store multiple inputs in local storage and then loop through them to show all the d ...

The navigation bar scrolling based on mouse position lacks smoothness and could use some enhancement

I'm currently working on adjusting the navigation bar based on the mouse position. It seems to be functioning, but I'm facing an issue with smoothing out the animation. When I stop moving the mouse to a certain point, there is a delay i ...

The HTML is not rendering as planned

I have 2 files, test.html <!DOCTYPE html> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="./test/jquery.min.js"></script> </head> <body> ...

Trouble with getTime() function functionality in Chrome browser

My JavaScript code is functioning properly in IE and Firefox. Take a look: var dt = new Date("17/05/2012 05:22:02").getTime(); However, when I try to run it in Chrome, the value of dt turns out to be NaN. I've been troubleshooting but can't see ...

Reveal or conceal the footer section as you reach the end of the webpage

My webpage layout consists of a fixed nav-bar at the top, a drop down sidebar, a <div> element with an id of content, some content inside the <div>, and a bottom <div> with a fixed position. I am trying to hide the bottom <div> whe ...

What is the best way to implement a third-party library that utilizes an outdated import method in Angular 4.x?

Can anyone guide me on how to include the mathjs library in Angular 4.0 and use it within a component? Here are the steps I've taken so far: yarn add mathjs I believe there should be a method for injecting JS libraries during one of the build lifec ...

The Antd Tooltip becomes unresponsive when a component is clicked and moved

Having an issue with a button that has an Antd tooltip, here is the setup: <Tooltip title="Some text"> <button onClick={openNotes}><Icon icon="notes" /></button> </Tooltip> Upon clicking the button, the ...

How can you protect your webhook from unauthorized access?

I am looking to create a webhook that will update the status of a document in my collection, triggering additional events in the process. Router.route('/mandrill/invitation_sent', { where: 'server' }) .post(function () { var resp ...

Attempting to grasp the concept of ES6 Promises by running three setIntervals consecutively

To gain a better grasp of ES6 Promises, I decided to tackle this particular challenge: There are three divs: div.red, div.green, and div.blue. They need to be displayed sequentially, each with a gradual increase in opacity through an async task using setI ...