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;
Related
Struts Version: 2.3.16.3
Is there a way to populate a list of objects without having to specify the index? Currently I have to reference the collection like so:
<input name="myCollection[0].myProperty" value="some value" />
I really want to be able to do something like this:
<input name="myCollection[].myProperty" value="some value" />
I am dynamically adding and removing elements on the page with JavaScript and it has been a pain to get the indexing right with the JavaScript. Rather just have the backend add to the end of the collection in the order the elements come across from the form. Similar to how PHP processes it.
The docs for the parameters interceptor say that it is really just a ognl expression that the input name is binding to. I went to the ognl docs and it says you can reference array's like this:
array["length"]
which would be the next element in the array. The parameter interceptor is spitting out a message that it is rejecting this parameter name. I would really like to find a way to make this happen, even if it means extending the parameters interceptor.
Well, since
you are manipulating the page with Javascript
you are having troubles detecting / updating the index of elements when adding / removing them
the simplest solution is:
use the syntax you prefer when manipulating them, for example myCollection[].myProperty, and
convert them into the form desired by Struts in a pre-submit function.
This way you don't have to bother with the indexes while manipulating the elements, but only once, at the end, when you can simply loop them by name or something, and change their name with javascript by assigning the right index.
A kick-off example with jQuery:
$(function() {
$('#myform').submit(function() {
$('[name^="myCollection[]"]').each(function(index) {
var oldV = this.name;
var newV = oldV.replace("myCollection[]", "myCollection[" + index + "]");
console.log("was: " + oldV + " - now is: " + newV);
this.name = newV;
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform">
Open Javascript Console, then press submit, then inspect input elements
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<button>submit</button>
</form>
You need somehow to identify which object some property belongs to. Indexes are simplest way to do that, so you cannot just remove them.
There are many ways to achieve what you want. Look at Andrea's answer for one possible solution using javascript.
You can also pull object properties to simple lists and later set them to object.
E.g.
private List<String> myProperty;
can be referenced in JSP w/o indexes:
<input name="myProperty" value="first value" />
<input name="myProperty" value="second value" />
Of course you if you have many properties you need to somehow sync them in JSP in such way that order and size of the properties in list is consistent for every property.
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>
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');
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>
I'm trying to have a value (key) that updates to correspond with a number in a textbox (angle) divided by a value (25). However, for some reason, the changeMe function doesn't seem to be executing. Am I using onchange incorrectly?
<script type="text/javascript">
function changeMe(x)
{
var y=document.getElementById(x).value;
y = (y/25);
y = (Math.round(y));
document.getElementById(key).value=y;
}
</script>
<form method="POST" action="">
Your Angle: <input type="text" name="angle" id="angle"
onchange="changeMe(this.id)" value="0"/>
Key: <span id="key">0</span><br />
</form>
Change the line
document.getElementById(key).value=y;
to
document.getElementById('key').innerHTML=y;
To see if it's being called, just add this as the first line:
alert("Hey, I'm being called!");
Now, I already see a problem here: in the last line of your function, you're doing getElementById(key), but you should enclose key with double quotes. If not, it's being considered a variable instead of a string.
The changeMe(this.id) bothers me, I am using to seeing just (this), but, the best way to know what is going on is to use either the Web Developer extension in IE8 (I press F12 and it comes up) or, preferably, Firebug, on Firefox, and then you can put in a break point at the beginning of the changeMe function and see what is passed in, as there may be an error.
And the other two already mentioned about the problem with your getElementById.
The last line document.getElementById(key) should be document.getElementById("key").
By the way you can simplify this a fair bit by passing the <input> element directly instead of its id:
<script type="text/javascript">
function changeMe(angle)
{
var key = document.getElementById("key");
key.innerHTML = Math.round(angle.value / 25);
}
</script>
<form method="POST" action="">
Your Angle: <input type="text" name="angle" id="angle"
onchange="changeMe(this)" value="0"/>
Key: <span id="key">0</span><br />
</form>
Try using the suggestion by James Black to use onchange="changeMe(this)", your function becomes simplified
function changeMe(x) {
y = Math.round(x.value/25);
document.getElementById('key').innerHTML = y;
}
Notice the document.getElementById('key').innerHTML = y, This will replace the inner html (as the name describes), I think that is what you wanted to use.