For in Javascript with user input

Asked

Viewed 70 times

3

I have a form field that receives a value inteiro, this field in the form has the function OnKeyPress, I need the user to enter some value this value goes to the for ex: the user has typed 5, the for goes from 0 a 4

My role in JavaScript:

function key_press(e) {
  for (var i = 0; i < e; i++) {
    $("#gridContainer2").dxDataGrid("addRow");
  }
}

My form:

@(Html.DevExtreme().Form<FormaPagamentoViewModel>()
    .ID("formularioCadastro")
    .ShowValidationSummary(false)
    .Items(items =>
    {
       items.AddGroup()
       .Items(groupItems =>
       {
         groupItems.AddSimpleFor(m => m.Fpg_quantidade)
         .Editor(e => e.NumberBox().Width("70px").OnKeyPress("key_press"));//Campo que o usuário ira preencher
    });
    })
    .FormData(Model)
    )
  • And what’s the mistake?

  • In vdd the error is that my for I n to passing the entered value, I am passing only the "e", but I testing discovered a solution

  • I should have commented on the part that needs change, sorry my mistake, but obg

  • 1

    There is no way instead of onKeyPress, put .OnKeyUp("key_press(this)")?

  • Yeah, there’s a way, it even looks better to use

  • But I don’t quite understand the difference between the two

Show 1 more comment

2 answers

3


Instead of OnKeyPress, use OnKeyUp, because the first will return the value that was before you press the keyboard, while the second will take the value after, the last entered value. Put a id in the field and take your value using document.getElementById:

.OnKeyUp("key_press")

In the function you do:

function key_press() {
   for (var i = 0; i < document.getElementById("ID DO ELEMENTO").value; i++) {
      $("#gridContainer2").dxDataGrid("addRow");
   }
}

Note that you do not need (e) in function, since nothing is being sent to her.

  • I cannot send elements via `this , the form field adds

  • It has the Width attribute, but as it is devextreme, it may create some id automatically

  • Yes, I can put an id, but I don’t know how to get javascript using this id

  • for (var i = 0; i < document.getElementById("ID DO ELEMENTO").value; i++) {

  • I tried that way, but Debugger says that q the value is Undefined

  • Change ID DO ELEMENTO for id that you put in the field.

Show 1 more comment

0

Testing, I ended up finding the following solution:

var event = e.event, str = event.key || String.fromCharCode(event.which);
for (var i = 0; i < str; i++) {
    $("#gridContainer2").dxDataGrid("addRow");
}

Event.Key takes the entered value and puts it in var str which can be used in the for.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.