Qcom
Qcom

Reputation: 19213

JavaScript clear text box input not functioning properly

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.

Upvotes: 1

Views: 1638

Answers (4)

Rajat
Rajat

Reputation: 34148

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.

Upvotes: 0

Christian Tellnes
Christian Tellnes

Reputation: 2080

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.

Upvotes: 1

Girish Dusane
Girish Dusane

Reputation: 1130

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.

Upvotes: 2

Claudiu
Claudiu

Reputation: 3261

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.

Upvotes: 1

Related Questions