PDA

View Full Version : Javascript Form Calculation



MostDope
05-29-2014, 06:48 PM
I am using a small script i found online, which counds the words in a file i attach to a form and it all works perfectly.

However i am trying to extend the script to take the value of the word count and make a simple calculation and then display it, however it doesn't work. Sometimes it was showing the value as 'NaN'.

My only javascript related experience comes from java so i aplogise for poor code.




<script type="text/javascript">
function loadDemo() {

WordCount.words("file_attach", function(words) {
document.getElementById("words").value = words;
});

var elt = document.getElementById("words");
var totalwords = elt.textContent;


totalwords = parseInt(totalwords);

var totalprice = totalwords * 12;

document.getElementById("tprice").value = totalwords;



}
</script>


<label for="name"><span>Name</span>
<input type="text" name="name" id="name" placeholder="Enter Your Name" />
</label>

<label for="email"><span>Email Address</span>
<input type="email" name="email" id="email" placeholder="Enter Your Email" />
</label>

<label for="file"><span>Attachment</span>
<input type="file" name="file_attach" id="file_attach" />
</label>

<label for="words"><span>No. of Words</span>
<input readonly type="number" id="words"/>
</label> <br/>

<label for="tprice"><span>Price</span>
<input readonly id="tprice"/>
</label> <br/>

Anyone with any help or pointers would be great!

DaveyErwin
05-29-2014, 07:25 PM
function loadDemo() {
WordCount.words("file_attach", function(words) {
document.getElementById("words").value = words;
}
) ; // should be };

MostDope
05-29-2014, 07:30 PM
I replaced the }); with }; and the work count stopped working?

Philip M
05-29-2014, 08:03 PM
I replaced the }); with }; and the work count stopped working?

Read and apply what Davey Erwin has told you.

totalwords = parseInt(totalwords);
should be
totalwords = parseInt(totalwords,10);

Do you intend that
document.getElementById("tprice").value = totalwords;
should be
document.getElementById("tprice").value = totalprice;

MostDope
05-29-2014, 08:16 PM
Below is the code i have now. tprice still shows 'NaN'.


<script type="text/javascript">
function loadDemo() {

WordCount.words("file_attach", function(words) {
document.getElementById("words").value = words;
});

var elt = document.getElementById("words");
var totalwords = elt.textContent;


totalwords = parseInt(totalwords,10);

var totalprice = totalwords * 12;

document.getElementById("tprice").value = totalprice;



}
</script>

Philip M
05-29-2014, 08:22 PM
One more time -

});

should be }};

Have you loaded your script after the HTML?

MostDope
05-29-2014, 08:28 PM
}}; broke the word count, and yes im using onLoad inside the body?

MostDope
05-29-2014, 08:38 PM
I dont know if it helps, but i have uploaded the page.

Proofreading | Distinctive Writers (http://beta.distinctivewriters.co.uk/proof.php)