Assign onfocus to DOM elements in runtime - javascript

I am interested in assigning onfocus or other similar functions to a DOM elements in runtime.
General Case:
<input type="text" id="box" onfocus="inputFocused()"/>
Runtime Assignment Case:
<input type="text" id="box"/>
And in the script
$('#box').onfocus = inputFocused();
inputFocused() is nothing more than a simple function. It appears not working properly.
Thanks for any help.

You could use it as :
$('#box').on('focus',inputFocused);
Hope this helps.
$('#box').on('focus',inputFocused);
function inputFocused(){
alert('focused');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box"/>

Just replace
$('#box').onfocus = inputFocused();
with:
$('#box').focus(inputFocused);
It's the jquery correct syntax. From the docs:
This method is a shortcut for .on( "focus", handler ) ...

Related

Pass text of input to calling function (yes it is possible)

I know this question has been asked -and answered- multiple times. However I found a new solution - but do not fully understand it. The setup is this:
<input id="input1" onchange="GetText()"/>
All answers i found suggest to use the id to get the value of the input.
function GetText(){
alert($("#input1").val());
}
$(this).val() does not work here.
Another way to use the value of the #input1 would be to use this.value in the calling function:
<input id="input1" onchange="GetText(this.value)" />
This passes the value as a parameter to the function.
However I found a JQuery sample that attaches a function to #input1 and makes $(this).val() work.
$("#input1").change(function(e){
alert($(this).val())
});
Against all answers here at stackoverflow seeing that it is possible to attach a function to a input field and have access to the value of it - I ask myself how I would have to write this function and not attach it with JQuery. Or can it be only attached with JQuery? Why?
Here is a fidle with this setup to play
You either pass reference to input object as a parameter in inline call to callback like this:
<input id="input2" onchange="GetText(this)" />
and then in javascript:
function GetText(_this){
alert(_this.value);
}
Fiddle here
Or you can attach function directly to input object like so
document.getElementById('input2').getText = function() {
alert(this.value);
};
and in html:
<input id="input2" onchange="this.getText()" />
Fiddle here
Basically this object in javascript is bound to context, in which the function has been created. When you define function globally, like GetText in your example, this is bound to global object in scope of that function.
<input id="input1" onchange="GetText.call(this)"/>
or
<input id="input1" onchange="GetText.apply(this)"/>
Will call the GetText function with the input as the value of this. Then you can use $(this) or this.value within the scope of GetText.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
If you're looking for a similar Vanilla JS function that you can put into you're HTML, which I actually don't recommend, because I support JavaScript HTML separation, it would be something like:
function getInputVal(context){
alert(context.value);
}
In your HTML:
<input id='whoCares' name='whoCares' value='Some Value' onchange='getInputVal(this)' />
Inline JS is not easy to maintain, especially if there's so much of it. It is better to separate your JS and HTML.
//Wait for DOM to load
$(function() {
//set up change event listener --> anonymous function
$('#input1').on('change', function() {
alert( this.value );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" />
Or if you want to use a named function:
//wait for DOM to load
$(function() {
//Define function
function GetText(){
alert( this.value );
}
//set up change event listener --> named function
$('#input1').on('change', GetText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="input1" />
All answers i found suggest to use the id to get the value of the input.
That's actually a pretty bad design; you want to create event handlers that can be unaware of the elements they're attached to.
The example without using jQuery would look like this:
var input = document.getElementById('input1');
input.addEventListener('change', function(event) {
alert(this.value);
}, false);
<input id="input1" />
See also: addEventListener()

jQuery click function on an array of inputs

I try to implement a change function on every input field named plz_von.
<input type="text" name="plz_von[]" class="plz_von" placeholder="10000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="20000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="30000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="40000">
I want to do it this way:
$('input[name="plz_von[]"]').change(function() {
alert("got it");
});
I don't know what's going wrong. Any idea? I tried it with the class name as well.
Because [ ] is an attribute selector. You need to escape it.
$('input[name="plz_von\\[\\]"]')
Since you have a class that is common, you might as well use that instead.
$('input.plz_von')
Thanks all for the support. Finally I found the failure.
I had to put the jQuery code into the ready function! This is quite clear, because the function cannot by added to the inputfield, when the input field isn't already loaded in the DOM.. grrr
$(document).ready(function() {
$('input[name="plz_von[]"]').change(function() {
alert("hu");
});
});
Best regards,
Marco

Setting HTML textbox value using javascript function?

I'm using this code to set the HTML textbox value using Javascript function. But it seems to be not working. Can anyone point out, what is wrong with this code?
Whats your Name?
<input id="name" value="" />
<script type="text/javascript">
function setValue(value){
var myValue=value;
document.getElementsById("name").value = myValue;
}
</script>
the "value" is came from my android java class using this codes
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/webpage");
web.loadUrl("javascript:setValue("+ value +")");
function setValue(value) {
var myValue=value; //unnecessary
document.getElementById("name").value= myValue;
}
But then as pointed out in the comments, you need to call setValue(value) somewhere in your code. Right now you just defined the function is never called.
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
You are using document.getElementsById("name") it should be document.getElementById("name")
not Elements it is Element
You are not linking the function to anything. For example, a click:
<input id="name" value="" onclick="javascript:this.value=12;"/>
Replace the onclick attribute for your desired function, whatever it does (you need to be more specific)
Also, there is no language attribute (at least not anymore) use type="text/javascript" instead
Here is a fiddle: http://jsfiddle.net/4juEp/
Click the input to see it working.
Look at this second fiddle. http://jsfiddle.net/4juEp/1/
which loads whatever is defined in the hid input to the name input.
Firstly, you have a typo in your javascript function i.e. you have used getElementsById as compared to getElementById
To set the value of the textbox on page load, I suggest you use an alternative
<body onload="setValue('yourValueToSet');">
<!-- Your usual html code in the html file -->
</body>
I think you are missing the quotes,
try,
web.loadUrl("javascript:setValue('"+ value +"')");
also consider about the typo.
Check this out:
<body onload="setvalue($value);">
Whats your Name?<input id="name" name="name" value=""/>
<script type="text/javascript">
function setValue(value){
document.{formname}.name.value = value;}</script>
It's not Elements
It's Element
You should use document.getElementById('object-id');

Attach one element's event handlers into another in JS

Let's say I have this part.
<input id="text1" type="text" name="text1" onchange="alert('valueA');" /><br />
<input id="text2" type="text" name="text2" /><br />
What I'd want to do is to get the onchange event handler of the input="text1" and attach to another element's event, "text2".
So far , it's okay.I can get DOM0 hanlder of input "text1" and attach to text 2 as DOM2 .
_handler= $('#text1')[0].onchange;
$('#text2').change(function (event) {
if (typeof _handler=== "function") {
_handler.call(this, event);
}
But, the problem is , I want to change/add some js codes before attaching into "text2".
For example , before attaching into "text2", I want to change "alert('valueA');" into "alert('valueA.This is text2')";
How can I do to achieve this?
The alert statement is just the example ,and please don't give solutions something like storing alert message into global variable, show the variable's value..etc.
Thanks.
This cannot be done. You cannot change the code inside of a function.
Although Javascript functions are mutable objects, you can only add properties and methods to them, but you can't change the code inside of 'em.
If you want to use the evil eval (as you've specified in the comments), you could convert the function to a string, replace whatever text you want inside the function, and then eval it:
$('#text2').change(function (event) {
eval(
'(' + $('#text1')[0].onchange.toString().replace('valueA', 'valueB') + ')()'
);
});
And here's the fiddle: http://jsfiddle.net/A4w2W/
But, please please please don't do this. This is the worst possible way to write code, ever!!
You should seriously reconsider your approach to this whole matter.
Technically, no. But there are other solutions.
<script type="text/javascript">
<!--
alertvalue = "valueA";
//-->
</script>
<input id="text1" type="text" name="text1" onchange="alert(alertvalue);" /><br />
<input id="text2" type="text" name="text2" /><br />
<script type="text/javascript">
$('#text2').change(function(event) {
alert(alertvalue + '. This is text2');
});
</script>

Add one handler in terms of another?

I have a tag with a complex "oninput" handler, e.g.
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...."/>
I want to add another handler that simply calls that one. My initial though was that this would work:
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...." onfocus="this.oninput"/>
But it doesn't. What should I be doing? Thanks.
Edit: I thought that onfocus="this.oninput" would copy the reference to the function, that's why I left off the parentheses for a call.
this.oninput() (note parentheticals) should work:
<input id="x" type="text" name="x"
oninput="console.log('test');" onfocus="this.oninput();"/>
http://jsfiddle.net/9kNrW/
This could work?
... onfocus="this.oninput()"
I assume there's no way to have the generated code be outsourced as proper functions that you could call from both event handlers...
Short answer:
Use parens: onfocus="this.oninput();"
If oninput references this or the event object, you need to add a little more:
onfocus="this.oninput.call(this, event);"
Explanation:
If you were attaching the event handlers in code, your syntax is correct. Because you are setting a function reference. Ie,
myInput.onfocus = myInput.oninput;
But, when attached in the markup, the code between the quotes actually is itself a function. Eg,
<span id="foo" onclick="alert('hello world');" />
Is equivalent to:
document.getElementById("foo").onclick = function () {
alert('hello world');
};
So your code as written is the equivalent of:
document.getElementById("x").onfocus = function () {
this.oninput; // returns a function reference. Does not call the function.
};

Categories

Resources