user2886091
user2886091

Reputation: 725

Javascript on input text change, change div text

I am trying to change text of one div, when I enter different values into my text input:

EXAMPLE:

Input = 1,
DIV TEXT: "rok" //in eng. "year"

Input = 2,
DIV TEXT: "roky"

Input = 3,
DIV TEXT: "roky"

Input = 4,
DIV TEXT: "roky"

Input = 5,
DIV TEXT: "rokov"

Default value of my input is 3.

html

<input type="text" id="pocetrokov" value="3"><span id="year">roky</span>

Js:

function rok() {
if(roky==2 || roky==3 || roky==4){
$('#year').html('roky');
  } else if( roky>4 || roky == 0){
$('#year').html('rokov');
  } else if (roky==1){
    $('#year').html('rok');
  }

} 

 $(function () {
 $('select, input').on('keydown blur change', rok);
 });

I get this when I change the defalut value:

Input = 1,
DIV TEXT ="rokov" instead of "rok"

Input = 2,
DIV TEXT ="rokov" instead of "rok"

... etc.

I get the correct value only when I click somehere outside the input

What is wrong? Thank you.

Upvotes: 0

Views: 828

Answers (3)

Emil Borconi
Emil Borconi

Reputation: 3467

Guys why are you complicating it so much with 2 functions?

$("html").on("keyup","#pocetrokov",function(){
var roky=parseInt($(this).val());
   if(roky==2 || roky==3 || roky==4){ $('#year').html('roky');}
   else if(roky>4 || roky === 0) { $('#year').html('rokov');}
   else if (roky==1){     $('#year').html('rok');   }

});

Upvotes: 0

Ash
Ash

Reputation: 1422

Use Keyup Event instead of other,because value of text field is fetched when you keydown and when key down your actual value thats on variable is the previous value,Not the one that is currently in input field So, the function Works correctly :

 $(function () {
 $('input').on('keyup', rok);
 });

Here is DEMO

Upvotes: 0

lshettyl
lshettyl

Reputation: 8181

Try this:



function rok(roky) {
    if(roky==2 || roky==3 || roky==4){
        $('#year').html('roky');
    } else if( roky>4 || roky == 0){
    $('#year').html('rokov');
    } else if (roky==1){
        $('#year').html('rok');
    }
} 

 $(function () {
    $('input').on('keyup blur change', function(){
        rok( $(this).val() );
    });
 });

Upvotes: 1

Related Questions