Check when an input text change value - javascript

How i can detect when an input value change when i'm filling the input with the path of imagen getting from filemanager.
I dont even know how it's called when the input is getting filled that way. (After select the image, automatically the input get the path as value)
I already tried this:
$('#my-input').on('change', function() {
alert("You changed the value of the input");
})
$('#my-input').on('input', function() { alert('some text') })
But this only works when user get interaction with the input i mean on keyup, keydown, etc.
Is that possible to do?
Thanks and sorry for the bad english.

If I understand correctly, you want to do this
document.getElementById('my-element').onchange();
after you fill the value via code as opposed to user entering a value.
Example here
document.getElementById('my-button').onclick = fillInput;
document.getElementById('my-input').onchange = inputChanged;
function fillInput(){
document.getElementById('my-input').value = "Test value";
document.getElementById('my-input').onchange();
}
function inputChanged(){
document.getElementById('my-input').style.border = "1px solid green";
}
<input id="my-input" type="text" />
<input id="my-button" type="button" value="Fill Input" />

Related

How to make data input readonly, but showing calendar?

I can't find any solution for this anywhere. I would like to allow user to see calendar when clicking on my input, but when user will try to change the value, it shouldn't change (or immediately change back for value, what was at the beggining).
Readonly attribute removes calendar, so I was trying to do it different ways like use onchange/onclick functions to restore my value after event, but the value was changing anyway.
So for now my input looks like this:
<input class='test' type='date' value='2020-06-04' onkeydown='return false' >
So at least user can't change value of my input using keyboard. Could you help me?
You might try to set a time limit
<html>
<body>
<input type="date" value="2020-06-04">
<input type="date" value="2020-06-04" min="2020-06-04" max="2020-06-04">
</body>
</html>
If I understood correctly, this is what you want.
HTML
<input class='test' type='date' value='2020-06-04' />
JavaScript
const date = "2020-06-04";
const input = document.querySelector('.test');
input.onkeydown = function(e) {
return false;
}
input.onchange = function(e) {
this.value = date;
}
Check out this JSFiddle
EDIT
function preventInputChange(input, staticValue) {
input.onchange = function(e) {
this.value = staticValue;
}
}

Is it possible to detect which input field was invalid upon form submit?

Using the code below, I am able to use .on("invalid") function to detect if there was an error with a field when submitting a form. If there was an error, I then check if both the input and textarea if either of them or empty, too long or too short and add the class .error.
However I am wondering if there is any way to simplify my code so that I don't have to run additional if statements inside the function.
$("form input, form textarea").on("invalid", function(event) {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (!input1.value || input1.value.length < 9 || input1.value.length > 69) {
input1.classList.add('error');
setTimeout(function() {
input1.classList.remove('error');
}, 500);
}
if (!input2.value || input2.value.length < 21 || input2.value.length > 899) {
input2.classList.add('error');
setTimeout(function() {
input2.classList.remove('error');
}, 500);
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" minlength="8" maxlength="70" required>
<textarea id="input2" maxlength="900" required></textarea>
<input type="submit">
</form>
Here is an example of what I am looking for, where x is the field (the input or textarea) which caused the form to be invalid.:
$("form input, form textarea").on("invalid", function(event) {
x.classList.add('error'); // variable x
setTimeout(function() {
x.classList.remove('error'); // variable x
}, 500);
});
I would ideally like to stick to JavaScript, however I appreciate that jQuery may be needed.
Here is a possible solution that doesn't exactly find the target with javascript, but uses the oninvalid event listener in html.
<input type="text" oninvalid="alert('You must fill out the form!');" required>
When the form returns invalid, instead of it being packaged as a form event, this will trigger as an input event. You can make it do whatever you like in javascript when that specific input is incorrect upon form submission.
https://www.w3schools.com/jsref/event_onsubmit.asp
The event onsubmit perhaps will be a better option. Is valid for all browsers
https://www.w3schools.com/jsref/event_oninvalid.asp
Instead, if you use oninvalid you will find problems with the Safari browser
<form onsubmit="validateForm()">
Enter name: <input type="text">
<input type="submit">
</form>
function validateForm() {
//your code here
if(validationfails){
return false; //if arrives here means the form won't be submited
}
}
I was able to solve this, particularly thanks to the suggestion by John Paul Penaloza, by using oninvalid on the input and textarea field. I called a function which then added the class .error to the input field - it does the same as the code in my question, but simpler:
function error(field) {
field.classList.add('error');
setTimeout(function() {
field.classList.remove('error');
}, 500);
}
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" oninvalid="error(this);" minlength="8" maxlength="70" required>
<textarea id="input2" oninvalid="error(this);" maxlength="900" required></textarea>
<input type="submit">
</form>
Or you can think differently and offer real time error reporting.
Add an id="myForm" to your <form> element, and then use Js in a lines of:
var allInputs = $('#myForm :input');
var inputsFuked = []
allInputs.each(function( index ) {
console.log(allInputs[index]);
$(allInputs[index]).change(function() {
if (allInputs[index].checkValidity()) inputsFuked[index]=1;
else inputsFuked[index]=0;
});
});
Here is working JSfiddle with couple of more elements without validation.
This will bind on change code to be executed every time some input changes. This is an example so it only toggles values in array. When you wanna validate, you simply check which are wrong. If you stored elements in array you could state which element. Simply switch toggle index logic to add/remove from array.
But with this contraption you can do way better, you can write instant reaction to invalid element. Instead changing index in array you could prompt alert, display error, make element red. Basically interact with the user the moment he focused out of element where he made input error instead doing it passively at some point after.

forcing focus to remain on a form text element until the value is numeric

I have a form which has input fields that expect numbers only.
I'm using javascript to validate the form when the value of the field changes.
If the value is numeric, do nothing.
If the value is not numeric, set it to zero and put focus in that text field. Essentially, I'm trying to trap the cursor in that field until a numeric value is entered. For some unknown reason, focus is not being placed on that form element. cell.focus() does not work. I've even tried document.getElementById(cel.getAttribute("ID")).focus(); What might I be doing wrong?
<html>
<head>
<script>
function NAN(cell){
if (cell.value != "") {
var re = /^(0|[1-9][0-9]*)$/;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = "0";
cell.focus();
}
}
}
</script>
</head>
<body>
<input type="text" name="num" value="" onchange="NAN(cell)"/>
</body>
</html>
Your problem is in the onchange attribute:
<input type="text" name="num" value="" onchange="NAN(cell)"/>
The value is executed as JavaScript code directly. You're passing code, not just a generic signature or prototype.
Inside those event handler snippets, there's a special object this defined, referring to the current DOM element (the input tag in this example).
(Just to mention it, there is also a second predefined object event, which most likely caused your confusion.)
As a simple fix for your issue, replace cell with this in the call and it should work:
<input type="text" name="num" value="" onchange="NAN(this)"/>
It's also important to note that you should keep in mind that this verification requires JavaScript to be executed. If it's disabled, the user might still pass any values, so you should check the value server side as well (assuming this isn't just client-only code).
As an alternative to using JavaScript, you could just use HTML5 to force a specific pattern on inputs. In this case this would be trivial to do:
<input type="text" name="num" value="" pattern="(?!0)\d+" title="Quantity">
The user won't be able to submit the form unless the pattern is validated, so there's no need to force the input focus. The pattern always has to match the full value, from beginning to the end. The title attribute is typically used to provide more information in the error popup.
There are two things done:
You have to change cell to this with onchange.
According to this question at least with Firefox setTimeout has to wrap this focus-method so that it works as expected.
And a more user-friendly approach is inserted as well at the second input-field.
Hope this example helps you:
function NAN(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
}, 0);
}
}
}
/*
* a more user friendly approach
*/
function NAN2(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
markElement(cell);
}, 0);
}
else{
tickElement(cell);
}
}
}
function tickElement(cell){
cell.setAttribute('style','border: 1px solid green');
}
function markElement(cell){
cell.setAttribute('style','border: 1px solid red');
}
<p>
Your approach(onchange):
<input type="text" name="num" value="" onchange="NAN(this)"/>
</p>
<p>
Or you can use a more user friendly approach to notify an user right now when they are tipping something wrong (onkeyup):
<input type="text" name="num" value="" onkeyup="NAN2(this)"/>
</p>

