0

I have a <table> with dynamically generated rows (<tr>’s).

In each row, I have a particular cell (<td>) in which I display a textbox. Within that textbox, I’ve added a custom data-roundingrule attribute which holds a particular value (in each row, the data-roundingrule attribute may (or may not) have a different value).

Here are two examples of what those textboxes might look like:

<input type=”text” id=”txt-1” name=”txt-1” data-roundingrule=”2”&gt;
<input type=”text” id=”txt-2” name=”txt-2” data-roundingrule=”13”&gt;

My goal is to create a change event on every textbox that verifies if the entered value (by the user) is a multiple of the value stored in the data-roundingrule attribute.

If the entered value by the user is a multiple of the data-roundingrule attribute then great! Leave things as is…</p>

If the entered value by the user is not a multiple of the data-roundingrule attribute then find/get/obtain the next nearest number that will be a multiple of the data-roundingrule attribute.

Here’s an example:

Considering the above two textboxes, in textbox 1, the user enters the value 1. The change event verifies if the value 1 is a multiple of the data-roundingrule set to 2. Since it’s not the case, then I need to change the value entered by the user and set it to 2.

Likewise for the second textbox…assuming the user has entered the value 4 in the textbox, 4 is not a multiple of 13, so I need to change the user’s input from a 4 to a 13.

If the user has entered the value 16 in the second textbox, 16 is not a multiple of 13 so I need to change the user’s input from a 16 to a 26 (which is the next multiple).

Hope this makes sense…</p>

Sincerely and thanks in advance!

4

3 に答える 3

2

You could do something like this:

$('input').change(function() {
    var round     = parseInt($(this).attr('data-roundingrule'), 10);
    var value     = parseInt($(this).val(), 10);
    var remainder = value % round;

    if(remainder != 0) {
        $(this).val(value + round - remainder);
    }
});
于 2013-02-19T18:13:06.177 に答える
0

Add an onchange method

<input type=”text” id=”txt-2” name=”txt-2” data-roundingrule=”13” onchange="roundUp(this)">

And then defined the function like so with Jquery...

function roundUp(el)
{
  var num = $(this).attr("data-roundingrule");
  num = num * 1 // lazy coercion to numeric type

  var val = $(this).attr(val);

  val = val * 1;
  if(val % num === 0)
  {
    //it's good
  }
  else
  {
    while(val % num !== 0)
    {
      val += 1;
    }
  }  
}

You should probably add some kind of error checking though...

于 2013-02-19T18:13:55.210 に答える
0
$('input').change(function () {
    var rr = parseInt($(this).data('roundingrule'), 10);
    if ($(this).val() % rr != 0) $(this).val(Math.ceil($(this).val() / rr) * rr);
});

jsFiddle example

于 2013-02-19T18:17:15.270 に答える