0

This is not a duplicate, because the value of the input is changed by a function, not by user input.

Is it possible to call a function if the value of the attribute of an element has changed?

E.g. I use an input text with the id color and a button which opens a color picker. If I select a color then the color value is written into the input text with id color.

Color Picker

I try to detect if the value of the input text with id color has changed and call a function which sets the background-color of my input text to the selected color.

My attempt:

$("input#color").on
(
    "change",
    function()
    {
        console.log("SOMETHING HAS CHANGED");

        var color = $("input#color").val();
        $("input#color").css("background-color", color);
    }
);

But SOMETHING HAS CHANGED is never shown.

I know I could solve this by using timers, but I think there must be a better solution.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Black
  • 18,150
  • 39
  • 158
  • 271
  • Its running properly, did you've add jquery files? – Fadhly Permata Sep 07 '16 at 07:44
  • Jquery file is included and the color picker itself is working. Jquery also works, if i change the event from `change` to `click` then something happens after the click. – Black Sep 07 '16 at 07:45
  • Change is only triggered when it loses focus and was changed. The best way to continually check and respond to change is to... Continually check if something has changed, with an interval for example. – somethinghere Sep 07 '16 at 07:47
  • I know that i could use an interval, but is this the only solution?! I was not planning to code it like this because i thought it would be a dirty workaround. – Black Sep 07 '16 at 07:49
  • 3
    Do one thing listen to the color picker click event or check where is setting value in your input. After value set call trigger change event of the input. – VJI Sep 07 '16 at 07:55
  • Yes thats also possible and it seems like this is my only option. – Black Sep 07 '16 at 07:57

0 Answers0