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

Protractor quickly launches and closes the Chrome browser without completing the entire scenario

In order to test my application using protractor, I created a scenario. The application begins with a non-angular login page and then progresses to an angular page after logging in. Here is the javascript code snippet that was utilized: var chai = requir ...

What is the best way to extract a specific data point from a website?

Imagine we had a website similar to PewDiePie's YouTube homepage at https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw. Now, I want to create a script that retrieves his subscriber count. Do I need to use Beautiful Soup for this task? I am awar ...

Clicking on the accordion twice does not alter the position of the arrow

I have implemented an accordion using "up" and "down" arrows. It works well, but when I click on the panel title again, the arrow does not change direction. Here is the issue: In my scenario, I have used "A" and "B" instead of the arrows. When the page l ...

Comparing React-Highcharts to regular Highcharts

Despite my efforts to find information on this topic through search engines, I have come up empty. So, I am turning to you with my question. Can someone explain the distinction between these two NPM packages: https://www.npmjs.com/package/highcharts htt ...

Can someone please explain the functionality of "next()" in middleware and how it operates?

Currently, I am following a tutorial by Net Ninjas on node.js and attempting to create my own examples to solidify the concepts in my mind. For reference, I refer to the GitHub source code available on their profile. However, I have encountered an issue at ...

A guide to effectively displaying JavaScript variables within a jQuery function

Initially, I believed this was a problem specific to WordPress, but after spending hours attempting to resolve it, I suspect that it may actually be a broader JavaScript issue. I've been grappling with this challenge for a few hours now and I'm ...

Issues with the ES version affecting back4app cloud code functions

Utilizing back4app as my backend service for deploying my React Native and JS app, I am currently experimenting with the 'Cloud Code Functions' feature. Being new to back4app, I encountered an issue when following their guide. I received this er ...

React Native: How come my text is breaking like this and failing to adhere to the container's margin settings?

I am facing a challenge in React Native where I need to display multiple elements next to each other, with a flex wrap when there are too many elements or if the text is too long. Each element consists of an icon and text, with the text breaking into the n ...

Animation event in CSS3 fails to trigger on Firefox browser

Exploring the potential of CSS3 animation to detect when an input transitions from the enable to disable state, I encountered a challenge specifically in Firefox. Here is the code snippet that showcases the issue: View Demo on jsFiddle HTML: <input t ...

Header logo not showing up on webpage

While working on a website template for a friend, I encountered an issue when uploading the site. The logo image was displaying perfectly fine on my local drive, but once uploaded, it showed as a broken image icon on the live website. Here is the code sni ...

WordPress AJAX code encountered a http400 Bad Request

I've recently started delving into website development and am currently working on a WordPress site. The issue I'm facing is similar to another query on SO, but that question doesn't involve jQuery.AJAX; instead, it utilizes jQuery.post with ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

Enhance your theme property in Styled Components by incorporating numerous style properties

Currently, I am delving into the world of styled components for a fresh project and exploring the theming capabilities it offers. I am finding it challenging to determine the best practice for adding multiple style properties to a single object, essentiall ...

Is there a way to determine if my cursor is within a specific zone?

Is there a way to check, using a .hover function, if my cursor pointer is inside or outside a specific zone? You can find an example here. HTML <ul class="menuLeft"> <li>1</li> <li>2</li> <li>3 ...

The Authorization Header is added just once during an AJAX CORS request

I am making calls to my RESTful API from JavaScript in a CORS scenario. To send my POST authenticated request, I am utilizing JQuery. Below is an example: function postCall(requestSettings, includeAccessToken) { requestSettings.type = 'POST& ...

React - updating key prop does not trigger re-render of child component

I have implemented react-infinite-scroll to display a continuous feed of data. My goal is to refresh the data feed whenever the user makes any changes to their settings. To achieve this, I am utilizing a key prop for the InfiniteScroll component. The conc ...

What is the best method for eliminating buttons and text in a row using CSS?

I faced an issue when trying to create a row, so I improvised with the following setup. However, I actually need a proper row layout for both the Google button and telephone number button. Here are my CSS snippets: .google-button { color: white; borde ...

Suggestions for breaking out of the function update()?

Having some trouble escaping my update() function. Here's the attempt I've made: if (score.l1 > 20) { break; } However, all I get is an error message saying "Illegal break statement" ...

Encountering a 405 error when sending a post request to Flask using AJAX for form submission - could this be a CORS problem?

I'm attempting to utilize Ajax and jQuery on the client side to send a POST request from a form submission, with Flask handling the data processing on the server side. However, when I try to make the post request, I encounter a 405-method not allowed ...