Trying to update background color based on text value

I am attempting to use Wix’s javascript to set the background color of a text element based on the value of that element.

Here’s my code:

$w.onReady(function() {
  // Write your JavaScript here
  let textVal = $w('#text36').text

  if (textVal === "Available" || null) {
    $w('#text36').html = `<h1 style="background-color: green">${$w("#text36").text}</h1>`

  } else {
    $w('#text36').html = `<h1 style="background-color: red">${$w("#text36").text}</h1>`

  }

It is always “Red” and never green no matter the value of the text36 element. If I manually set the value of text36 it works so the issue is getting the value. This is coming from a CMS Field.

Not good…
if (textVal === “Available” || null)

GOOD:
if (textVal) {…}

I only want to display green if textVal = “Available”

if (textVal === 'Available') {console.log('RESULT = TRUE');}
else {console.log('RESULT = FALSE');}

I don’t understand what you’re trying to say

$w.onReady(()=> {	
	let textVal = 'Available'

	if (textVal === "Available") {
		$w('#text36').html = `<h1 style="color: green">${$w("#text36").text}</h1>`
	} 
	else {$w('#text36').html = `<h1 style="color: red">${$w("#text36").text}</h1>`}
});

This is where you will replace your own VALUES…(set it to whatever else but not available and test it again)…

let textVal = ‘Available’

Thanks for responding. However I want the value of textVal to be the value of the text element on the screen not what I set it in the code. If the text value is “Available” it should be highlighted as Green. If not “Available” then red…

If I set it in the code textVal = “Available” then it works. If I try to read it from the screen then it doesn’t work

any thoughts or recommendations?

I’ve read this whole thread and i recommend going the old school workaround way ……

Make 3 boxes inside the repeater, design each one with each color version. Set all to collapse on load. On repeater item ready, check what the value of Status is, then expand appropriate box. Green, red, etc.

I don’t know why i thought it was a repeater. Whatever your element is. On regular page, dynamic page, repeater or not, etc. Just design the possible combination and display the correct one after you have checked for the value.

1 Like

It is a repeater! Thanks…I’ll try that out

1 Like