简体   繁体   中英

onclick javascript function not passing variable from textbox

I've been digging through Stack Overflow for a few days now trying to figure out why my code isn't working. Alas, here I am, asking a very simple question.

I have an HTML form that has a text box and a submit button. You enter a number into the textbox, click the submit button and it's supposed to update a div with information about the number you entered. I know the function works. If I hard code a number into the submit button, it inserts the html properly. But if I change the submit button's onclick to include the text in the textbox, nothing happens.

Any help would be greatly appreciated.

HTML===============================

<form>
<input type="text" name="thenumber" id="thenumber" /> <input type="button" onClick="numbers(document.getElementById('thenumber').value);" value="Click Me!" />
</form>
<div id="message"></div>

JS=================================

var numbers = function(identify){

switch (identify) {

    case '1234':
        document.getElementById("message").innerHTML = "Device 1";
        break;
    case '5678':
        document.getElementById("message").innerHTML = "Device 2";
        break;
    case '9101':
        document.getElementById("message").innerHTML = "Device 3";
        break;
        default:
        document.getElementById("message").innerHTML = "Device Unknown";
};
};

Thanks again for all your help!

您缺少括号

    "numbers(document.getElementById('thenumber').value)"

If you want include the text in the text box, you don't have to use innerHTML, you have to use value.

Ex:document.getElementById("message").value = "Device Unknown";

Ok, try copy my code.

<input type="text" name="thenumber" id="thenumber" /> 
<input type="button" onClick="numbers(document.getElementById('thenumber').value)" value="Click Me!" />

<div id="message"></div>

var numbers = function(identify){

switch (identify) {

    case '1234':
        document.getElementById("message").innerHTML = "Device 1";
        break;
    case '5678':
        document.getElementById("message").innerHTML = "Device 2";
        break;
    case '9101':
        document.getElementById("message").innerHTML = "Device 3";
        break;
        default:
        document.getElementById("message").innerHTML = "Device Unknown";
};
};

You have a syntax error on onClick event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM