3

How can I check if the value of an input box is not the same after blur?

$("#username").on('blur', function() {
  $("#usertext").append("new input<br>");
})

Check this jsFiddle: https://jsfiddle.net/xztptsdg/

Let's think that I enter "Josh" in input and after blur, will append new input box. But, user can "re-blur" the username input, and will append other input.

I want to check if the value is the same, not append new input.

3 Answers 3

3

You may use change instead of blur, for example:

$("#username").on('change', function() {
    $("#usertext").append("new input<br>");
});

So, there is no need to check if the value changed or not because the change event is sent to an element when its value changes.

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

Comments

2

See this fiddle

You can keep a global variable to store the current value of the textbox and then check whether the entered value is the same as the previous one. If not, then append the new input text and also set the global variable with the new one. Below is the Javascript that does this.

JS

var txt = "";
$("#username").on('blur', function() {
  if (txt != this.value) {
    $("#usertext").append("new input<br>");
    txt = this.value;
  }
})

I would suggest you to use change(). According to the docs

The change event is sent to an element when its value changes.

See the fiddle and below is the JS code with change().

$("#username").change(function() {
    $("#usertext").append("new input<br>");
});

Comments

1

You can do it like following snippet.

var text = '';
$("#username").on('blur', function() {
  if(this.value != text){
    text = this.value;  
    $("#usertext").append('new input<br>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="username" id="username">
<br>
<span id="usertext"></span>

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.