Автоматически обновлять поле ввода с помощью математики, используя jquery? - PullRequest
4 голосов
/ 17 января 2012

Хорошо, мне нужна помощь, у меня есть онлайн-калькулятор, где я должен получить линейный счетчик из двух полей ввода. Мне нужно, чтобы это было автоматически, поскольку они вводят данные. Я понятия не имею, как это сделать .. любая помощь кодирования будет принята с благодарностью! Вот HTML:

<input type="text" name="ancho" />
<input type="text" name="alto" />
<input type="text" name="material" />

Мне нужно вывести в это поле:

<input type="text" name="ml" />

Вот уравнение для математической части этого: (материал / 100) / ((альт / 100) * (якорь / 100))

Заранее благодарю за помощь!

Ответы [ 4 ]

5 голосов
/ 17 января 2012

Вздох Я не вижу много проверок ошибок здесь в решениях, поэтому я решил опубликовать просто еще ...

// locate all the input fields on the page
$(':input')
// bind to anything change related (down to keyboard changes so the element
// won't need to lose focus, or the user won't have to press enter)
.bind('keypress keydown keyup change',function(){
    // retrieve the values of the inputs (we also call parseFloat to confirm
    // we are dealing with numeric values)
    var acho = parseFloat($(':input[name="acho"]').val(),10),
        alto = parseFloat($(':input[name="alto"]').val(),10),
        matl = parseFloat($(':input[name="material"]').val(),10);

    // default the end result to an empty string (you'll see
    // why with the following statement)
    var v = '';

    // confirm that all three values that go in to the equation are
    // all numbers before we try to perform any math functions. If
    // all goes well, "v" above will have the actual resulting value.
    // if any number is invalid, the "Result" field (ml) gets emptied
    if (!isNaN(acho) && !isNaN(alto) && !isNaN(matl)){

        // your math function
        v = (matl / 100) / ((alto / 100) * (acho / 100));
    }

    // replace the value of "ml" with our new calculated value
    $(':input[name="ml"]').val(v.toString());
});

... С демоверсией

2 голосов
/ 17 января 2012

Попробуйте:

$('input[name="material"],input[name="ancho"],input[name="alto"]').change(function(){
$('input[name="ml"]').val(($('input[name="material"]').val() / 100) / (($('input[name="alto"]').val() / 100) * ($('input[name="ancho"]').val() / 100)));
})

A jsFiddle здесь.

0 голосов
/ 17 января 2012

будет обновляться при вводе любого из полей.хотя не проверено.

$('input').keyup(function(){
    var material = $('input[name="material"]').val(),
    alto = $('input[name="alto"]').val(),
    ancho = $('input[name="ancho"]').val(),
    result;

    if (material != "" && alto != "" && ancho != ""){
        result = (material/100) / ((alto/100) * (ancho/100));
        $('input[name="ml"]').val(result);
    }
});
0 голосов
/ 17 января 2012

Используйте $('input[name="yourName"]').val(), чтобы получить значение в каждом входе, а затем примените вашу формулу.

Для установки окончательного результата в поле результатов используйте $('input[name="yourName"]').val(results)

что-то вроде:

$('input').blur(function(){
   //Get values
   var ancho= $('input[name="ancho"]').val();
   var alto= $('input[name="alto"]').val();
   var material= $('input[name="material"]').val();
   //Calculate results
    var results =  (material/100) / ((alto/100) * (ancho/100));

   //update output
   $('input[name="ml"]').val(results);
});

Вы можете добавить логику в обработчик blur/change event для ввода

jsFiddle

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...