jQuery Retrieving and Comparing Text Input - javascript

I tried to use jQuery to check if the value of a text input has changed, and if so if it matches a predefined word. I've tried to use .focusout() to detect change, as this answer advises, with no success. I was able to detect a change, but I was unable to compare that change to the predefined word. Is it possible to do this with jQuery, and if so, how?
$(document).ready(function() {
var code = $('#code');
// Save the initial value
$.data(code, "last", code.val());
// Setup the event
code.focusout(function() {
var last = $.data(code, "last");
if (last != $(this).val())
alert("changed");
var value = $("#code").attr('value');
if (value === "CODE") {
$(".upper").slideUp(1000);
$(".lower").slideUp(1000);
$(".main").css({
left: -1000
});
$(".test").css({
color: green
}); //Testing Property
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="ENTER" class="input" id="code">
<p class="test">Does it work?</p>
Thanks!

Instead of using .attr('value'), just use .val()
$(document).ready(function() {
var code = $('#code');
// Save the initial value
$.data(code, "last", code.val());
// Setup the event
code.focusout(function() {
var last = $.data(code, "last");
if (last != $(this).val())
alert("changed");
var value = $("#code").val();
if (value === "CODE") {
alert("CODE!");
$(".upper").slideUp(1000);
$(".lower").slideUp(1000);
$(".main").css({
left: -1000
});
$(".test").css({
color: green
}); //Testing Property
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="ENTER" class="input" id="code">
<p class="test">Does it work?</p>

Set the last value again if the value has changed. And you didn't specify any starting value, so your starting value will be empty.
$(document).ready(function() {
var code = $('#code');
// Save the initial value
$.data(code, "last", code.val());
// Setup the event
code.focusout(function() {
var last = $.data(code, "last");
if (last != $(this).val()){
$.data(code, "last", code.val());
alert("changed");
}
var value = $("#code").attr('value');
if (value === "CODE") {
$(".upper").slideUp(1000);
$(".lower").slideUp(1000);
$(".main").css({
left: -1000
});
$(".test").css({
color: green
}); //Testing Property
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="ENTER" class="input" id="code">
<p class="test">Does it work?</p>

$(document).ready(function() {
var code = $('#code');
var lastWord = "";
// Setup the event
code.focusout(function() {
var value = $("#code").attr('value');
if(value === lastWord){
alert("No change");
}else{
alert("Change")
}
lastWord = value;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="ENTER" class="input" id="code">
<p class="test">Does it work?</p>
Basically you start with an empty string as your 'last code', then on focus out, you compare your value to your lastWord, if those matches, there wasn't any change. When you are done comparing, you set your lastWord to your value.

Related

Temporarily disable an input field if second input field is filled

I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">

How to make sure every input field has greater value than the value of previous input?

How to make sure that every field has greater value than the value of previous input? If condition is true, then I can submit a form.
$('#add').on('click', function() {
$('#box').append('<div id="p1"><input required type="number" min="1" max="120" name="val" ></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
You need to loop through all the inputs, keeping the value of the previous one to compare it. Keep in mind, your current "add input" code will give all the inputs the same name, which will make it problematic to use on your action page. You can use an array for that.
$("#add").on("click", function() {
$("#box").append('<div id="p1"><input required type="number" min="1" max="120" name="val[]" ></div>');
});
$("form").submit(function(e) {
return higherThanBefore(); //send depending on validation
});
function higherThanBefore() {
var lastValue = null;
var valid = true;
$("input[name^=val]").each(function() {
var val = $(this).val();
if (lastValue !== null && lastValue >= val) { // not higher than before, not valid
valid = false;
}
lastValue = val;
});
return valid; // if we got here, it's valid
}
<a id="add" href="javascript:void(0);">Add </a>
<form action="test">
<div id="box"></div>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One line added, one line changed. Simply get the last input's value, and use that as the min value for the new input.
$('#add').on('click', function() {
// get the current last input, save its value.
// This will be used as the min value for the new el
var newMin = $("#box").find(".p1 input").last().val() || 1;
// Append the new div, but set the min value to the
// value we just saved.
$('#box').append('<div class="p1"><input required type="number" min="'+newMin+'" max="120" name="val" ></div>');
$(".p1 input").on("keyup mouseup", function(){
var triggeringEl = $(this);
if (triggeringEl.val() >= triggeringEl.attr("min") ) {
triggeringEl.removeClass("error");
}
triggeringEl.parent().nextAll(".p1").children("input").each(function(){
if($(this).attr("min") < triggeringEl.val() )
$(this).attr("min", triggeringEl.val() );
if ($(this).val() < $(this).attr("min")){
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
})
})
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
So I made changes, to reflect the comments (great catch, by the way), but there is a challenge here. If I set the minimum value when the current el's value changes, works great. But I can't assume that the current el is the highest value in the collection, so if the current el is being decremented, I haven't figured the logic to decrement all subsequent minimums. Sigh...
At any rate, the section that creates the new input and sets the minimum remains the same. Then I had to add a listener to handle changes to the input. If the input is changed, by either keyboard or mouse, all subsequent minimums (minima?) are checked against this value. Those that are lower are set to this value, and then all elements are checked, minimum vs. value, and an error signal is set if needed. Still needs work, as I can't figure how to handle decrementing a value, but it's a start.
You can use .filter(): for each input field you can test if the next one has a value greater then the current one.
$('#add').on('click', function() {
var idx = $('#box').find('div[id^=p]').length;
$('#box').append('<div id="p' + idx + '"><input required type="number" min="1" max="120" name="val' + idx + '" ></div>');
});
$('form').on('submit', function(e) {
var cachedValues = $('form [type=number]');
var noOrderRespected = cachedValues.filter(function(idx, ele) {
var nvalue = cachedValues.eq(idx + 1).val();
return (+ele.value < (+nvalue||+ele.value+1)) ? false : true;
}).length;
console.log('noOrderRespected: ' + noOrderRespected);
if (noOrderRespected > 0) {
e.preventDefault();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>

Allow only number digits in input type regex. issue is i am able to type this(1.) , want to prevent it

MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.

can we use and operator to combine multiple jQuery events

I want to use jQuery to see if three text boxes are changed so I can send data through AJAX.
I tried a simple script:
$("#name, #position, #salary").change(function()
{
console.log("All data are changed");
});
Where name, position and salary are the respective IDs of three text box.
The result was that when I change the first one:
And when I changed the second:
And here is the third one:
So, I've got the message when separately each text box is changed. What I do need is when the three are changed, display the message. I am new to jQuery, so I want to know if I can use something like IF ... AND ... AND in jQuery.
A lot of validation frameworks have the concept of a dirty input once a user has changed the value. You could implement this and check when all your fields are dirty.
$("#name, #position, #salary").change(function() {
this.classList.add("dirty");
if ($(".dirty").length === 3) {
console.log("All data are changed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
We can abstract this out into a jQuery plugin for re-usability
$.fn.allChange = function(callback) {
var $elements = this;
$elements.change(function() {
this.classList.add("dirty");
if (callback && $elements.filter(".dirty").length === $elements.length) {
callback.call($elements);
}
});
return $elements;
}
$("#name, #position, #salary").allChange(function() {
console.log("All data are changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
You can store changed inputs in an array, and check it's length to detect if all of them where changed.
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
changedInputs.push(this.id);
if(changedInputs.length === 3) {
alert('All 3 inputs where changed!');
}
});
You can try:
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
if !(changedInputs.include(this.id) ){
changedInputs.push(this.id);
if(changedInputs.length == 3) {
alert('All 3 inputs where changed!');
}
});
You can also use this approach. Fiddle
var isNameChanged, isPositionChanged, isSalaryChanged = false;
function fieldsChanged()
{
var id = $(this).attr('id');
if (id == 'name') isNameChanged = true;
else if (id == 'position') isPositionChanged = true;
else if (id == 'salary') isSalaryChanged = true;
if (isNameChanged && isPositionChanged && isSalaryChanged) {
console.log('All have been changed');
isNameChanged = isPositionChanged = isSalaryChanged = false;
}
}
$(function(){
$('#name, #position, #salary').change(fieldsChanged);
});
Try using a class:
<input class="need">
<input class="need">
<input class="need">
$(".need").change(function()
{
var all = 0;
$(".need").each(function(i,v){
if ($(v).val().length >0 ) {
all+=1;
}
});
if(all.length == 3) {
alert('All 3 inputs where changed!');
}
});
Store the multiple selectors in a variable. On .change() loop through the elements in the multiple selector to test the input values. If all inputs have content an additional function can be called.
$(document).ready(function(){
var $selectors = $('#input1, #input2, #input3');
$selectors.change(function(){
var allChanged = true;
console.log($(this).attr('id') + ' was changed.');
$selectors.each(function(){
if ($(this).val() == '') {
allChanged = false;
}
});
if (allChanged) {
// $().ajax();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input id="input3">
one possible solution:
var needed = ["name", "position", "salary"];
$("#name, #position, #salary").change(function()
{
if(needed.length == 0) return;
needed.splice(needed.indexOf($(this).attr('id')), 1);
if(needed.length == 0)
console.log("All data are changed");
});
first, you need to init the array "needed" to all required fields
then, when a field is changed, you remove that field from the needed array
once the array is empty, all required values are changed ;)
the first condition is to ensure not to log the message more than once
You can compare current input value to default one, then the logic could be like following:
btw, i set a common class for all inputs to check, because this is how it should be done imho...
$('.inputToCheck').on('change', function() {
var allInputsChanged = !$('.inputToCheck').filter(function() {
return this.value === this.defaultValue;
}).length;
if (allInputsChanged) alert('All inputs changed!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="name" class="inputToCheck">
<input id="position" class="inputToCheck">
<input id="salary" class="inputToCheck">

How to update an appended value?

Guys I have an input text and when I start typing, it counts how many letters I am using. But when I clear the input value, I can't change letter counter. How can I get it?
Thanks in advance.
Jsfiddle
function count_letter() {
var len = $("#area").val().length;
$('#counter').append(len);
}
$('#area').bind('keyup', function() {
$('#counter').html('');
count_letter();
});
$('#clear-value').click(function(){
$("#area").val(" ");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="area"><br>
<div id="counter"></div><br>
<button id="clear-value">
Clear value
</button>
In the #clear-value event handler, add:
$('#counter').empty();
Which will clear the #counter element.
function count_letter() {
var len = $("#area").val().length;
$('#counter').append(len);
}
$(function() {
$('#area').bind('keyup', function() {
$('#counter').html('');
count_letter();
});
$('#clear-value').click(function(){
$("#area").val("");
$('#counter').empty(); //<<<-----
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="area"><br>
<div id="counter"></div><br>
<button id="clear-value">
Clear value
</button>
Just call your count_letter function when you clear the input value :
$('#clear-value').click(function(){
$("#area").val(" ");
$('#counter').html('');
count_letter();
});
Cleear your counter on click of clear value button.
See below in action:
https://jsfiddle.net/28bs18gq/2/
function count_letter() {
var len = $("#area").val().length;
$('#counter').append(len);
}
$('#area').bind('keyup', function() {
$('#counter').html('');
count_letter();
});
$('#clear-value').click(function(){
$("#area").val(" ");
$('#counter').html('');
});

Categories