Как изменить цвет фона поля ввода после того, как пользователь перестает печатать, если выполняется определенное условие - PullRequest
0 голосов
/ 10 июля 2019

Я абсолютно новичок в html и javascript.

У меня есть приложение, в котором пользователи вводят новую цену за элемент. Я хочу сделать цвет фона поля ввода красным, если новая цена +/- 25% к старой.

Они фиксируют цены нескольких товаров каждый раз, поэтому у меня есть таблица полей формы. Я не знаю, как передать конкретную строку таблицы в мой сценарий javascript, поскольку имена не меняются между строками, а также строки изменяются динамически в зависимости от пользователя.

Я использую колбу с wtforms.

Вот функция javascript, которую я сейчас имею.

<script type=text/javascript>
  $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>

var typingTimer;                //timer identifier
var doneTypingInterval = 1500;  //time in ms, 1.5 second for example
var $input = $('#nuevoPrecio');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
        $.getJSON($SCRIPT_ROOT + '/_revisarCaptura', {
          unidades: $('th[name="unidades[0]"]').innerHTML(),
          ultimoPrecio: $('th[name="ultimoPrecio[0]"]').innerHTML(),
          nuevoPrecio: $('th[name="nuevoPrecio[0]"]').innerHTML(),
          nuevasUnidades: $('tr[name="holder[0]"]').innerHTML(),
        }, function(data) {
          $("#nuevoPrecio").style.backgroundColor(data.result);
;

}

</script>

вот таблица, которую скрипт должен изменить


{{form.hidden_tag()}}

{% from '/inputs/_formhelpers.html' import render_field %}
{% set i = [0] %}
<font size= "2"  >
<table class= "table table-striped">
  <tr class = "thead-dark">
    <th style = "text-align:center;">Id</th>
    <th style = "text-align:center;">Cotización</th>
    <th style = "text-align:center;">Artículo</th>
    <th style = "text-align:center;">Descripción</th>
    <th style = "text-align:center;">Marca</th>
    <th style = "text-align:center;">Presentación</th>
    <th style = "text-align:center;">Unidades</th>
    <th style = "text-align:center;">Último Precio</th>
    <th style = "text-align:center;">Nuevo Precio (MXN)</th>
    <th style = "text-align:center;">Nuevas Unidades</th>

  </tr>

{% for subForm1, subForm2 in form.precios|zip(form.unidades) %}

    {{ subForm1.hidden_tag() }}
    {{ subForm2.hidden_tag() }}

    <tr>
      <th name = 'version' style = "text-align:center;">{{df.versionId_x[i].values[0]}}</th>
      <th name = 'cotizacion' style = "text-align:center;">{{df.cotizacion[i].values[0]}}</th>
      <th name = 'artciulo' style = "text-align:center;">{{df.nombre[i].values[0]}}</th>
      <th name = 'descripcion' style = "text-align:center;">{{df.descripcion[i].values[0]}}</th>
      <th name = 'marca' style = "text-align:center;">{{df.marca[i].values[0]}}</th>
      <th  name = 'presentacion' style = "text-align:center;">{{df.presentacion[i].values[0]}}</th>
      <th name = 'unidades' style = "text-align:center;">{{df.unidades[i].values[0]}}</th>
      <th name = 'ultimoPrecio' style = "text-align:center;">${{df.ultimoPrecio[i].values[0]}}</th>
      <th name = 'nuevoPrecio' style = "text-align:left">{{render_field(subForm1.precio(style='width:75px;'))}}  <br> <small> <strong> <font color="red">Producto encadenado.</font> </strong> </small> </th>
  <th name = 'nuevasUnidades'style = "text-align:left">{{render_field(subForm2.unidad(style='width:75px'))}} </th>

    </tr>
{% if i.append(i.pop() + 1) %}{% endif %}

{% endfor %}
</table>
</font>


А вот функция, которая проверяет, выполнено или нет условие ввода пользователем:


@inputs.route('/_revisarCaptura')
def revisarCaptura():
    nuevoPrecio = request.args.get('nuevoPrecio',0,type = float)
    nuevasUnidades = request.args.get('nuevasUnidades', 0, type=float)
    ultimoPrecio = request.args.get('ultimoPrecio', 0, type=float)
    unidades = request.args.get('nuevasUnidades', 0, type=float)

    if abs(nuevoPrecio/nuevasUnidades - ultimoPrecio/unidades)/ultimoPrecio/unidades > .25:
        return jsonify(result='red')
    else:
        return jsonify(result='white')


...