0

I would like to add an exception or condition in this code.

var a = 0;
    $(document).ready(function() {
            $(document).on("change", "#txtInput" ,function(){
            $("#contenido").append("<tr><td>"+$("#txtInput").val()+"</td></tr>");
                a += 1;
                var str = 'Total Bianuales: '
                $('p').html(str + a);
              }
           )

    });

This is how it works: I get a value with the ID txtInput. I got some condition about this ID up in my code but I want to apply it when it add the value in a table that it's created. How do I make a condition that only append the value I get from txtInput when it's major or equal than 9?

Thanks for your help anyway!

2
  • You can use an if condition to validate it Commented Sep 9, 2016 at 22:21
  • I tried but it didn't work Commented Sep 10, 2016 at 1:09

2 Answers 2

1

Remember that change fires when input looses focus so you will need to click out of the control to cause it to fire. If you wanted it to fire on each keystroke then you want the input event.

var a = 0;
$(document).on("change", "#txtInput",function(){
  var inputLength = this.value.length;
  if (inputLength <= 8) { return; }

  $("#contenido").append("<tr><td>" + this.value + "</td></tr>");
  $("p").html('Total Bianuales: ' + (++a));
});
<input id="txtInput" />
<table id="contenido"></table>
<p></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting "NaN" when I run this. I would like to add in the table the value I type on "input". For example, if I type "DR0010001" (ID that we use at work), I want it to be add in the table. But if I type any value lower than 9 characters, I don't want it to be add in the table. Because with the code I show you early, it does it.
I thought you wanted to ensure that the "value" of the input was more than 8. Now that I know you want the length of the string to be more than 8, I have updated the code.
Now it's working as expected. Thank you so much @JonSG!
1
var a = 0;
$(document).ready(function() {
  $(document).on("change", "#txtInput" ,function(){
    var textinput = parseInt($(this).val());
    if (textinput > 8) {
      $("#contenido").append("<tr><td>"+$(this).val()+"</td></tr>");
      a += 1;
      var str = 'Total Bianuales: '
      $('p').html(str + a);
    }}
  );
});

1 Comment

You might simplify with var textinput = parseInt(this.value); and once you have textinput, you can use it again when building the table row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.