What is the best way to swap out an icon based on the chosen option?

Here is my code:

$('#mySelect').on('change', function() {
  var value = $(this).val();
  $(".title").html(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>


<span class="icon"><i class="fa fa-check-square"></i>&nbsp;&nbsp;
<span class="title"> Title </span>
<br /><br />
<select id="mySelect">
  <option value="" selected disabled hidden>Choose a social media</option>
  <option value="Telegram" >Telegram</option>
  <option value="Instagram">Instagram</option>
  <option value="Facebook">Facebook</option>
  <option value="GooglePlus">GooglePlus</option>
</select>

All I'm trying to do is also changing that icon. I mean I have an array contains needed class names:

var classes = {Telegram: "fa-telegram", Instagram: "fa-instagram", Facebook: "fa-facebook-square", GooglePlus: "fa-google-plus-square"};

I want to change the class of that i (which is into span.icon) based on the selected option. How can I achieve this?

Answer №1

To update the icon, first remove any existing classes and then add the new classes using the following code:

// Remove current icon.
$("#socialIcon i").attr("class","");

// Set the new icon.
$("#socialIcon i").addClass("fa");
$("#socialIcon i").addClass(classes[value]);

Make sure to assign an ID "socialIcon" to the span containing the icon for easy identification.

var classes = {Telegram: "fa-telegram", Instagram: "fa-instagram", Facebook: "fa-facebook-square", GooglePlus: "fa-google-plus-square"};

$('#mySelect').on('change', function() {
  var value = $(this).val();
  $(".title").html(value);
  
  // Remove current icon.
  $("#socialIcon i").attr("class","");

  // Set the new icon.
  $("#socialIcon i").addClass("fa").addClass(classes[value]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span id="socialIcon" class="icon"><i class="fa fa-check-square"></i>&nbsp;&nbsp;
<span class="title"> Title </span>
<br /><br />
<select id="mySelect">
  <option value="" selected disabled hidden>Choose a social media</option>
  <option value="Telegram" >Telegram</option>
  <option value="Instagram">Instagram</option>
  <option value="Facebook">Facebook</option>
  <option value="GooglePlus">GooglePlus</option>
</select>

Answer №2

Consider using the $.prop() method to reset the entire icon set.

var classes = {
  Telegram: "fa-telegram",
  Instagram: "fa-instagram",
  Facebook: "fa-facebook-square",
  GooglePlus: "fa-google-plus-square"
};
$('#mySelect').on('change', function() {
  var value = $(this).val();
  $(".title").html(value);
  $('.icon').find('i').prop('class', 'fa ' + classes[value]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />


<span class="icon"><i class="fa fa-check-square"></i>&nbsp;&nbsp;
<span class="title"> Title </span>
<br /><br />
<select id="mySelect">
  <option value="" selected disabled hidden>Choose a social media</option>
  <option value="Telegram" >Telegram</option>
  <option value="Instagram">Instagram</option>
  <option value="Facebook">Facebook</option>
  <option value="GooglePlus">GooglePlus</option>
</select>

Answer №3

Perhaps this solution will be beneficial

 var classes = {Twitter: "fa-twitter", LinkedIn: "fa-linkedin", Pinterest: "fa-pinterest-square", GitHub: "fa-github"};
$('#mySelect').on('change', function() {
   var value = $(this).val();
   var icon = classes[value];
   $('span.icon').find('i').attr('class', '');
   $('span.icon').find('i').addClass('fa '+classes[value]);
   $(".title").html(value);
});

Answer №5

Here's another approach you could consider.

let socialMediaClasses = 
{Twitter: "fa-twitter", Snapchat: "fa-snapchat", LinkedIn: "fa-linkedin-square", Pinterest: "fa-pinterest"};

$('#mySelect').on('change', function() {
  let chosenValue = $(this).val();
  $(".title").html(chosenValue);  
  $("#socialIcon i").attr("class","fa "+socialMediaClasses[chosenValue]);
});

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 bookmarklet compatibility on mobile browsers like iOS and Android

Here is the bookmarklet code I have: javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js";c.onload=c.onreadystate ...

Utilizing JQuery to ensure that rows have consistent height in two dynamically generated tables

To meet my specific requirements, I am tasked with creating two separate tables that will contain the same number of rows but different data. The first table will display Item Information, while the second table will provide consolidated information about ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

The generation of the npm bin script is not working as expected on Windows operating systems

I'm working on developing an NPM package for command line use. I've set up npm's bin in my package.json to specify the JS file to be executed. Here is a snippet from my package.json: "name": "textree", "bin": { "textree": "./src/cli.js" ...

Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to pla ...

What can be done to improve the elegance of this jQuery function?

I am facing an issue on my webpage where I have a drop-down select box with a default value of (empty). The problem arises when the user selects an entry, and the appropriate form for that entry type should be displayed. However, there are a couple of iss ...

Tips for displaying videos with sound when the autoplay has been successfully implemented, but the audio is not working

I've been working on creating a video player with autoplay functionality, but I'm facing an issue with the sound not playing. Here's what I currently have in my code, but it's not behaving as expected: var myaudio = docum ...

Troubleshooting: Why isn't my jQuery Click Event functioning in Mozilla but working perfectly fine in

While I know this question has been asked before, I can't seem to locate the posts I remember reading about it. I apologize for any duplication, but I am trying to implement a "click anywhere BUT here to close element overlay" effect on my personal we ...

How can I verify if an SVG file has a reliable source? (having troubles converting SVG to canvas)

While attempting to use an SVG generated by a chart plugin (https://wordpress.org/plugins/visualizer/), I am facing issues retrieving the source of the SVG-image being created. Interestingly, when using other SVGs with the same code, everything works perfe ...

Tips for looping through each cell in a column of a DataTable to verify its content

I have a table generated using the jquery DataTables API. One of the columns displays word frequencies for each word in the table. If a frequency is less than 40, I want to change that cell to display "unranked" instead of the actual number. How can I ite ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

Incorporate a new class for every date within the range of start and end

I have incorporated a JQuery event calendar plugin into my project, sourced from this specific website. Within my events, there are distinct start and end dates. Currently, I have managed to display green squares on the calendar for both the start and end ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Experience interactive video playback by seamlessly transitioning a webpage video into a pop-up when clicking on an

I want to have a video play as a pop-up when the user clicks a play button, while also fading out the background of the page. It should be similar to the way it works on this website when you click to watch a video. How can I achieve this? <div class=" ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

How can I trigger an audio element to play using onKeyPress and onClick in ReactJS?

While attempting to construct the Drum Machine project for freeCodeCamp, I encountered a perplexing issue involving the audio element. Despite my code being error-free, the audio fails to play when I click on the div with the class "drum-pad." Even though ...

Time taken to execute all the tests using the karma runner

We have recently transitioned to running unit tests remotely using browserstack across multiple browsers and operating systems with the help of the karma-browserstack-launcher plugin. The current output of our test run appears as follows: $ grunt unit:re ...

The priority of custom attributes in HTML

There seems to be some ambiguity regarding whether data- attributes should be considered primary or secondary syntax. Is there a defined standard for this in major frameworks like Angular? For example, if an attribute is specified as both my-attr and dat ...

How to Eliminate Lower Borders from DataGrid Component in Material UI (mui)

I've been trying to customize the spacing between rows in a MUI Data Grid Component by overriding the default bottom border, but haven't had much success. I've experimented with different approaches such as using a theme override, adding a c ...

Ways to align the navigation icon to the left side

I need help positioning my help icon at the bottom of the screen, regardless of the user's monitor size. I've tried using margin and margin-top, but it doesn't adjust properly when changing monitor sizes. Any suggestions or assistance would ...