Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript will not pass information into function from html

Ok so very new to Javascript. Trying to learn the code by simply changing the text on a button using an external javascript file. But I can't even get javascript to read the buttons valueexternally, in Chrome's debug tools I see my button value is btn="". It reads the button object but can't read its properties.

<html>
<head>

    <title> Test  </title>
    <script type="text/javascript" src="Gle.js"></script>
</head>

<body>
    <div><canvas id="Gle" width="800" height="600"></canvas>
</div>
    <div>
        <h2>Enter the mass and coordinates</h2> 
        <input id="txtbox" type="text" /><br/>
        <button id="btn" onclick="change()">Add</button>

    </div>


    </body>
</html>

The Gle.js

"use strict";


function change() {
    var x = document.getElementById("btn").value;
    var elem = document.getElementById("btn");
    var txt = document.getElementById("txtbox");
    txt.text = elem.value;
    elem.value = "Ok";
    } 

When I debug the x value it is "", nothing changes on my screen. I am using brackets IDE.

like image 926
CromeX Avatar asked Aug 28 '16 23:08

CromeX


2 Answers

x is empty because '#btn' doesn't have the 'value' attribute specified. The "Add" string is inside its inner HTML (or text),

alert(document.getElementById("btn").innerText);

And you can index this in the event scope, it's a reference of '#btn', this.innerText.

A alternative is to get the '#btn' child nodes values, which is cross-browser.

alert(this.childNodes[0].nodeValue);

This alert the first text specified in the element inner.

like image 72
Klaider Avatar answered Nov 10 '22 00:11

Klaider


I'm expecting to have the button title "Add" appear?

The button doesn't have a value attribute so its value property is an empty string.

"Add" is the content of the text node inside the button element.

var x = document.getElementById("btn").firstChild.data;
like image 44
Quentin Avatar answered Nov 10 '22 01:11

Quentin