Deactivate "When the viewModel attribute holds the phrase 'some text'"

I came across this answer on Stack Overflow regarding checking for a value in Knockout, but it seems to be outdated. I am attempting to achieve something like this:

<li>
   <span data-bind="text: Subject"></span>
   <!-- ko if: Subject.contains('Important') -->
      <i class="fa fa-exclamation-triangle"></i>
   <!-- /ko -->
</li>

In this scenario, I want the fontawesome icon to be displayed next to the Subject text if it contains the word 'Important'. Unfortunately, using 'contains' as a function does not work, and I am having trouble finding an updated solution.

Answer №1

To incorporate a `contains` method for observables, you have the option to create it as a custom function by referring to Knockout's documentation. Another approach would be to add it exclusively to `vm.Subject`, or alternatively, inline it as recommended by Matt.

ko.observable.fn.contains = function (str) {
  return this().indexOf(str) > -1;
};

vm = {
  Subject: ko.observable('This is Important')
};

ko.applyBindings(vm);

setTimeout(() => vm.Subject('This is not'), 1500);
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<span data-bind="text: Subject"></span>
<!-- ko if: Subject.contains('Important') -->
<i class="fa fa-exclamation-triangle"></i>
<!-- /ko -->

Answer №2

This is the final code snippet I used:

<li>
   <span data-bind="text: Subject"></span>
   <!-- ko if: Subject().indexOf('Important') !== -1 -->
   <i class="fa fa-exclamation-triangle"></i>
   <!-- /ko -->
</li>

It ended up working perfectly! Many thanks to Matt.kaaj for the assistance. Roy's method seems ideal for repeated instances, but in my case where I only needed to check once, the straightforward inline solution sufficed. Grateful for your help!

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

Retrieve the scrollTop, scrollLeft properties, and other scroll-related data from an element using Selenium

When testing a Python/Django element that is scrolled using scrollTop, I am trying to retrieve the value of scrollTop. In JavaScript, I can access this value with: element.scrollTop I attempted to do this in Python using: element.get_attribute('sc ...

Deleting a DOM element within an element that has been created by an external script

On a webpage, I have third-party ad content that is generated by an external script. This content has a delay in loading. My goal is to eliminate a line break from the ad content, but this can only be done once the external script finishes loading and all ...

What is the best way to set up multiple unique uglify tasks in grunt?

I am facing issues when trying to create multiple Uglify tasks in Grunt. Currently, I have to toggle between commenting and uncommenting a task to get it to work properly. I need assistance in generating two separate minified .js files using this plugin ...

Exploring the possibility of designing custom pageload tooltips inspired by jQuery validationEngine's visual style and interface

My website incorporates the jQuery.validationEngine plugin to ensure the accuracy of user input. The tooltips that accompany this validation feature are particularly appealing; they gracefully fade in and vanish when users interact with them. To visualize ...

Sequelize encountered an error: getaddrinfo ENOTFOUND (even though the address is correct)

I've encountered some Sequelize errors while attempting to deploy a site I developed using Angular and Express/Sequelize. Here's the issue: Everything works perfectly on my local WAMP server, connecting to the local database without any problems ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

Tips for obtaining the entire date and time on one continuous line without any breaks or separation

Is there a way to retrieve the current date and time in the format of years, months, days, hours, minutes, seconds, and milliseconds like this? 201802281007475001 Currently, I am getting something like: 2018418112252159 This is my code so far: var dat ...

Extracting information from a Postgres query in Node.js

I'm looking for guidance on how to pass the results of a postgres query in Node.js to another function. Can anyone provide an example? ...

Dealing with the state of an array of checkboxes: What you need to know

Is there a way to individually control the checked state of an array of checkboxes? Here is the array in question: const CheckboxItems = t => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', ...

Adjust the color of the text based on a conditional in react

I am looking for a way to select elements and change text color in my unordered list based on specific conditions. Below is an example of the structure I have: <div style={styles.passwordRules}> <ul style={styles.listOne}> <li style={ ...

Weekly downloads for NPM show no activity

https://i.stack.imgur.com/4Uhk4.png https://i.stack.imgur.com/0vikS.png Why are all the weekly downloads showing zero for npm packages? I'm new here and confused about why this is happening, any insights? If you could please help me open this issue ...

Having Trouble Accessing Custom Screen in React Navigation?

The navigation from the Order screen to the Home Screen is not working as expected. Every screen in the route works, except for the Home screen, which just navigates back to the Map screen. I have clearly instructed to navigate to Home. Here is the curren ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

attempting to shift course, but finding no success

I'm attempting to include dir=rtl or direction: rtl in the CSS, but it doesn't seem to have any effect on the browser and the content still displays left to right. What steps can I take to fix this? This template is pre-made from Colorlib. It&ap ...

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...

The optional attribute feature in Angular directives

Looking for a solution: angular .module('test') .directive('multiButton', function () { return { restrict: 'E', replace: true, scope: { disabled: '@' }, template: ' ...

Check for non-null Sequelize Where conditions

Suppose I need to execute a select command using Sequelize with the condition: WHERE ID=2134 However, if the user does not provide an ID, then the WHERE clause should be omitted (as it is null). What is the best way to handle this situation in Sequelize ...

Is there a way to create an effect where the color of a floating action button changes when you hover over it, similar to a filter?

I'm new to using the <Fab /> element and I'm struggling to figure out how to implement a hover effect that will change the button's color. Here's what I have so far: JavaScript: <Fab variant="extended" className=&quo ...

Would it be a security risk to share the Stripe charge ID and connected account ID with clients on the frontend?

I am currently making an ajax call to my backend and I am unsure whether it is secure to reveal the charge id and the connected account id on the client side. Just to clarify, there are no secret keys or sensitive information stored in the browser. Your ...

Nested tables in Datatables retrieving child table rows based on parent table

I have been struggling for the past three days to get my nested Datatables working properly. I have a parent table called MAINtable and a child table called adjlinesTable. The issue I am facing is that all lines from the adjlinesTable are being drawn to ...