Toggle between bold and original font styles with Javascript buttons

I am looking to create a button that toggles the text in a text area between bold and its previous state. This button should be able to switch back and forth with one click.

function toggleTextBold() {
  var isBold = false;
  if (isBold) {
    // Code to unset text as bold
  } else {
    // Code to set text as bold
  }
}
<button onclick="toggleTextBold()">TOGGLE BOLD</button>


<form>
  Enter Text:
  <br>
  <input type="text" name="your text" id="entertext">
</form>

Answer №1

If you want to achieve this effect, Jquery can help you out

Form Section

<button class="toggleStyle">TOGGLE</button>
<form>
  Input Text:
  <br>
  <input type="text" name="userInput" id="textInput">
</form>

Jquery Script

$(".toggleStyle").click(function() {
   document.getElementById("textInput").classList.toggle("style");
});

CSS Styling

.style { font-style: italic; }

Answer №2

To make text bold, you can create a class specifically for bold formatting and then apply or remove that class from the text element as needed.

Avoid using HTML event attributes to attach event handlers to DOM objects because:

  • They result in messy code that is difficult to read and often leads to redundant code.
  • They introduce global wrapper functions around your custom function, affecting the binding of this within the event handling function.
  • They do not adhere to the standards outlined in the W3C DOM Event specification.

It's recommended to handle all event bindings in JavaScript and utilize the .addEventListener() method.

// Access DOM elements
var btn = document.getElementById("btnToggleBold");
var txt = document.getElementById("txtInput");

// Listen for button click event and toggle bold class on text element
btn.addEventListener("click", function(){
  txt.classList.toggle("bold");
});
/* This class will be toggled when the button is clicked */
.bold {font-weight:bold; }
<form>
  <div>
    <button id="btnToggleBold">BOLD</button>
  </div>
  <div>
    Enter Text:
    <br>
    <input type="text" name="txtInput" id="txtInput">
  </div>
</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

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...

I'm facing a MongooseServerSelectionError: when trying to connect to 127.0.0.1:27017. Despite trying all the solutions provided on StackOverflow, the issue persists

MongooseServerSelectionError: Failed to connect to 127.0.0.1:27017 at NativeConnection.Connection.openUri (/mnt/d/Ecommerce/node_modules/mongoose/lib/connection.js:802:32) at /mnt/d/Ecommerce/node_modules/mongoose/lib/index.js:341:10 at ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

Filtering with multiple attributes in Angular using GroupBy

I have a set of JSON data structured like this: [ { "id": 1, "address": "MG Road", "country": INDIA, "state": AP, "city": VIJ }, { "id": 2, "address": "Miyapur", "country": INDIA, ...

Creating a unique design for a CSS menu with distinct section dividers and stylish onHover effects

Hey there! I'm currently working on a new menu design using UL and LIs elements. I would really appreciate some advice on how to add lines after each LI and properly indent them with the specific bullet image I have chosen. If you're interested ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

Having difficulty retrieving the value of a dynamically selected radio button in AngularJS

Having trouble with selecting radio options in my code, need some assistance to fix it. Check out my Plnkr Code - http://plnkr.co/edit/MNLOxKqrlN5ccaUs5gpT?p=preview Although I am able to retrieve names for the 'classes' object, the selections ...

Customizing the step function of HTML5 input number with jQuery: A guide

Is there a way to modify the step value in HTML5 number inputs for my web application? I would like it to increment and decrement by 100 instead of 1. I attempted the following approach: $("#mynumberinput").keydown(function(e){ if (e.keyCode == 38) / ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

Guide on grabbing characters/words typed next to # or @ within a div element

Within a div element, I have enabled the contenteditable property. My goal is to capture any text input by the user after typing '#' or '@' until the spacebar key is pressed. This functionality will allow me to fetch suggestions from a ...

Navigating through a nested array within a JSON object using Vue.js - a guide

I have a JSON data array that includes outer and inner subarrays. My goal is to loop through both levels and create a table. Below you'll find a snippet of the sample array: { class:'I', subDdiv:[ { ...

Use the $.get() method in JavaScript to send a parameter to my controller function

My objective is to showcase the event details in a modal. To achieve this, I am running a JavaScript script that calls the "GetEventsDetails" method in my "Event" controller with the event ID. While debugging in Chrome, I can see the ID being passed corre ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

The text is not appearing properly in an HTML file due to issues with

Hi trying to display the text received from the controller's scope. Here's what I have attempted: HTML: <div ng-repeat="item in sResults"></div> Controller JavaScript: $scope.sResults = []; function App( ){ var Label ...

Building Effective Web Designs with Bootstrap and Semantic Grid System

There are several ways to effectively organize and maintain the Bootstrap Grid. For example: <div id='header'> <div class='row'> <div class='col-md-6 header-left'> or <div id='header&ap ...

List of recommended countries with their respective flags and descriptive text

I am currently working on creating a country suggestion list that includes flags next to the selected result. While I have been successful in generating the suggestion box based on the country names, I am looking to enhance it by displaying the respective ...

Sending information through a form via a POST request after clicking on a hyperlink

I am attempting to submit a form using POST by clicking on a link and passing some hidden values. This is the code I'm currently using: $( document ).ready(function() { $('a#campoA').click(function() { $.post('testForm2.php', { ...

The Npm generate script is failing to create the necessary routes

I've integrated vue-router into my nuxt project, but I encountered an issue when running npm run generate - it generates everything except for my pages. I suspect the problem lies with the router implementation as I didn't face any issues before ...