Ns789
Ns789

Reputation: 531

How to change background color of input text field on the basis of dynamic value in php?

I am trying to change the background colour of the input field on the basis of the dynamic float value coming from the database or from another page.

Code sample:

<div>
    <input type="text"  readonly value="<?php echo $time_per_tag; ?>"  data-ranges='[[1, 14, "#BEFB93"], [15, 16, "#FDEB99"], [17, 17.5, "#FEBE5C"], [18, 100, "#FB9090"]]' onkeyup="checkFilled(event);">
</div>

output:

here

Here $time_per_tag is the variable that contain value from the database in float. Now if the value is between(1-14) the background colour will be green(#BEFB93) and if between(15-16) then yellow(#FDEB99) and so on...

JS:

  function checkFilled(event) {

              var inputVal = event.target;
              var inputData = JSON.parse(inputVal.dataset.ranges);
              var color = "";

              for (i = 0; i < inputData.length; i++) {
                if (inputVal.value >= inputData[i][0] && inputVal.value <= inputData[i][1]) {
                  color = inputData[i][2];
                  break;
                }
              }

              inputVal.style.backgroundColor = color;
            }

the problem is I don't want to input editable by the user. only readyonly purpose. but if I do that code might not be work. I want something like code works without onkeyup.

Any kinda suggestion, code modification & implementation is highly appreciated.

Upvotes: 1

Views: 690

Answers (2)

Dmitriy
Dmitriy

Reputation: 93

if you want input to be read only, maybe it shouldn't be input but just span or div?

Upvotes: 1

Mister Jojo
Mister Jojo

Reputation: 22265

Simply add your color in the style attribute :

<input type="text"
  readonly value="<?php echo $time_per_tag; ?>"
  style="background-color: <?php echo $yourColor; ?>" >

Upvotes: 1

Related Questions