I am fairly new to javascript and I am 13. So I am new to events in javascript. I would like help on this code:
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
if (x=="Kyle")
{
document.write("Correct!");
}
else
{
document.write("Incorrect!")
}
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
</body>
I want it to say correct when I type my name. Please help. Thanks
the line
if (x=="Kyle")
should read
if (x.value=="Kyle")
x represents the element, not the element's value.
I hope this helps. Feel free to ask if you have any other problems.
First create a div tag below your form and give it an id of something like "messageBox"
so:
<div id="messageBox"></div>
then replace
document.write("Correct!");
with
document.getElementById('messageBox').innerHTML = "Correct!";
and the same for incorrect.
All this does is create a div tag so that the javascript has somewhere to output the success/failure message.
You were oh so very close. You get the DOM element (getElementById), but you need to get the actual value of the element. Use x.value == "Kyle"
Related
After trying multiple ways of what I want to do, which all failed, I'm asking here. This is probably pretty basic, but I just can't do it.
What I essentially want to do:
Create a variable
"Assign" a text box (value) to it
Automatically have the variable's content change to whatever is put into the text box
Potentially have the variable's value used somewhere else immediately
If the user had to press a button to update the element using the variable's value, that'd be OK, too, I just want to have this done.
Alright, I have to correct myself. Another try worked, with the result of 'undefined'.
<head>
<meta id="test3" charset="utf-8">
<link rel="stylesheet" href=".\css\Starter.css">
<title id="test1">TITEL</title>
<script>
function txtSet(txtInp) {
var txt = txtInp.value
document.getElementById('txtP').innerHTML = txt
}
</script>
</head>
<body>
<input type="text" id="txtInp" onkeyup="txtSet(txtInp.value)"></input>
<p id="txtP"></p>
</body>
Try this one:
<body>
<script>
var a = "";
function changeVariable(){
document.getElementById('demo2').value=document.getElementById('demo').value;
}
</script>
<input type="text" id="demo" onkeyup="changeVariable()"></input>
<input type="text" id="demo2"></input>
</body>
I think that you're searching for onkeyup if it's so: you can use as it follows:
In your html
<input type="text" name="name" id="id" onkeyup="yourFunction(this.value);">
and in your js file
var theVariable;
function yourFunction(theTextInTheTextBox){
theVariable = theTextInTheTextBox;
}
It could also be onkeypress or onkeydown events, just try the three to see which is the one that you're actually searching for. To see the difference between the three I advise you to take a look at this link
I'd like to display the page title in a form input field using plain javascript.
I've tried this but it doesn't work. What am I doing wrong?
<input type="text" value="javascript:document.title;"/>
Also, how can I check if the input field is actually there and do nothing if so. I'd like to do this check to avoid JS errors.
No, it would not. value is never executed. Try this instead:
<title>title text here</title>
<!-- ... -->
<input type="text" id="titleinput">
<script>
var theInput = document.getElementById('titleinput')
if (theInput) {
theInput.value = document.title;
}
</script>
EDIT: Shown how to test for existence of the input, and removed the arcane way of finding title since there is a better way. Although, in this case, you might know that you've created the input field, and take it as granted that it is there (your program should make an error if it's not, just like it should make an error if you delete a line from the code itself. I would only have such a check on HTML that I do not control. It might be a personal choice though, I know I don't do enough defensive programming.
EDIT2: jasonscript has a point, but I thought it would confuse the OP even more. If you want a best-practices answer though, you'd do some variety of this, to avoid global variables:
(function(theInput) {
if (theInput) {
theInput.value = document.title;
}
})(document.getElementById('titleinput'));
value attribute is a string, it wouldn't execute if you place some JS in it.
You would set its value with JS after the input is ready in DOM:
<input type="text" value="">
<script>
document.querySelector('input').value = document.title;
</script>
Whereas querySelector will give you the first input element in the DOM.
Specificly, you can pass any css selectors to the method, e.g. ID selector in following code. Please note different parameter querySelector is using:
<input type="text" value="" id="titleInput">
<script>
document.querySelector('#titleInput').value = document.title;
</script>
More on querySelector, visit selectors api spec.
This would work:
HTML:
<title>awesome site</title>
<input type="text" id="textinput" value=""/>
JAVASCRIPT:
<script>
var title = document.title;
var textinput = document.getElementById('textinput');
if (textinput) {
textinput.value = title;
}
</script>
or shorter:
<script>
document.getElementById('textinput').value = document.title;
</script>
I am new to programming and I have a small problem
I have a form named "fr" with an input text box named "in" and a variable "n" with the value of "my text"
this is my code what I have:
<html>
<head>
<script LANGUAGE="JavaScript">
var n = "my text";
document.fr.in.value = n;
</script>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
</body>
</html>
but somehow input "in" does not show the text "my text"
I have been browsing the internet but I couldn't find any solution which works..
everything what I try does not work.
I think I am doing something very simple wrong.
please help me.
document.fr does not exist yet at time of invocation; hence, everything following it doesn't exist either, so it throws a TypeError
TypeError: Cannot read property 'in' of undefined
To fix this, move your code to be invoked after the nodes exist, using your favourite method
window.addEventListener('load', function () {
var n = "my text";
document.fr.in.value = n;
});
I'll further note that;
The preferred way to look up an Element is to give it an id attribute and use document.getElementById. An id must be unique.
Using the language attribute of <script> is depreciated, if you want to specify the language, use the type attribute type="text/javascript" or type="application/javascript"
Opening the Console when a script is not working as expected will often show you the cause immediately. This is usually done with F12.
You should init the script after the form is defined, as explained by Paul S. in his answer. So you may do,
<html>
<head>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
<script type="text/javascript">
var n = "my text";
document.forms.fr.in.value = n;
</script>
</body>
</html>
This would run the script after the form is defined. Or put this code in some function, and instantiate the function after the form is defined(i.e. loaded).
As Paul pointed out you should only try to get a hold of page elements when you are certain that the element you are interested has already been loaded. So in this case you can set the value of the input field by running your code when the page has fully loaded and by getting a reference to the input like this:
window.addEventListener("load", function () {
var n = "my text";
var myInput = document.getElementsByName("in");
myInput[0].value = n;
});
Note, because getElementsByName() returns an array, you will have to use [0], to get the first element.
Okay, first thing, I had a lot of trouble thinking of a title for this, and also of what to search for in Google. So that may just be me being stupid, but here is what I would like you help with.
I have a form, that has a button that will add additional input fields, but I would like the the name of the field to iterate everytime the button is pressed. E.g. the first time it will be:
<input type="textfield" name="field1" value=""/>
Then the second time it is pressed, it will be:
<input type="textfield" name="field2" value=""/>
I also have a small example of what I currently have here: http://jsfiddle.net/5gh75/14/
Please let me know if you can help me, or if you require more info thanks :)
The best way to handle this is to name them all field[].
When handled by the server-side code, it will build an array for you. For instance, in PHP you would get $_POST['field'][0], $_POST['field'][1] and so on.
For your example:
JQuery
var i=0;
$('span.add').click(function () {
$('<input>').attr({
type: 'textfield',
name: 'program'+i
}).appendTo('#addsoftware');
i++;
});
JSFiddle.
But #Kolink-s answer is much better.
Edit: I just saw the previous posts after sending this. Using an array would definitely be better, and JQuery is always nice :).
Just use some javascript:
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
idx = 0;
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "textfield");
element.setAttribute("name", "field" . idx);
element.setAttribute("value", "");
idx++;
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
I took this example from: Add more text fields dynamically in new line (html)
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.