Attach one element's event handlers into another in JS - javascript

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>

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()

Even the most basic Javascript is failing on me - but WHY?

I'm struggling with some very basic Javascript here (not a big fan or expert in Javascript at all!), and I just cannot wrap my head around why this fails....
I have some very basic HTML markup:
Value 1: <input type="text" id="int1" /> <br />
Value 2: <input type="text" id="int2" /> <br /><br />
<input type="button" name="add" value="Add" onclick="add();" />
and then some Javascript:
<script type="text/javascript">
onerror = unhandled;
function unhandled(msg, url, line) {
alert('There was an unhandled exception');
}
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
From my (Pascal- and C#-based) understanding, the add method should read out the values from the input elements with ID's int1 and int2 and add those values and then show the result.
Seems basic and harmless enough......
But even if I do enter two valid integers (like 10 and 20) into those two textboxes, I keep getting an There was an unhandled exception and I just cannot understand what is going wrong here.
Can someone enlighten me??
$.val() returns a string value. you need to convert both returned strings to numbers and then add the values.
try this
function add() {
alert(parseFloat($('#int1').val()) + parseFloat($('#int2').val()));`
}
You have a few different issues going on here.
Firstly, if you're using jQuery, it would be best to use a click event instead of an inline function call.
Second, the values are returned as strings from the inputs, so you must convert them by using parseInt()
Also, your error handler is useless if you're not alerting the error message, the msg argument in this case.
onerror = unhandled;
function unhandled(msg, url, line) {
alert(msg);
}
$("input[name=add]").click(function() {
var int1 = parseInt($("#int1").val());
var int2 = parseInt($("#int2").val());
alert(int1 + int2);
});
Fiddle: http://jsfiddle.net/9bepJ/
Well firstly, .val() will return a string. The addition operator won't add the numeric values of those strings, it will just concatenate the strings.
But that's not causing your exception. Get rid of the everything but the add function. It should work then.
<script type="text/javascript">
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
This is, of course, assuming you included the jQuery library since that's where the $() function comes from.
Try using binding onclick event instead writing it inline.
I have made fiddle for you. Check it out
UPDATE:
http://jsfiddle.net/rkhadse_realeflow_com/FhL9g/7/
<script>
function add() {
var int1 = parseInt(document.getElementById("int1").value);
var int2 = parseInt(document.getElementById("int2").value);
alert(int1 + int2);
}
</script>
Value 1:
<input type="text" id="int1" />
<br />Value 2:
<input type="text" id="int2" />
<br />
<br />
<button onclick="add()">Add</button>
As it looks like you're using $(..) functions, be sure you're including jQuery on the page, before you use those functions.
Aside from that, I always have scope issues when I put my event handlers in HTML attributes. Try putting them in your code, which has the added benefit of being unobtrusive JavaScript (a new pattern for cleaner, more maintainable code).
Also, add an id to your button:
<input type="button" name="add" value="Add" id="myButton" />
Add event handler in code and remove onclick attribute from your button
document.getElementById('myButton').onclick = add;

Simple HTML input onkeypress event not working

I'm new here (and to web development in general), and I have been trying to understand why my function is not being executed on the specified event.
I found this post, and it seems exactly like what I want, but even this did not work:
html <input type="text" /> onchange event not working
Any help would be appreciated. My exact code follows. I have some text input fields (actually search boxes), and ultimately I want to have it check a checkbox when the user enters data into the text fields, but it doesn't even seem to call the function.
I have tried a few variants while reading the post mentioned above. Here are some input field attributes I have tried:
<input type="date" name="dt" size="10" value="2012-07-21" onChange="SetCheckBox('d')" />
<input type="search" size="10" name="sl" value="" onChange="SetCheckBox('n')" />
<input type="search" size="10" name="sf" value="" onkeypress="SetCheckBox('n')" />
<input type="search" size="20" name="st" value="" onkeypress="SetCheckBox(this);" />
and here is my javascript:
<script language="javascript" type="text/javascript">
Function SetCheckBox(id) {
alert (id.value);
document.write('test');
}
</script>
I have tried not passing any arguments and just doing a document.write, but it doesn't seem to be calling the function. And yes, javascript is enabled and working elsewhere on the page just fine!
The script is in the body, just below the form.
The (lack of) behavior is the same in multiple browsers.
Thank you for any help you can provide.
Ray
For javascript the function keyword is lowercase.
Function SetCheckBox(id)
needs to be:
function SetCheckBox(id)
Also, you're not passing object to get an id, so...
function SetCheckBox(id) {
var ele = document.getElemenyById(id);
alert (ele.value);
document.write('test');
}
Several issues apart from the already mentioned uppercase F in Function
your function passes a variable called id but expects a field
you pass a string that is not an ID and not referring to a field
only the last version using (this) will work, but there is no value to alert
document.write will WIPE the page and all scripts on it when it is invoked after page load (e.g. not inline)
So code should be EITHER
function SetCheckBox(id) {
var val = document.getElementById(id).value
alert (val);
document.getElementById('someContainer').innerHTML=val;
}
OR
function SetCheckBox(fld) {
var val = fld.value
alert (val);
document.getElementById('someContainer').innerHTML=val;
}
Based on your description, my guess is you want to do this: DEMO
<input type="date" id="dt" name="dt" size="10" value="2012-07-21"
onkeypress="SetCheckBox(this)" />
<input type="checkbox" id="dtChk" />
using this script
function SetCheckBox(fld) {
var checkbox = document.getElementById(fld.id+"Chk");
// check if something is entered, uncheck if not
checkbox.checked=fld.value.length>0;
}
and maybe even with this addition
window.onload=function() {
document.getElementById("dt").onkeypress();
}
which will check the box if the field is not empty at (re)load time
in javascript function keyword is written in small letters and here you wrote F in caps.
onkeypress and onchange event should works
<body>
<script type="text/javascript">
function SetCheckBox() {
alert("1");
}
</script>
<input id = "test" value="" onkeypress="SetCheckBox();" />
<input id = "test1" value="" onchange="SetCheckBox()" />
</body>

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');

Execute any script in double quotes

how can i run any javascript in double quotes ?
For example:
<input type="text" value="" />
i would like to execute an alert or any other code in the value = "" (double quotes). Like:
<input type="text" value="<script> onmouseover=alert(0);</script>" />
the code show as a string on page. So is there anyway to execute script in double quotes ?
Ah, I see, you probably want to do something like this:
<input type="text" onchange="try{eval(this.value)}catch(e){}" />
That inline script will attempt to execute what's in its value attribute every time the tag is changed (and you blur out of the element). The try catch block is so that anything that would normally not work won't get executed. The eval function parses a string and runs it as Javascript code.
You leave yourself open to many forms of attacks when you use eval, so unless this is for purely educational or in house purposes, I would advise you don't use this.
The input object has its own events and you have to assign to them
For example to execute an alert when the mouse hovers over it:
<input type="text" value="testbox" onMouseOver="alert('testing');"/>
<input type="text" onmouseover="alert(0);" />

Categories

Resources