Javascript onFocus triggers on page load - javascript

Fiddle
So I'm having this problem.
I have a simple form:
<form method="post" action="login.php">
<input type="text" name="Username" value="Username" />
<input type="password" name="Password" value="Password" />
<input type="submit" name="submit" value="Log in" />
</form>
And this script:
function focus(element) {
console.log('focused ' + element.getAttribute('name'));
var elementValue = element.value;
var elementName = element.getAttribute('name');
elementValue = (elementValue == elementName ? '' : elementValue);
}
var fields = ['Username', 'Password'];
for (var i = 0; i < fields.length; i++) {
console.log(i + ': ' + fields[i]);
var input = document.getElementsByName(fields[i])[0];
console.log('input value: ' + input.value);
input.onFocus = focus(input);
}
It is supposed to create Focus event listeners for every of the inputs and call focus() function as user clicks on any of the fields. But for some reason, as console shows, it just calls the function once a loop for every of the fields and just stops not responding to future Focus events.
So my guess is there's something wrong with this line input.onFocus = focus(input);, but I don't know what. What am I missing?

On the line below, you're calling the focus function immediately and passing the return value (which is undefined). You also need to use onfocus not onFocus because the property name is case sensitive.
input.onFocus = focus(input);
Instead, you can use .bind() like so:
input.onfocus = focus.bind(null, input);
This will setup the function with the argument set, without actually calling it.
Updated fiddle

Because instead of assigning the focus function as the handler of the onFocus event, you're assigning its returned value (which is undefined).
Try this instead:
input.onfocus = focus.bind(input, input);
Or
input.onfocus = function() { focus(input);
Also, you need to change onFocus to onfocus.
See MDN

Related

Disable Button Until Fields are Full Pure JS

Trying to keep a button disabled until the form fields are filled in and I cannot seem to accomplish this. I've created a small example with a single field but the principle will be the same with a larger form.
Can anyone help?
Code:
function checkForm() {
var name = document.getElementById("name").value;
var cansubmit = true;
if (name.value.length == 0) {
cansubmit = false;
}
if (cansubmit == false) {
document.getElementById("submitbutton").disabled = true;
}
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton">Test me</button>
There are a couple of mistakes in your sample:
var name is assigned to the value string of the name element, then you check the value property of that - the string has no value property.
the id of the submit button is myButton so use that id to get it by id (when setting the disabled attribute).
You can disable the submitbutton until the length of the name input is greater than 0.
And disabling the button initially sounds like a good idea, right?
See corrected example below:
function checkForm()
{
var name = document.getElementById("name").value;
var cansubmit = (name.length > 0);
document.getElementById("myButton").disabled = !cansubmit;
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
You might also want to consider handling change via methods other than keypress - e.g. mouseup, etc... I tried adding onchange="checkForm()" and it works but only on blur (focus-change)...

Javascript Replace onKeyUp event with a string

Im not very good at JavaScript and need a hand with what I think is an easy script. Basically I have an input box that when the user types in a key it will disappear and change to whatever string I have. I could only get the one letter to change, so that I have something to show what i mean. So whenever a user types a message it gets replaced with an "h", what I want though is to have "hello" typed out letter by letter and not just "h" all the time and not "hello" all at once.
Here is the code.
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/))"
onkeyup ="this.value=this.value.replace(/\D/g,'h')">
</form>
JUST EDITED AS IT IS GIVING JS ERROR HOPE YOU WONT MIND:Are you trying something like this:
function replaceString(el){
var sampleText = "hello".split("");
var value = "";
console.log(el)
el.value.split("").forEach(function(str, index){
value += sampleText[index%sampleText.length];
});
el.value = value;
}
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/));"
onkeyup ="replaceString(this);"/>
</form>
If you want to simulate typing text into the textbox then you will need to use a timeout. The following function should suffice:
function simulateTyping(str, el)
{
(function typeWriter(len)
{
var rand = Math.floor(Math.random() * (100)) + 150;
if (str.length <= len++)
{
el.value = str;
return;
}
el.value = str.substring(0,len);
if (el.value[el.value.length-1] != ' ')
el.focus();
setTimeout(
function()
{
typeWriter(len);
},
rand);
})(0);
}
You'll need to pass it two parameters : the string to type e.g. "hello" and the element into which to type the string. Here's a simple wrapper function:
function typeHello() {
var el = document.getElementById('t1');
var str = 'hello';
simulateTyping(str, el);
}
When you call the typeHello function it will find the element with the "t1" id and type the "hello" text.

Intercept input entering

