dynamically detect if textbox value is change - javascript

Is it possible to detect the change of a textbox even if that textbox value is not entered by user like the below scenario? I have some scenarios like when the page is loading for the first time the texbox get loaded with data.
$("#txt1").change(function(){
$("#txt2").val("1")
//$("#txt2").change();
});
$('#txt2').on("change", function() {
// some computation will happen here.
alert("1");
});
$("#btn1").click(function(){
$("#txt2").val("1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt1">
<input type="text" id="txt2" name='text1'>
<button id="btn1">
Click
</button>

The value changed by JavaScript does not trigger any event so you just can't catch event in this case.
You can implement a watcher to your input value using interval
var oldValue = $("#txt2").val();
setInterval(function() {
var currentValue = $("#txt2").val();
if (currentValue !== oldValue) {
$("#txt2").trigger("change");
oldValue = currentValue;
}
}, 100);
$("#txt1").change(function(){
$("#txt2").val("1")
});
$('#txt2').on("change", function() {
// some computation will happen here.
alert("1");
});
$("#btn1").click(function(){
$("#txt2").val("1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt1">
<input type="text" id="txt2" name='text1'>
<button id="btn1">
Click
</button>

As you know that on textbox1 change event you are changing second textbox value, you need to trigger it manually
$(document).ready(function () {
$("#txt1").change(function () {
$("#txt2").val("1")
$("#txt2").trigger("change");
});
$("#txt2").change(function () {
alert("1");
});
})

Related

whatever the number , i enter in form field, i want that to be stored in a variable.

(web designing) whatever the number , i enter in form field, i want that to be stored in a variable. When the user changes the value in the form field , value stored in the variable needs to be updated. How to do that ?
Try this:
<input type = "text" id = "id1">
<script>
$("#id1").change(function(){
var a = $("#id1").val();
alert(a);
});
</script>
there is a jsbin that demonstrates required functionality
jsbin
or
<form>
<input id="input" type="number">
</form>
<button id="button">Log Value</button>
<script>
var input = document.getElementById('input');
var button = document.getElementById('button');
var val;
input.addEventListener('change', function (event) {
val = +event.target.value;
});
button.addEventListener('click', function () {
console.log('Value:', val);
});
</script>
<form>
<input type="text" id="inputid" value="test"/>
<button type="submit">submit</button>
</form>
<script>
$( document ).ready(function() {
var input =$('#inputid');
var saveVar;
// input.change(function(){
// console.log(input.val());
// });
input.on('keyup', function(ev){
saveVar=input.val();
console.log(saveVar);
});
});
</script>

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>

calculation using decimal number field

I'm trying to make a calculation using number fields that have set decimal places.
While the decimals are being displayed properly, the calculation is not running. Here is my javascript:
function setZeroNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(0);
};
function setThreeNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(3);
};
$(document).ready(function(){
$(".calc").keyup(function(){
var areasf = +$(".SF").val();
$("#acre").val(areasf/43560);
});
});
And the HTML:
<input type="number" onchange="setZeroNumberDecimal(this)" name="grosslandSF" class="calc SF">
<input type="number" onchange="setThreeNumberDecimal(this)" name="grosslandacre" disabled="disabled" id="acre">
Any help would be great.
Instead of inline onchange event you can use oninput event.
When you change a value like in:
$("#acre").val(areasf/43560)
this will not fire the corresponding event, so you must do it by yourself:
$("#acre").val(areasf/43560).trigger('input');
The snippet:
function setZeroNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(0);
};
function setThreeNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(3);
};
$(document).ready(function(){
$(".calc").keyup(function(){
var areasf = +$(".SF").val();
$("#acre").val(areasf/43560).trigger('input');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" oninput="setZeroNumberDecimal(this)" name="grosslandSF" class="calc SF">
<input type="number" oninput="setThreeNumberDecimal(this)" name="grosslandacre" disabled="disabled" id="acre">
</form>

Input event not working if value is changed with jQuery val() or JavaScript

If I change the value of an input field programmatically, the input and change events are not firing. For example, I have this scenario:
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
The problem: The event is triggered when I type in the textfield, but not when I press the button. Is there a way to achieve this with some kind of event or otherwise without having to do it manually?
What I don't want to do: I could go through all my code to add a trigger or function call everywhere manually, but that's not what I'm looking for.
Why: The main reason I would like to do this automatically is that I have a lot of input fields and a lot of different places where I change these inputs programmatically. It would save me a lot of time if there was a way to fire the event automatically when any input is changed anywhere in my code.
Simple solution:
Trigger input after you call val():
$input.trigger("input");
var $input = $("#myinput");
$input.on('input', function() {
alert($(this).val());
});
$('#change').click(function() {
// Change the value and trigger input
$input.val($input.val() + 'x').trigger("input");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="myinput" type="text" />
<button id="change">Change value</button>
Specific solution:
As mentioned you don't want to trigger input manually. This solution triggers the event automatically by overriding val().
Just add this to your code:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
var res = originalVal.apply(this, arguments);
if (this.is('input:text') && arguments.length >= 1) {
// this is input type=text setter
this.trigger("input");
}
return res;
};
})(jQuery);
See JSFiddle Demo
PS
Notice this.is('input:text') in the condition. If you want to trigger the event for more types, add them to the condition.
There are some ways on how to achieve it. Here, you can use the levelup HTML's oninput() event that occurs immediately when an element is changed and call the function.
<input id="myinput" type="text" oninput="sample_func()" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
function sample_func(){
alert(input.val());
}
$('#change').click(function() {
input.val(input.val() + 'x');
});
Or this jQuery, input thing (just related to above example).
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
input.on("input", function() {
alert(input.val());
});
$('#change').click(function() {
input.val(input.val() + 'x');
});
You can also use javascript setInterval() which constantly runs with a given interval time. It's only optional and best if you're doing time-related program.
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
setInterval(function() { ObserveInputValue(input.val()); }, 100);
$('#change').click(function() {
input.val(input.val() + 'x');
});
jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically.
You could create your own miniature jQuery extension to proxy this so that you always trigger the event but only have to do in one modular place, like so:
$.fn.changeTextField = function (value) {
return $(this).val(value).trigger("change");
}
Then, just call your new function whenever you want to update your text field, instead of using jQuery's 'val' function:
$("#myInput").changeTextField("foo");
Here's a version working with a proxy function:
<!DOCTYPE html>
<html>
<head>
<title>Test stuff</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<input id="myInput" type="text" />
<button id="myButton">Change value</button>
<script type="text/javascript">
$.fn.changeTextField = function (value) {
return $(this).val(value).trigger("change");
}
$( document ).ready(function() {
var $input = $("#myInput");
$input.on("change", function() {
alert($input.val());
});
$('#myButton').click(function() {
$("#myInput").changeTextField("foo");
});
});
</script>
</body>
</html>
For reference, this question has really already been answered here:
Why does the jquery change event not trigger when I set the value of a select using val()?
and here: JQuery detecting Programatic change event
Looks like there's no way, other than using .trigger().
Let's try the same thing using .change() event:
var $input = $("#myinput");
$input.on('change paste keyup', function() {
alert($(this).val());
});
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("change");
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or you need to trigger it manually:
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("input");
});
Snippet
var $input = $("#myinput");
$input.on('input', function() {
alert($(this).val());
});
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("input");
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Trigger didn't work for. Creating an event and dispatching with native JavaScript did the work.
Source: https://stackoverflow.com/a/41593131/6825339
<script type="text/javascript">
$.fn.changeTextField = function (value) {
return $(this).val(value).dispatchEvent(new Event("input", { bubbles: true });
}
$( document ).ready(function() {
var $input = $("#myInput");
$input.on("change", function() {
alert($input.val());
});
$('#myButton').click(function() {
$("#myInput").changeTextField("foo");
});
});
</script>
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
$input.val($input.val() + 'x')
$input.trigger('change');
The change event only fire when input blur.
Try this
$('#input').trigger('change');

Copy text of a field into another automatically

I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.
If the user deletes the text in field_1, it should also get automatically deleted in field_2.
I've tried this but it doesn't work:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>
Any ideas?
You are almost there... The function is correct, you just have to assign it to the change event of the input:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
//Since you have JQuery, why aren't you using it?
var box1 = $('#field_1');
var box2 = $('#field_2');
box2.val(box1.val());
}
$('#field_1').on('change', onchange);
});
$(document).ready(function() {
$('.textBox1').on('change', function() {
$('.textBox2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textBox1"/>
<input type="text" class="textBox2"/>
If you are using jQuery, it is very easy - you need just register the right function on the right event :)
Here's the code:
<input id="foo" />
<input id="bar" />
$(function(){
var $foo = $('#foo');
var $bar = $('#bar');
function onChange() {
$bar.val($foo.val());
};
$('#foo')
.change(onChange)
.keyup(onChange);
});
JSFiddle: http://jsfiddle.net/6khr8e2b/
Call onchange() method on the first element onblur
<input type="text" id="field_1" onblur="onchange()"/>
try with keyup event
<input type="text" id="box_1"/>
<input type="text" id="box_2"/>
$('#box_1').keyup(function(){
$('#box_2').val($(this).val());
})
Try something like:
$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});
Heres a fiddle: http://jsfiddle.net/otwk92gp/
You need to bind the first input to an event. Something like this would work:
$(document).ready(function(){
$("#a").change(function(){
var a = $("#a").val();
$("#b").val(a);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="a" />
<input type="text" id="b" />
If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.
Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.
var $field1 = $("#field_1");
var $field2 = $("#field_2");
$field1.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $field2.val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$field2.val(v1);
v2 = v1;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="field_1" value=""/><br/>
<input id="field_2" value=""/>

Categories