I want to use a value from a HTMl input but i cant make it into a variabel. Im a beginner at this so maybe it will be pretty obvious to you but i couldnt find anything on the internet that helped me with my problem.
script.js:
function getInputValue(){
var inputVal = document.getElementById("numberIn").value;
return inputVal;
}
document.getElementById('numberOut').innerHTML = getInputValue();
index.html:
<input type="text" placeholder="Dezimalzahl hier eingeben" id="numberIn">
<button type="button" onclick="getInputValue();">Convertieren</button>
<p id="numberOut"></p>
<script src="script.js"></script>
The reason it doesn't work for you is because the line document.getElementById('numberOut').innerHTML = getInputValue(); gets ran only once, when the input is empty. Your button's onclick only returns the value from the input, but it doesn't re-set it into numberOut.
Please look at my example, I took the same exact line and put it into a function that a button executes, and it seems to work perfectly!
function getInputValue() {
const inputValue = document.getElementById("myInput").value;
return inputValue;
}
function showValue() {
document.getElementById("result").innerHTML = getInputValue()
}
<input type="text" id="myInput"/>
<div id="result"></div>
<button onclick="showValue()">Click Me!</button>
Your idea is
When I click on the button, that's what should happen:
Read the value for an input element from the DOM.
Assign that value to another element.
but, in your implementation you did
When I click on the button:
Read the value.
Return it.
Believe me, that's what your implementation is saying.
If we came to the last step
document.getElementById('numberOut').innerHTML = getInputValue();
He's calling you, "Hey, why you are putting me outside the function, we did not agree like that".
So, that is the first correction
Let deal with the assignment function and place it inside the function.
The second, and after placed the assignment function in his reserved place ... the function now has the full steps
Read the value.
... ... ...
Assign it to the other element directly :), there is nothing that my function should return.
And, now!
Should I write the final getInputValue() function, or I let it to you?
Greetings ;)
Related
I've got a huge feeling I'm simply being idiotic here, but is it me or is Js not firing in JsFiddle?
I built this snippet here but can't seem to get it to fire. Im probably missing something super obvious, but would be grateful for any assistance.
HTML
<div id="col">
<h3 class="txt spacer">Dynamic input, based on select value...</h3>
<input type="text" name="field-one" class="txt stretch" />
<div class="boxes">
<input type="checkbox" id="box-2" onChange="myFunction()" checked>
<label for="box-2">Apply a name?</label>
</div>
</div>
</div>
Javascript
function myFunction() {
// Text field element.
var a = document.getElementByName('field-one');
// Checkbox element.
var b = document.getElementById('box-2');
if (b.checked) {
a.disabled = false;
a.placeholder = 'Not Applicable';
alert('Checkbox State Changed.');
} else {
a.disabled = true;
a.placeholder = 'Enter Your Full Name';
alert('Checkbox State Changed.');
}
}
JS FIDDLE
Thanks in advance for the assistance.
Regards,
-B.
EDIT
I'm an idiot. Thanks guys.
Couple of things here, it should be document.getElementsByTagName (plural) and you need to change the settings, that will embed the JS code in before the body closes.
var a = document.getElementsByName('field-one')[0];
I am using [0] here to access the very first element of the array as document.getElementsByName() will return you an array of elements if encountered multiple matching elements. If you want to select a specific one, make sure you select the DOM element in a more specific way.
And change the Load Type to
No wrap - in <body> (<head> will work as well)
Demo
The Javascript Load Type for your jsFiddle is set to onLoad. This will nest your myFunction function, and therefore won't be available in the global scope.
You can either change the Load Type, or set the variable on the window:
window.myFunction = function()....
NB: You then receive another error for getElementByName. This isn't a function of document. You're probably looking for getElementsByName.
Open the DevTools and you'll see
Uncaught ReferenceError: myFunction is not defined
at HTMLInputElement.onchange ((index):192)
Now why isn't the function defined? Perhaps it's not defined at the right spot?
Look at where you load your JavaScript and change it to:
Here's an updated fiddle. Note that I fixed a typo on line 3 getElementsByName.
First, set your seeting of javascript LOAD TYPE to head.
last, is getElementsByName not getElementByName and it would return array so you need to parse.
let a = document.getElementsByName('field-one')[0];
hope it's helpful.
I am new to JavaScript and I'm still figuring things out.
I already searched the web for this but I'm not quite sure what keywords should I use. I am creating some program with a random number using html and JS.
So in my javascript (inside the tag)
I have something like:
var x;
function initRandom() { // I run this function at loading time (i.e: <body onload="initRandom();">)
x = Math.random();
}
function checkGuessedNumber() { // this just checks if the number guessed by the user is == to x and displays "correct" in a div if it is correct otherwise "incorrect"
}
So the main problems I am encountering is that
The html elements gets reset after submit. For example, the text fields becomes blank, the things I displayed in a div becomes blank. It just shows for a short period of time then gets reset
After that, the generated number becomes a different number I think the html page loads once more every time I click submit. And I don't like that to happen.
What I am having confusions on is the return statement on the onClick() attribute and how is it different on without return. See examples below:
CODE1:
<form onsubmit="return checkGuessedNumber();">
<input type="text"> // input for the number
<input type="submit"> // click if already sure of input number above
</form>
CODE2:
<form onsubmit="checkGuessedNumber();"> // notice no return here
<input type="text">
<input type="submit">
</form>
And finally if I'll just gonna put the checkGuessedNumber on <input type="submit" onclick="checkGuessedNumber();"> OR having a return before that.
Here's a live demo (click) of everything in this post.
First, don't use inline js (js functions in your html, like onclick). Read some of these results: Why is inline js bad?
Just for completeness, I'll explain how it works anyway:
This disables the submit nature of the button.
<input type="submit" onclick="return false;">
Now, if you want to use a function, you still need to produce the above result, so:
<input type="submit" onclick="return foo()">
and foo will have to return false, so that return foo() is the same as return false:
function foo() {
//do what you need to do;
return false;
}
I'll update this in a moment explaining the best practice, NOT using inline js.
The best element for a "button" is <button>, so I recommend that.
<button id="my-btn">Click Me!</button>
I gave it an id so that we can easily identify it in javascript. There are plenty of other ways to get element references, but that's another topic. Now, in javascript:
//get the element reference
var myBtn = document.getElementById('my-btn');
//this will make the button call function "foo" when it is clicked.
myBtn.addEventListener('click', foo);
function foo(event) {
//do whatever you want
}
If you assign an event listener to an element that has a default behavior, you can prevent the default behavior like this:
//the "event" object is automatically passed to the event handler
function foo(event) {
event.preventDefault();
//do what you want here
}
I know it is possible to change different parts of an element such as class, value and html content.
What I am looking for is a way to change the values of the function call itself.
document.getElementById(id).onclick = "javascript:FUNCTION('"+id+"','0');";
The second pass value is what I will be changing. So value "0" can be for example "1" or "2"
Is this possible?
EDIT:
In case this gets going down the wrong road.....
This is what I will be changing with that code.
So then the page ( and script ) is ready to run again with new values
<div id="id" class="stuff" onclick="javascript:function('id','0');" style="cursor:pointer;">
hope that clarifies things a bit more.
RE-EDIT:
Well seems this might not be possible. So will start looking at ways round.
It depends on what you are trying to do, but here is a way of doing it which would not even require the changing of the function.
var myValue = 0
document.getElementById("test").onclick = function (aEvent) {
myValue++;
alert(myValue);
}
See fiddle: http://jsfiddle.net/AqZHZ/
I have a struts tag like this
<s:select label="Select Item" name="select3ph3meter1" id="select3ph3meter1"
headerKey="0" headerValue="-- Please Select --" list="meterHeaderList"
required="true" onchange="show_3ph3meter1(this.value)" />
The problem is it is not calling the above function on change event. It works when I change the code to this:
... onchange="alert('calling')"
I can't understand what's happening here.
Here is the JavaScript function:
function show_3ph3meter1(select3ph3meter1) {
$("#3ph3meter1").load("meterFiller3p31.action",{select3ph3meter1:select3ph3meter1});
}
function show_depotReceipts(selectrecitem) {
$("#recQuantity").load("depotRecQ.action",{selectrecitem:selectrecitem});
$("#recRange").load("depotRecRange.action",{selectrecitem:selectrecitem});
}
The adjacent function is working perfectly so I assume there is no JavaScript error.
Also, when I put in another function (for instance the adjacent function name in onchange), it is also working. The problem may be with this particular function name show_3ph3meter1().
Hi if you have some other java script written over there contains errors , this code wont work.
So better have like this
<select class="style" onchange="//do something like this
//var e = document.getElementById('selectelement'); //if (e) e.value=100;" />
please check in IE browsers to get the java script errors. write entire code in that change event
First check your calling function name
if this is correct then just write
onchange="javascript : show_3ph3meter1(this)"
and get value on the function
3 else try the access value in function with selector
var elem = document.getElementById("short_code"),
selectedNode = elem.options[elem.selectedIndex];
var valu = selectedNode.value;
I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}