What I am trying to do is make the input box think that I am typing numbers into it rather than changing the value of said input. So the first thing I did was make the input box a variable:
var input = document.querySelectorAll("input")[1];
Then what I did was focus the input box to make it seem like I had clicked in it with my mouse:
input.select();
This is the part that I am now stuck on. What I would like to do is make the input box think that I typed a number into it, say, 41. If anyone could please tell me what code I need to put into console to make the input box think I typed in "41", it would be greatly appreciated. Thank you.
You can use setTimeout and add one character each time like this :
var input = document.querySelectorAll("input")[1];
input.select(); // you can also use input.focus()
input.value="";
var text = "41";
var l=text.length;
var current = 0;
var time = 1000;
var write_text = function() {
input.value+=text[current];
if(current < l-1) {
current++;
setTimeout(function(){write_text()},time);
} else {
input.setAttribute('value',input.value);
}
}
setTimeout(function(){write_text()},time);
<input type="text">
<input type="text">
This will work with any content you want to write, you simply need to adjust the variable with what you need.
I know this was really really long ago, but I'm currently working on a very similar problem and encountering the exact same issues that the original poster was encountering, and I found this code snippet (credit):
element.dispatchEvent(new KeyboardEvent("keydown", {
key: "e",
keyCode: 69, // example values.
code: "KeyE", // put everything you need in this object.
which: 69,
shiftKey: false, // you don't need to include values
ctrlKey: false, // if you aren't going to use them.
metaKey: false // these are here for example's sake.
}));
And the specific key codes you need can be found here.
This is definitely an extremely overcomplicated way of doing things, you'd need something to translate whatever input string you have into a list of instances of KeyboardEvent, and then dispatch them one by one, but as far as I can tell this is the proper way to truly "simulate" keyboard input.
Related
I have an input box in a component. I want to prevent the user from being able to add any input if the value of the input box contains more than 2 decimal places.
E.g. if a user inputs 10.95 I dont want to allow them write anything else after this value. They could still update it to 101.95 but it should prevent any input being added after the final decimal place.
The code I have so far is below.
class inputBox extends Component {
countDecimals(value) {
if(Math.floor(value) === value) return 0;
return value.toString().split(".")[1].length || 0;
}
updateValue(e) {
if(this.countDecimals(e.target.value) > 2) {
//prevent user from inputting into box after the decimal place...
}
}
render() {
return(
<input type='text' onChange={this.updateValue} />
)
}
}
You could use React controlled component and bind a state to the input's value atrribute. Then your onChange event handler will look like.
updateValue(e) {
this.setState({ value: e.target.value.toString().split(".").map((el,i)=>i?el.split("").slice(0,2).join(""):el).join(".")})
}
Worked for me.
document.getElementById("yourinput").oninput=function(){
this.value=this.value.toString().split(".").map((el,i)=>i?el.split("").slice(0,2).join(""):el).join(".");
};
Replace the value with a new value, that is shortened to two chars after each dot.
http://jsbin.com/soretokuse/1/edit
I think you need to save the oldvalue, that should work.
var input=document.getElementById('input'),
countDecimals=function(value) {
if(Math.floor(value) === value) return 0;
if(value.toString().split(".")[1])
return value.toString().split(".")[1].length || 0;
},
updateValue=function(val) {
if(countDecimals(val) > 2) {
input.value=input.getAttribute('oldValue');
}
};
input.oninput=function(){
updateValue(this.value);
input.setAttribute('oldValue',this.value);
}
<input id="input" type="text"/>
As far as my knowledge in Javascript and HTML goes there is no 'easy solution' for this. Working with both 'raw' JS and ExtJs forms has learned me that there are multiple ways to focus and manipulate a field. Which makes it hard to manipulate the inner value at the right time.
So allow me to split your issue in to multiple problems. Which I will attempt to tackle:
Triggering
You want your logic to run at all the times something happens to the field.
The following link provides you with the options:
http://www.w3schools.com/TAGS/ref_eventattributes.asp
When you use onchange it will trigger when someone changes the values after you blur the field (you click or tab away from the field). So that's no good.
You could try the key (up, down, press) events. But that excludes when you paste a value.
Long story short, you could in theory try to implement a function on every event you could think of to make sure you catch the users input and do what you want with it.
My solution is, start a timer when you focus a field and validate the value and do further logic. And finalize everything you wanted to do on blur.
Determining the correctness of the value
You could write some nifty regex or a single line statement that tells you if the value is correct. It's all the same in the end, it should fit your needs.
So something like:
var inputVar = element.value;
var inputFloat = parseFloat(inputVar);
var normalizeInput = Math.round(inputFloat * 100) / 100;
if(inputFloat > 0 && normalizeInput == inputFloat){
#correct value
}else{
#incorrect value
}
Handling correct/incorrect input
Now you want to handle the user input and do something.
Things like setting the field to disabled or read only would prevent further input and changes, but would not let your users do anything to your field.
As what I read is you want the field to not change in function, you want to be able to edit it.
So that leaves you with 2 options:
Editing the field content directly by overriding the element.value with the desired value.
Manipulating key inputs / selection to try and keep the cursor at same position the user left it while correcting the false input.
I would opt for the former as it is a lot less of a hassle, although it might mess with the cursor position (browser dependant).
Final implementation
So what I propose combining all the above:
On focus you start running a setTimeout or setInterval
http://www.w3schools.com/jsref/met_win_settimeout.asp
http://www.w3schools.com/jsref/met_win_setinterval.asp
In the function run then, you check if there is a previous value set.
The first time it is NOT so:
You have to hold this previous value somewhere, you could hold it in a variable within javascript or put it in to the field in the DOM.
http://www.w3schools.com/jsref/met_element_setattribute.asp
var inputElement.setAttribute('old_value', oldValue);
Now you check if this value is correct before saving it, else just default it back to blank (or attempt to normalise the value to something that validates, you could keep cutting away characters at the right for example).
Now on each run you check if the value is correct. If the value is correct, you hold the new value as the 'new' previous value (and calling setTimeout again if you use that method).
If it is not correct you write back the old value or attempt to normalise the input value and if that fails use the last correct value.
On the blur event you clear the setTimeout or setInterval running in the background:
http://www.w3schools.com/jsref/met_win_cleartimeout.asp
http://www.w3schools.com/jsref/met_win_clearinterval.asp
(Alternatively you could check if the document.activeElement is the same as the one that is run on this 'loop' so it knows when to stop).
On blur you check the value one last time and do the same logic to prevent false input.
PLAN B
Use the HTML5 number input field:
HTML 5 input type="number" element for floating point numbers on Chrome
Try <input type="number" step="0.01" /> if you are targeting 2 decimal
places :-).
edited Apr 27 '15 at 18:10
Andre Figueiredo
Which only works on browsers that support it.
I am trying to implement auto-complete using CodeMirror show-hint addon, specifically with sql-hint. I want it auto-complete as I type.
What I am doing right now is,
codemirror_editor.on("change", function(instance) {
CodeMirror.commands.autocomplete(instance);
});
But the problem is, it completes words before I even type a single letter for a word. For example after space, it gives a long list of all possible tokens. I want it to show up only if some characters are typed. Can someone please help with that?
Before firing the autocomplete command, check whether the cursor is actually after 'some' (whatever 'some' means) letter characters. Also, do nothing when instance.state.completionActive is true, since that means there's already a completion popup open. Finally, you probably want to listen for the "inputRead" event instead of "change", so that you don't trigger when a change is made to the document in a way that didn't involve the user typing.
This is how I solved this, after Marijn's answer.
codemirror_editor.on("inputRead", function(instance) {
if (instance.state.completionActive) {
return;
}
var cur = instance.getCursor();
var token = instance.getTokenAt(cur);
var string = '';
if (token.string.match(/^[.`\w#]\w*$/)) {
string = token.string;
}
if (string.length > 0) {
CodeMirror.commands.autocomplete(instance);
}
});
This may be specific to SQL.
I am answering my own question to share the actual solution for the question.
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
I've found some code on a site and been tinkering with it a little. It involves some functions to add and delete students (the add code is below) from an array - into a value field. I can't figure out why in tarnations we need this extra piece of code, however.
Here is the js code:
var students = ['Paulie', 'Nicole', 'Kevin', 'Mare'];
function addClick(){
var addRemove = document.getElementById('addRemoveStudent');
var studentsBox = document.getElementById('studentsBox')
students.push(addRemove.value);
addRemove.value = '';
studentsBox.value = students.join(', ');
}
My question is: Why do we need the addRemove.value = ''; line? I've tested it without that code and it still works fine. Is there a reason we need that?
I can send more code including the HTML but didn't what to overwhelm anyone with the volume.
Thanks so much in advance!
-Anthony
It's not necessary. I guess semantically it means to clear the addRemove box first before replacing the value.
It's optional, but it's simply to clear the text box so the user can enter a brand new value if they want to run the function again.
To clear the value of the addRemoveStudent ( I think it is a input type="text") Just for it, It is not needed in the array. Just to clear the value of that control.
Presumably addRemove is an input element. Setting the value property of an input element to an empty string '' means that the input is emptied: it will have no text in it.
My guess is that this function is run when a button is clicked, so it adds a new student to the array, updates the studentsBox field with the right data, and clears the input element so you can add more if the user wishes to do so.
i am developing an autocomplete feature.but i am facing one problem there...
when i click on the suggestion box one of the results will not enter into the suggest html box...
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
position = oTr.id.substring(2, oTr.id.length);
updateKeywordValue(position);
}
can you plz tell the solution
thanks
function updateKeywordValue(oTr)
{
var oKeyword = document.getElementById("keyword");
var strKeyword="";
var crtLink = document.getElementById("a" +oTr.id.substring(2,oTr.id.length)).toString();
crtLink = crtLink.replace("-", "_");
crtLink = crtLink.substring(0, crtLink.length);
oKeyword.value=unescape(crtLink.substring(googleurl.length, crtLink.length));
strKeyword=oKeyword.value.toString();
if (oTr.id.substring(2,oTr.id.length)==0)
{
oKeyword.value=strKeyword.substring(3,strKeyword.length);
}
selectedKeyword=oKeyword.value;
}
you should get rid of the second parameter in the substring() method. Since you just want the remainder of the string, I'm guessing, that is the default if you don't set a second value.
position = oTr.id.substring(2);
My guess is that you are getting the value of the keyword from the id, and pushing that into the input box, right? If that's the case, we'll need to see more of your code. Specifically, I'd like to see the updateKeywordValue function and I'd also like to know if the text that they are hovering over is the text you are trying to send the input box. If so, you could probably simplify the whole thing and go with something like:
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
keywordbox.value = oTr.innerHTML;
}
But this is based on the assumption that the only data inside the hovered row is the text, and no other html. And I had to make up a name for your input box.
But if this way off, this is because we need more information to see the real problem.