Ways to enable JavaScript code to accept input from both a text field and a text

I have a JavaScript code that allows users to input text and choose to make it bold, italicized, or underlined. For example, if the user checks the bold option, the text will appear in bold format. Here is the JavaScript code I am using:

$('input[name="textStyle"]').change(function(){
        if ($(this).val() == 'bold'){
            if ($(this).is(':checked')) $('input[name="styledText"]').css('font-weight', 'bold');
            else $('input[name="styledText"]').css('font-weight', 'normal');
        }
        else if ($(this).val() == 'italic'){
            if ($(this).is(':checked')) $('input[name="styledText"]').css('font-style', 'italic');
            else $('input[name="styledText"]').css('font-style', 'normal');
        }
        else if ($(this).val() == 'underline'){
            if ($(this).is(':checked')) $('input[name="styledText"]').css('text-decoration', 'underline');
            else $('input[name="styledText"]').css('text-decoration', 'none');
        }
    });
body {
    background-color: #5f5959;
    color: #000000;
}
textarea[type=text], select {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

textarea[type=submit] {
  width: 100%;
  background-color: #f9f9f9;
  color: 000000;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

textarea[type=submit]:hover {
  background-color: #908989;
}

div {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}
<form style="font-family: 'Poppins', sans-serif; color: #f9f9f9;">
    Bold:<input name="textStyle" type="checkbox" value="bold"/>
    <br>
    Italic:<input name="textStyle" type="checkbox" value="italic"/>
    <br>
    Underline:<input name="textStyle" type="checkbox" value="underline"/>
</form>

<div style="margin-left: 240px; width: 1000px; height: 665px;">
    <p><center style="font-family: 'Poppins', sans-serif; font-size: 13px;">When submit, your text will clear and your blog will be published!</center></p>
    <textarea type="text" placeholder="Title" style="font-family: 'Poppins', sans-serif;"></textarea>
    <form style="font-family: 'Poppins', sans-serif;">
        <textarea name="styledText" type="text" style="font-family: 'Poppins', sans-serif; border-width: 2px; border-style: solid; outline: none; border: none; height: 445px;"></textarea>
        <input style="height: 50px; width: 1000px; font-family: 'Poppins', sans-serif; border-radius: 7px;" value="Submit" type="submit">
    </form>
</div>

I encountered an error while trying to apply these styles to my text. It seems like the JavaScript code only works for input fields but not for textarea elements. Is there a way to modify the code so it can work with both? I want the large blank area to accept user input and display it as bold, italicized, or underlined. Thank you!

Answer №1

To begin with, instead of using

$('input[name="styledText"]')
, switch to
$('textarea[name="styledText"]')
. Additionally, the jquery .css method also accepts an object as input. Therefore, create an object named cssProps and include default properties within it. Next, upon toggling the checkbox, update the values of these keys accordingly. Finally, at the end, apply the styles using .css by passing in the cssProps properties.

let cssProps = {
  'font-weight': '',
  'font-style': '',
  'text-decoration': ''
}

$('input[name="textStyle"]').change(function() {
  const val = $(this).val()
  if ($(this).is(':checked')) {
    switch (val) {
      case 'bold':
        cssProps['font-weight'] = 'bold';
        break;
      case 'italic':
        cssProps['font-style'] = 'italic';
        break;
      case 'underline':
        cssProps['text-decoration'] = 'underline';
        break;
    }
  } else {
    switch (val) {
      case 'bold':
        cssProps['font-weight'] = '';
        break;
      case 'italic':
        cssProps['font-style'] = '';
        break;
      case 'underline':
        cssProps['text-decoration'] = '';
        break;

    }
  }
  $('textarea[name="styledText"]').css(cssProps)
});
CSS styles...
Javascript & HTML code...

Answer №2

$('[name="styledText"]')
can be used to target all elements with the attribute name="styledText"

Answer №3

Could you kindly review the code snippet provided below? It should be suitable for your needs. We have opted to use the textarea element instead of input in our JavaScript code since you have indicated that a textarea is being used as a field.

For more details, please visit: https://jsfiddle.net/yudizsolutions/o1msuL83/

Answer №4

Check out the link below for more information. I've made a slight modification to your HTML code

<textarea type="text" name="styledText" placeholder="Title" style="font-family: 'Poppins', sans-serif;"></textarea>
. Additionally, I have targeted the name attribute using
$('[name="styledText"]')
.

https://codepen.io/Umesh8965/pen/jOymyLo

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

Issue with Mongoose $in operator causing updates to only affect a single document

Having some issues with the "$in" operator in Mongoose. I have a User schema that includes an array of Card schema. The Card schema contains a 'score' field that I want to update based on a list of Card ids. Here's what I have attempted: Us ...

Use jQuery's change method to initiate a hidden file input

Want to create a fake file input using an anchor tag and trigger the hidden file input with jQuery? Looking for some advice on how to make this happen. Check out my current attempt here. I'm not sure if I'm on the right track with this, so any g ...

What is the best way to align these Iframes in the center?

This is the html <div class="main_content"> <section class="episodio"> <article class="contenedor_episodios"> <h2>Episodios</h2> <div class="episodio_spotify" ...

What is the best way to implement a CSS Style specifically for a glyphicon icon when it is in keyboard focus?

I have a particular icon representing a checkbox that appears as a glyphicon-star. It is designed to display in yellow when focused on by the keyboard navigation. This feature is intended to help users easily identify their location on a page. However, an ...

Utilizing OrbitControls with SVGRenderer displays a pair of SVG elements positioned at opposite ends

In my project, I have created two scenes and two renderers. One scene is for a simple 3D mesh sphere, while the other is for an SVG circle. The SVG scene is positioned on top of the Mesh scene, acting as an overlay. Both the sphere and the circle are place ...

Cypress test never finishes when an unforeseen alert is triggered in the system during the test

When a web application unexpectedly throws an error using an alert box, the Cypress test becomes stuck indefinitely. The test will not complete or fail until the user manually closes the browser or clicks on the OK button within the alert box. https://i.s ...

Creating a visually engaging parallax effect in two columns with differing lengths that align perfectly at the conclusion

Recently, I came across an interesting layout technique on Apple's website that involves two columns with different lengths. As you scroll down the page, one column slows down to align with the other so that they both meet at the bottom. You can chec ...

How to make a Kendo Grid Combobox template or editor automatically set focus and select all text

I've been experimenting with using the combobox as either an editor or template for a column. The key difference is that one (the template) is always visible, while the other (the editor) is only displayed when the user edits a cell in the column. I&a ...

Packaging an Angular project without the need for compiling

In order to enhance reusability, I structured my Angular 6 Project into multiple modules. These modules have a reference to a ui module that contains all the style sheets (SASS) as values such as: $primary-text-color: #dde7ff !default; Although this app ...

Concealing forms within an Angular 5 application

I'm currently working on displaying the terms of use on the initial screen along with two buttons. If the user clicks the accept button, they will be directed to the authentication form. However, if they click refuse, the "Refused Terms" screen will a ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Dispatch is functioning properly, however the state remains unchanged

I'm currently developing an application that utilizes redux for state management. In a particular scenario, I need to update the state. Here is how my initial state and reducer function are set up: import { createSlice } from '@reduxjs/toolkit&a ...

Transform preexisting Vue UI library measurements into pixels

I was curious about converting all existing units (em / rem) to pixels. How can I easily convert the entire output units to px? Are there any tricks or methods available? Currently, I am utilizing Vuesax UI to create a plugin for various websites and temp ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Clicking on the prop in a React class component

This is the situation I am facing <List> {mainTags.map((mainTagItem) => { return ( <ListItem onClick={() => { setMainTag(mainTagItem.tag.tagId) }} button className={classes.mainTagItem}> <div className={classes. ...

Cors issue resolved: No 'Access-Control-Allow-Origin' error

I am currently working on a function that calls a web services API. function FetchData() { var parameters = { EVENT_CODE: EvnCode }; $.ajax({ url: 'http://00.00.00.000/CRM/getev ...

What are the various jQuery methods that can be utilized in the object parameter of a jQuery element creation request?

According to a post by John Resig on his website at http://ejohn.org/apps/workshop/adv-talk/#3, it is mentioned that methods can be attached using the object parameter. While 'text' appears to function correctly, any other content in the object ...

Transitioning from Backbone to AngularJS - What challenges can be expected?

Currently I am deep into a large Backbone project (around 8000 lines of JavaScript, not counting external libraries) and I am contemplating making the switch to AngularJS. At the moment, a significant portion of my code deals with DOM manipulation, event ...

Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available? import Feature from 'components/home/Fea ...

Execute a self-invoking JavaScript function with dynamic code

I'm facing a challenging problem that I just can't seem to solve... There's a function on another website that I need to use, but unfortunately, I can't modify it The code in question is: Now, I am looking to add a prototype "aaa" to ...