Having trouble altering font-family, font-size, and font-weight with JavaScript?

Looking for a way to dynamically change textareas based on selections made in dropdown menus? Check out this JavaScript code snippet: http://jsfiddle.net/73udajhm/

The following is the JavaScript used:

$(function () {
    $("#fontsize").on('change', function () {
    $('.address').css('font-size', $(this).val() + 'px');
    });
});

$(function () {
    $("#fonttype").on('change', function () {
    $('.address').css('font-family', $(this).val());
    });
});

$(function () {
    $("#fontweight").on('change', function () {
    $('.address').css('font-weight', $(this).val());
    });
});

This is the HTML part of the code:

Font Size:
<select id="fontsize">
<option>-</option>
<option value="24">24</option>
<option value="16">16</option>
</select>

<br />Font Type:
<select name="fonttype">
<option>-</option>
<option value="verdana">Verdana</option>
<option value="arial">Arial</option>
</select>

<br />Font Weight:
<select id="fontweight">
<option>-</option>
<option value="bold">Bold</option>
<option value="regular">Regular</option>
</select>

<div>
<textarea id="label" class='address'>Hello 123</textarea>
<textarea class='address'>Hello 123</textarea>
</div>

Answer №1

It is possible to condense this into a single function by making adjustments in the html and js code. This involves setting the id of an element as a property to be set in the css, replacing regular with normal in the fontFamily element, and using RegExp.prototype.test() to verify if there is a digit in the value of the element before returning either the length value including "px" or a string of the select value when setting the css.

html

Font Size:
<select name="fontSize" id="fontSize">
    <option>-</option>
    <option value="24">24</option>
    <option value="16">16</option>
</select>
<br />Font Type:
<select name="fontFamily" id="fontFamily">
    <option>-</option>
    <option value="verdana">Verdana</option>
    <option value="arial">Arial</option>
</select>
<br />Font Weight:
<select name="fontWeight" id="fontWeight">
    <option>-</option>
    <option value="bold">Bold</option>
    <option value="normal">Normal</option>
</select>
<div>
<textarea id="label" class='address'>Hello 123</textarea>
<textarea class='address'>Hello 123</textarea>
</div>

js

$(function () {
    $("[id^=font]").on("change", function () {
       $(".address")
       .css(this.id, /\d/.test(this.value) ? this.value + "px" : this.value);
    });
});

View the demonstration on jsfiddle here.

Answer №2

Make sure to review your coding thoroughly.

The style isn't displaying correctly because you used name instead of id in the font type selector.

Additionally, change regular to normal for the font-weight property.

Answer №3

Here is what I believe to be the most organized version:

$(function() {
  $("select").on('change', function() {
    var $property = $(this).attr('name');
    var $value = $(this).data("sufix") ? $(this).val() + $(this).data("sufix") : $(this).val();
    $('.address').css($property, $value);
  });

});
Font Size:
<select name="font-size" data-sufix="px">
  <option>-</option>
  <option value="24">24</option>
  <option value="16">16</option>
</select>
<br />Font Type:
<select name="font-family">
  <option>-</option>
  <option value="Verdana">Verdana</option>
  <option value="Arial">Arial</option>
</select>
<br />Font Weight:
<select name="font-weight">
  <option>-</option>
  <option value="bold">Bold</option>
  <option value="normal">Normal</option>
</select>
<div>
  <textarea id="label" class='address'>Hello 123</textarea>
  <textarea class='address'>Hello 123</textarea>
</div>

Cheers!

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

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...

Create a basic cache within an AngularJS service to store data retrieved from HTTP requests, ensuring that the cache returns an object

Looking to implement a simple caching mechanism in an AngularJS service for data retrieved from HTTP requests. The goal is to always reference the same object to avoid duplicating requests. Below is an example code snippet showcasing the issue at hand. Li ...

Customizing the appearance of all Angular components with styles.scss

Is there a way to create a universal style in styles.scss that can be applied to all Component selectors (e.g. app-componentA, app-componentB ...)? I understand that I could manually add the style to each selector, but I am concerned that it may be forgot ...

