Simple HTML input onkeypress event not working - javascript

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>

Related

Scan QR Code value into an input field

This is the scanner I am using...
On Web : https://atandrastoth.co.uk/main/pages/plugins/webcodecamjs/
On Git : https://github.com/andrastoth/WebCodeCamJS
It's working 100%. But I need to add some custom extra's.
When the QR Code is scanned it outputs my result into this paragraph tag.
<p id="scanned-QR"> The scanned code text value is printed out here </p>
However I need it to be an input field so I can use it's value in a url.
How can I set an input field equal to the value submitted to the Paragraph tag?
I have tried these methods and they failed :
Method 1
<input id="scanned-QR"> The scanned code text value is printed out here </input>
Method 2
<p id="scanned-QR" onchange="update"></p>
<input id="code_id_value" type="text" name="" value="">
<br>
<script>
function update(){
var code_id_value = document.getElementById("scanned-QR").innertext;
document.getElementById("code_id_value").value = code_id_value;
}
</script>
The key that you're missing is that the T in .innertext needs to be capitalised (as .innerText).
In addition to this, using inline event handlers is bad practice, and you should consider using .addEventListener() instead of onchange.
This can be seen working in the following:
document.getElementById("scanned-QR").addEventListener("click", update);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerText;
document.getElementById("code_id_value").value = code_id_value;
}
// Demo
update();
<p id="scanned-QR">Text</p>
<input id="code_id_value" type="text" name="" value="">
Hope this helps! :)
So this is the solution I came up with.
Here's my paragraph and input function
<p id="scanned-QR" onchange="update">SCAN.BZ</p>
<input id="code_id_value" type="text" name="" value="">
Here's my function. WITH a interval for every millisecond or faster "I think it's every millisecond".
It runs smoothly and doesn't lag. and the result is practically immediate.
<script type="text/javascript">
setInterval(update,1);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerHTML;
document.getElementById("code_id_value").value = code_id_value;
}
update();
</script>
Thanks for the help "Obsidian Age" Really appreciate it. :)

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;

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>

JavaScript clear text box input not functioning properly

I know that this is an embarassingly easy question, but I can't figure out the problem, and that's why I'm asking the question, so please don't reiterate this point.
Anyway, I'm just working on something here, and when I tested my page to see how things were going, I realized that my calculate() method isn't clearing text input like I want it to.
Here is the markup and the script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculate(){
var valuea = document.form1.variablea.value;
var valueb = document.form1.variableb.value;
var valuec = document.form1.variablec.value;
document.form1.variablea.value = "";
document.form1.variableb.value = "";
document.form1.variablec.value = "";
}
</script>
</head>
<body>
<form name="form1">
a:<input name="variablea" value="" type="text">
<br/>
b:<input name="variableb" value="" type="text">
<br/>
c:<input name="variablec" value="" type="text">
<br/>
<input name="calculate" value="Calculate!" type="button" onClick="calculate()">
</form>
</body>
</html>
Please tell me if you see anything.
You might want to try using another name. I tried to call the "calculate" function but it keeps on giving me an error saying "calculate" is not a function. But when I call the function "calculateQuad" and change the onClick event to call "calculateQuad" it works.
Not very sure, but if you don't want to move to jQuery here's what you could try:
function calculate() {
var inputa = document.getElementById('inputa');
inputa.value = '';
}
Just test this, having an id "inputa" on one of the input boxes. I only know how to get elements by id, name or tag in raw Js. Of course, you could then extend your code to what you want using one of these methods to get your form elements.
Inside the onclick method is there a reference to the item you clicked. It is named the same as the name you put on the item, "calculate". This results in that "calculate" does not refer to the function, but the input tag.
To resolve this by either typing
onclick = "window.calculate()"
or rename the name of either the input-tag or the function.
change the name of the input button to something else:
<input name="calcul" value="Calculate!" type="button" onClick="calculate()">
and it works. Since the calculate function is residing directly under the global object, I have a weird feeling your name attribute is somehow overwriting it.
Just throwing this out there. I will take a deeper look at why this is happening though.

Categories

Resources