Is there a way to intercept the value the user inputs before it ever even appears in the element? I tried to use Object.defineProperty but it appears to not work for InputElement.value since
var value;
Object.defineProperty($('input')[0], 'value', {
get: function() {return value},
set: function(val) {console.log(val); value = val;}
});
doesn't appear to change any behavior. Or is oninput/onchange the only option? Since I'd rather have my code executes before the browser's.
http://jsfiddle.net/zpmu1xcu/
If you want to detect input before the text is entered by the browser, you can use the Element.onkeydown property. This event fires as soon as the key is pressed down, before the browser interprets the action.
var demo_i = document.getElementById('demo_i');
var demo_d = document.getElementById('demo_d');
demo_i.onkeydown = function(e) {
demo_d.textContent = e.which;
// Returning false stops the event from going any further
return false;
}
<input id="demo_i"><div id="demo_d"></div>
is this what you are looking for?
function InterceptInputValue($input) {
var value = $input.val();
// intercept value that changes and saved to value variable
$input.keydown(function(e) {
value += String.fromCharCode(e.keyCode);
return false;
});
this.getValue = function() {
return value;
};
}
var i = new InterceptInputValue($("input"));
$("input").blur(function() {
alert('input value is: ' + i.getValue());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
I think you're only option is keyup.
It is the only one that can capture the data and not leave any behind.
Using the snippet below, type test in each of the text boxes.
The code tries to reset the value to blank with each key stroke.
keyup is the only one that deletes the input with each stroke.
keydown clears the last character typed, once you leave the field.
keypress leaves the last character typed in the input field
var tbxKeyDown = document.getElementById('tbxKeyDown');
var tbxKeyUp = document.getElementById('tbxKeyUp');
var tbxKeyPress = document.getElementById('tbxKeyPress');
// [Jedi mind trick] ==> you entered nothing
tbxKeyDown.addEventListener('keydown', testKeyDown, false);
tbxKeyUp.addEventListener('keyup', testKeyUp, false);
tbxKeyPress.addEventListener('keypress', testKeyPress, false);
// Remove anything entered
function testKeyDown() {
tbxKeyDown.value = '';
}
function testKeyPress() {
tbxKeyPress.value = '';
}
function testKeyUp() {
tbxKeyUp.value = '';
}
KeyDown = <input type="text" id="tbxKeyDown" value="" />
<br/><br/>
KeyUp = <input type="text" id="tbxKeyUp" value="" />
<br/><br/>
KeyPress = <input type="text" id="tbxKeyPress" value="" />

i have code it can be sum two textbox values using javascript

i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again?
<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}
</script>
<input class="input_field2" type="text" readonly name="advance"
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">
You could keep a property on the read-only text field to keep the old value:
function B()
{
var adv = document.getElementById('advance'),
rec = document.getElementById('recamt');
if (typeof adv.oldvalue === 'undefined') {
adv.oldvalue = parseFloat(adv.value); // keep old value
}
adv.value = adv.oldvalue + parseFloat(rec.value));
rec.value = '';
return false;
}
You're calling the sum function every time the readonly input is focused using the new value. If you only want it to add to the original value, you need to store it somewhere.
HTML:
<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">
JS:
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onclick = function() {
this.value = parseFloat(originalValue) +
parseFloat(document.getElementById('recamt').value);
return false;
};
http://jsfiddle.net/hQbhq/
Notes:
You should bind your handlers in javascript, not HTML.
The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox.

not changing textbox value from ui and unable to display

taking value in 1st textbox and want to display it in 2nd..
1st <input type="text" value=" " id = "marks1" name = "marks1" onblur = "myFunction('marks1')" />
2nd <input type="text" value=" " id = "marks2" name = "marks1" disabled = "disabled" />
and on oblur I am calling a function. Whenever I change the value from UI, on function call I am getting the old value i.e. ' ' instead of changed value.
in the variable "value" the old value which i am getting, i am unable to display it on 2nd textbox.
function myFunction( txtname )
{
alert("call");
var txtobj = document.getElementsByName(txtname);
var value = txtobj[0].value;
alert("my value : "+value);
txtobj[1].value = value;
}
I know the code is okay, but it is not working at me. Is there any other way?
Works for me:
function myFunction(element)
{
var txtobj = document.getElementsByName(element);
var value = txtobj[0].value;
txtobj[1].value = value;
}​
http://jsfiddle.net/pwTwB/1/
Are you getting an error?
Try it this way:
function myFunction( txtname )
{
var txtobj = document.getElementById(txtname);
var target = document.getElementById("marks2");
target.value = txtobj.value;
}
Here is a simple way to set the next textbox's value.
function moveText(ele){
document.getElementById("marks2").value = ele.value;
}
Then use the following in your html markup
<input type="text" id="marks1" onblur="moveText(this)" />
<input type="text" id="marks2" disabled="disabled" />

Categories

Resources