Issues with rendering in Next.jsORErrors encountered during rendering

Encountering errors while attempting to build my page using "Yarn Build" Automatically optimizing pages ... Error occurred prerendering page "/design/des". More details: https://err.sh/next.js/prerender-error: Error: Cannot find module './des.md&apos ...

Issue with function not getting triggered upon ng-click event binding

Having trouble getting a button to call the getFilteredRows() function in my MVC app's view and controller. I've tried various combinations, but the button just won't trigger the function. Can anyone help me figure out why? @using ProjectEx ...

How to retrieve the index of a nested ng-repeat within another ng-repeat loop

On my page, there is an array containing nested arrays that are being displayed using ng-repeat twice. <div ng-repeat="chapter in chapters"> <div ng-repeat="page in chapter.pages"> <p>Title: {{page.title}}</p> </d ...

Unlocking the Power of NextJS Keyframes

After successfully creating a background with 3 images using keyframes in my initial project built with html and css, I decided to recreate the project using NextJS. However, I encountered an issue where the third image does not display in NextJS. Instead ...

With vuejs, only one place can control the changing of v-model

Hello, I am currently working on integrating VueJS2 code with Laravel Blade. However, I have encountered an issue with the following VueJS2 code: new Vue({ el:'.add_item_to_price_menu', data:{ percentage:null, }, methods: ...

"Exploring the technique of extracting substrings in JavaScript while excluding any symbols

I am working on a JavaScript web network project and I need to use the substring method. However, I want to exclude the colon symbol from the substring because it represents a hexadecimal IP address. I do not want to include colons as part of the result. H ...

Is there a way to transform a local array into remote JSON data?

I am attempting to retrieve an array from a remote server that is connected to a dynamic database. From what I have gathered on Ionic forums, it seems that I need to utilize the $http function from AngularJS. However, since I am new to AngularJS, the curr ...

What is the process of compiling a Vuejs single file component?

Seeking assistance with Vuejs 2 (webpack-simple template) - I am looking for a way to compile my template before rendering it. Below is the code snippet in question: App.vue <template> <div id="app"> <h1>{{ msg }}</h1> ...

The statusText variable for getXMLHTTP object is not found when the status is not equal to

Earlier, I posted about this issue before isolating the problem. Now that I have isolated it, I wanted to repost with a clearer focus on the two functions causing the problem. Whenever I update my State, it triggers the getCity function. The call is being ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Ensure that each row in the grid expands to occupy all remaining space, with the option to scroll if additional space is required

Looking to have a grid item expand to fill 100% of available space, but also scroll if it exceeds that space. Here's an example scenario where I'm having trouble with the CSS line marked: '/* DOESN'T WORK */' when attempting to s ...

Error: An uncaught SyntaxError has occurred due to a missing closing parenthesis after the

I encountered an error saying "Uncaught SyntaxError: missing ) after argument list" at the end of this line. I have double-checked the parentheses, but still can't figure out what the issue might be. <input type="button" class="b ...

Is there a way to determine the quantity of items within a sortable div?

In my HTML document, there are multiple divs containing smaller divs that can be rearranged within each other. Upon loading the document, a random assortment of these smaller divs are added to #boxtop. Below is a snippet of my HTML code: <html> &l ...

Changing the state using setState outside of the component does not trigger an update

My shop is situated within the store.js file like all the other Zustand stores: const retryStore = create(set => ({ retry_n: 0, setGRetry: (retry_n) => set(state => ({ ...state, retry_n, })), })); export { retryStore }; ...

Is it possible that Ajax.IsAjaxRequest() never returns true?

There seems to be a problem with the code "if(Request.IsAjaxRequest())" in the controller class as it always returns false for me. I need some assistance in understanding why this is happening. Interestingly, when I use ajax.beginform in my cshtml file wit ...

Resolving problems with jQuery auto-populating select dropdowns through JSON data

I am facing an issue with auto-populating a select dropdown using jQuery/JSON data retrieved from a ColdFusion CFC. Below is the code snippet: $(function(){ $("#licences-add").dialog({autoOpen:false,modal:true,title:'Add Licences',height:250,wid ...