0

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.

2
  • html is too large to be putted in here. Can you specify what are u searching for in html so I can choose which part of html should i put here? Commented Feb 14, 2014 at 12:36
  • LShetty - great, it works, Post it like an answer and I will accept it, If you would like to. Thank you Commented Feb 14, 2014 at 12:41

3 Answers 3

1

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() );
    });
 });
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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');   }

});

Comments

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.