Edit/Cancel Button in Javascript

I have a form where the user can edit their text. I want the user to be able to retrieve their text if they delete it by hitting the cancel button.
How would I be able to retrieve a users text if they edit the original text, and when they press cancel the original text in the form before the edit comes back?
You could use data-* attributes to do this by adding data-original-text to the input like :
<input name='first_input' data-original-text='First input text' value="First input text"/>
And add a click event to the cancel button that will get the data attribute and assign it to the value :
$('form').on('click','#cancel',function(){
$(this).closest('form').find('input').each(function(){
$(this).val($(this).data('original-text'));
})
})
Hope this helps.
$('form').on('click','#cancel',function(){
$(this).closest('form').find('input').each(function(){
$(this).val($(this).data('original-text'));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name='first_input' data-original-text='First input original text' value="First input original text"/>
<input name='second_input' data-original-text='Second input original text' value="Second input original text"/>
<button id='cancel'>Cancel</button>
</form>
Something like the following could be built upon so that they could make multiple changes and still have the previous text available on change.
// JavaScript source code
var orginalText = "Please Enter Some Text here";
var newTest = "";
$(document).ready(function () {
$("#target").change(function () {
newText = this.text;
});
$(".cancel").on("click", function () {
$("#target").text(orginalText);
});
});

Is it possible to repeatedly use the same text box to get input from users in HTML & Javascript?

So I have a created a text box using html code along with a button for "confirm"
<input type="text" id="myInput" style="height: 10px; width: 50px" value="">
<button onclick="enter_value()">Confirm</button>
What I intend to do is to use the same text box over and over for different inputs as the website guides the user to do different tasks (which all functions are written in js)
I'm trying to figure out a way to use this same text box for all inputs users have to insert, but so far nothing is working.
I tried creating a function like:
function enter_value(){
var name = document.getElementById("myInput").value;
}
This should be able to store the value of the input in the variable name. Problem is, I want to execute this when button is pressed, but the button is not responding and the variable "name" always returns "Enter Your Input Here" (is this default?)
What am I missing here?
You can definitely re use the same text box to take in more than one piece of information. The question is how do you store the info in the process. So you can keep the onclick handler that you already have, then change what you do with the input based on the state of the page.
Current Step: <div id="current_step">name</div>
<input type="text" id="myInput" style="height: 10px; width: 50px" value="">
<button onclick="enter_value()">Confirm</button>
<div class="results">
<div id="name_result"></div>
<div id="addr_result"></div>
</div>
function enter_value(){
var curStep = document.getElementById("current_step").innerHTML,
curValue = document.getElementById("myInput").value;
//do some error testing here, if it is a bad submission dont continue
if (curValue == "") return false;
if (curStep == "name"){
document.getElementById("name_result").innerHTML = curValue
document.getElementById("current_step").innerHTML = "address"
}
else if (curStep == "address"){
document.getElementById("addr_result").innerHTML = curValue
document.getElementById("current_step").innerHTML = "Done!"
}
document.getElementById("myInput").value = '';
}
You should be able to use this to get started

Categories

Resources