DOM event clearing text values - javascript

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Related

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

for loop with array of strings rendering the same thing twice?

I am building in javascript a simple feedback that has a text area and is grabbing the text and displaying a successful message when the add button is clicked. When the view feedback button is clicked it should render the feedback and it does but if I click the button once and then type in the text area again and again it keeps rendering multiple times the same feedback message. Attached is my javascript code.
var array = Array();
var x = 0;
function addFeedback() {
array[x] = document.getElementById('feedback').value;
x++;
document.getElementById('feedback').value = '';
document.getElementById('result').innerHTML =
'<h2><h3> Your have successfully Added Feedback!</h3></h2>';
}
var feedback = '';
function displayFeedback() {
for (var i = 1; i < array.length + 1; i++) {
feedback = array[i - 1] + '<br/>';
console.log(feedback);
}
document.getElementById('result').innerHTML =
'<h2>feedback Details: </h2>' + feedback.split('<br>');
}
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<!-- Fill code here -->
<div>
<h2>Feedback for the ART OF LIVING</h2>
<div>
<label for="feedback"></label>Enter the Feedback:
<textarea id="feedback" name="feedback" value="feedback" type="text"></textarea>
<div>
<input type="button" id="create" name="create" onclick="javascript:addFeedback()">Add Feedback</input><br/>
<input type="button" id="view" name="view" onclick="javascript:displayFeedback()">View feedback</input>
</div>
<div id="result"></div>
</div>
</div>
</body>
</html>

How to focus cursor in specific point in textarea using js?

I am trying to create "quicklink" option in textarea using which users can insert html tags by directly clicking over them. It is working fine but after I click any quicklink button the cursor moves to the end of the text present in the textarea.
How to keep/focus cursor just after the inserted tag?
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
// Getting closest number for array
// https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
$('#txtarea').click(function(){
var str = $(this).val();
var regex = /\<([a-zA-Z\/]+\>)/gi, result, indices = [];
// Getting positions as array
// https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
var cursorPosition = $(this).prop("selectionStart");
$(this).prop('selectionEnd');
var closestPosition = closest(cursorPosition,indices)
$(this).prop('selectionEnd', closestPosition);
})
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
You can get current cursor position by using following solution:
https://stackoverflow.com/a/1909997/7676742
And increment it by the length of your new added html tag (for instance 3 for <a>) and set position of cursor by using following solution:
https://stackoverflow.com/a/49750025/7676742
I found an easy way to do this:
function quicklink(link){
var linklen=link.length;
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").prop('selectionEnd', cursorPos+linklen);
$("#textarea").focus();
}

How to create 3 links to define and one to erase

The document added another 3 link given in such a way that three links define three fruit and the fourth to erase selections
How do I do that?
<html>
<head>
<script language="javascript">
<!--
function FruitBox() {
window.document.myform.fruit[].checked = true;
}
function clearall() {
for (var p = 1; p < 3; p++) {
var x = window.document.myform.fruit("value");
for (var i = 0; i < 4; i++)
x[i].checked = false;
}
}
//-->
</script>
</head>
<body>
<from name="myform">
<input type="radio" name="fruit" onclick="window.document.myform.fruit.value='oranges'">oranges & Tangerines <br>
<input type="radio" name="fruit" onclick="window.document.myform.fruit.value='bananas'">bananas <br>
<input type="radio" name="fruit" onclick="window.document.myform.fruit.value='peaches'">peaches,Nectarines & Palmus <br> To select Oranges click here
<input type="reset" Value="Sterge" onClick=" clearall()" />
</from>
</body>
</html>
You misspelled tag form
you need to pass something to the function
you need to access that something
the reset will reset the form. No need to call a function
since you use form access there is no need to address the form from the top of the document but there is ALSO no need to set the value of the fruit on click
if you give each radio an ID, you can have a <label for="oranges">Click here to select oranges</label> instead of a link
<html>
<head>
<script language="javascript">
function FruitBox(idx) {
window.document.myform.fruit[idx].checked = true;
return false; // cancel the link - preventDefault can be used too
}
/* NOT needed
function clearall() {
for (var p = 1; p < 3; p++) {
var x = window.document.myform.fruit("value");
for (var i = 0; i < 4; i++)
x[i].checked = false;
}
}
*/
</script>
</head>
<body>
<form name="myform">
<input type="radio" name="fruit">oranges & Tangerines <br>
<input type="radio" name="fruit">bananas <br>
<input type="radio" name="fruit">peaches,Nectarines & Palmus <br>
To select Oranges click here
<input type="reset" Value="Sterge" />
</from>
</body>
</html>

how to sum radio button values only one time?

I am using this code to sum values from multiple radio buttons :
$(document).ready(function(){
var total = 50000;
$("input[type=radio]").change(function(){
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
});
the problem is that when user click on a radio button in a group and then select another radio button in that group the new value will be add to this, i want to only add one of the values to the total value.
for example in this group :
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
when first time a user select seconed radio the 5000 will be add to total price, but if he change it to third option, 15000+5000 will be add to total, i want to have only one of them !
The problem seems, to me, that the total var is declared out of the scope of the change callback. This will cause the closure of the change callback to contain the total variable, so it's value will be persisted across subsequent change calls.
If declare the total within this callback, you should be fine:
$("input[type=radio]").change(function(){
var total = 5000; // => declared locally, so initialized at each change.
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
I wrote a simple example demonstrating this recently (although I did it without using jQuery).
Just store the value you add, and then subtract it from the total before adding a new one.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Radio Test</title>
</head>
<body>
<form action="" method="get" id="myForm">
<fieldset id="myRadioGroup">
<legend>Radios</legend>
<div>
<label> <input type="radio" value="0" name="add" checked> 0 </label>
</div>
<div>
<label> <input type="radio" value="20" name="add"> 20 </label>
</div>
<div>
<label> <input type="radio" value="30" name="add"> 30 </label>
</div>
</fieldset>
<div id="total">45</div>
</form>
<script type="text/javascript">
(function () {
var group = document.forms.myForm.elements.add;
var currentValue = function currentValue () {
for (var i = 0, j = group.length; i < j; i++) {
if (group[i].checked) {
return Number(group[i].value);
}
}
};
var oldValue = currentValue();
var total = document.getElementById('total').firstChild;
var update = function update () {
var current = currentValue();
total.data = Number(total.data) - oldValue + current;
oldValue = current;
};
for (var i = 0, j = group.length; i < j; i++) {
group[i].onchange = update;
}
}());
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>
W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
</body>
<script type="text/javascript">
$(function()
{
$('input:radio').change(function()
{
var total = 50000;
$('input:radio:checked').each(function()
{
if (isNaN(this.value))
total = total;
else
total += parseFloat(this.value);
});
$('.price_amount').text(total);
});
});
</script>
</html>

Categories

Resources