how to call a function with a submit element [duplicate] - javascript

This question already has answers here:
Why can't I get the input from the input box?
(6 answers)
Closed 1 year ago.
I'm trying to call a function using an event listener but for some reason, it won't work. I'm not getting any errors in my javascript or HTML, so what's the deal?
// Data
const clicks = document.getElementById('loc');
const input = document.getElementById('input').value;
const check = document.getElementById('check');
var totalClicks = 0;
var wToType = "var loc = 0";
// functions
function checkCode() {
if (input === wToType) {
totalClicks += 1
clicks.textContent = "Lines of code:" + totalClicks;
}
};
// Event listeners
check.addEventListener("click", checkCode, false);
<h1 id="loc">Lines of code: 0</h1><br><br>
<h3 id="wtt">Lets get started with our loc (lines of code) variable. Type "var loc = 0"</h3>
<input type="text" name="myInput" id="input" size="25" required>
<input type="submit" id="check" value="Write line(s) of code">

Write
const input = document.getElementById('input')
in the line 2, and
input.value == wToType
in line 11.

It's better to take the value from your input right during calling the function.
Here is the right JS code:
// Data
let clicks = document.getElementById('loc');
const check = document.getElementById('check');
let totalClicks = 0;
let wToType = "var loc = 0";
// functions
function checkCode() {
const input = document.getElementById('input').value;
if(input === wToType) {
totalClicks += 1
clicks.textContent = "Lines of code: " + totalClicks;
}
};
// Event listeners
check.addEventListener("click", checkCode, false);

Related

How to populate multiple HTML DOM elements with local storage values

I want to display contents in the last <div> element when a click event occurs but now it only shows 1st 2 elements. Is there something I am not doing right somewhere?
Here is my code so far:
JS
const iname = document.getElementById("name");
const iemail = document.getElementById("email");
const iphone = document.getElementById("phone");
const submit = document.getElementById("submit");
const storage = document.getElementById("storage");
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
localStorage.setItem(name, "");
localStorage.setItem(email, "");
localStorage.setItem(phoneno, "");
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `Name : ${key}<br />Email : ${value}`;
}
localStorage.clear()
HTML
<p>Name</p>
<input id="name" autocomplete="off">
<p>Email</p>
<input id="email" autocomplete="off">
<p>Phone no</p>
<input id="phone" autocomplete="off">
<button id="submit">Let's go</button>
<div id="storage" class="box">
<h1>Is this correct?</h1></div>
I think you are setting the values in localstorage the wrong way.
The syntax for storing stuff in there is localstorage.setItem(keyName, keyValue).
And your code is setting the keyName argument to the value you are getting from the form and keyValue argument to an empty string; not what you need.
Make the following changes and you should be good to go (see comments):
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
// set local storage values
localStorage.setItem("name", name); // modified
localStorage.setItem("email", email); // modified
localStorage.setItem("phoneno", phoneno); // modified
location.reload();
}
console.log(localStorage); // new (maybe unnecessary)
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `${upFirst(key)}: ${value}<br>`; // modified
}
localStorage.clear();
/**
* new: making the first letter an upper case (for labels in the output div).
* See usage in 'for loop' above.
*/
function upFirst(stringValue) {
return stringValue.slice(0, 1).toUpperCase() + stringValue.slice(1);
}

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

What's the next step in creating a temp converter?

This is my very first time trying to create a simple program by using JS and I am a beginner, so please bear with me. I am here because I feel like I have all these pieces of code but I can't understand how to link them together. I have two functions inside the form that work on their own but I clearly need to link them to the result statement inside the if statement and I am not sure how to do that. Also, I am sure this is poorly written code but for now I am just focussing on having a working program. This is the JS code I have so far (HTML after that):
// grab elements & store in variable
const form = document.querySelector("form");
const submit = document.getElementById("submit");
const selectCelsius = document.getElementById("celsius")
const selectFahrenheit = document.getElementById("fahrenheit")
const result = document.getElementById("result");
const userInput = document.getElementById("userInput").value
form.addEventListener("submit", (e) => {
e.preventDefault();
const fahrenheit = (c) => {
let f = (c * 9/5) + 32
return f
}
const celsius = (f) => {
let c = ((f - 32) * 5) - 9
return c
}
if (selectCelsius === "Celsius" && submit.innerHTML === "CONVERT") {
return result.innerHTML = "Your result is " + userInput(fahrenheit)
}
if (selectFahrenheit === "Fahrenheit" && submit.innerHTML === "CONVERT") {
return result.innerHTML = "Your result is " + userInput(celsius)
}
})
HTML:
<body>
<div class="main-wrapper">
<div class="sub-wrapper">
<div class="weather">
<img src="./img/weather.png" alt="weather">
<h1>temperature converter</h1>
</div>
<form action="#">
<input type="number" id="userInput" name="temperature" placeholder="temperature">
<select name="temperature" id="temperature">
<option value="celsius" id="celsius">Celsius</option>
<option value="fahrenheit" id="fahrenheit">Fahrenheit</option>
</select>
<input type="submit" id="submit" value="CONVERT"></input>
</form>
<p id="result"></p>
</div>
</div>
<script src="./app.js"></script>
</body>
There are a couple of issues with your code.
First of all, you are accessing the values of user-input at the time of the application-load, hence when the user makes any changes in the input box and submits, the value entered by the user doesn't reach javascript.
The logical check applied inside the submit event's callback function are not correct. You need to access the value of the select element which has id temperature.
The function invocation for calculating the conversion was also wrong in your case. Function invocation follows <function-name>(<argument>) pattern. Hence it should be fahrenheit(userInput) instead of userInput(fahrenheit). and similarly celsius(userInput)
Following changes in the js code should give you the expected outcome.
// grab elements & store in variable
const form = document.querySelector("form");
const submit = document.getElementById("submit");
const result = document.getElementById("result");
form.addEventListener("submit", (e) => {
e.preventDefault();
const userInput = document.getElementById("userInput").value;
const selectTemperature = document.getElementById("temperature").value;
const fahrenheit = c => {
let f = (c * 9) / 5 + 32;
return f;
};
const celsius = f => {
let c = (f - 32) * 5 - 9;
return c;
};
if (selectTemperature === "celsius") {
result.innerHTML = "Your result is " + fahrenheit(userInput);
}
if (selectTemperature === "fahrenheit") {
result.innerHTML = "Your result is " + celsius(userInput);
}
})
Here is a link to my solution: https://stackblitz.com/edit/js-kruqd1

I stuck with this code, trying to figure out, how it should work

I'm working on a poject, need it must be auto calculation.
let say that we have uncounted hidden inputs with known same class and attr. diffrent value, attr diffrent price, price2 price 3 in a div to count
What im trying to do is to get attrs (price, priceX2, priceX3)
if the user inserted a number ex. 1 or 40, will return first input(price, priceX2, priceX3), and if its given 61 0r 70 then it will return to the third input(price, priceX2, priceX3) so on
<div id="countDiv">
<input type="number" value="" id="counter" />
<button id="countBtn"> Count </button>
<input type="hidden" value="40" price="1100" priceX2="1200" priceX3="1220" class="classeid">
<input type="hidden" value="60" price="1150" priceX2="1250" priceX3="1300" class="classeid">
<input type="hidden" value="70" price="1220" priceX2="1350" priceX3="1400" class="classeid">
</div>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var parentDOM = document.getElementById("countDiv");
var classCounter = parentDOM.getElementsByClassName("classeid");
var counter = $("#counter").val();
for (var i = 0, n = classCounter.length; i < n; ++i) {
var mPrice = parseInt(classCounter[i].value);
var cPrice = parseInt(classCounter[i].getAttribute('price'));
var cPriceX2 = parseInt(classCounter[i].getAttribute('priceX2'));
var cPriceX3 = parseInt(classCounter[i].getAttribute('priceX3'));
}
});
});
</script>
Hope this code help you.
Do do it dynamically it's not better to do using the Hidden field if you have more than 3 input hidden field. The logic will be different in that case.
Considering only 3 hidden input fields then code looks as below:
HTML Code:
provide id to the each hidden input fields as first, second and third as written in the code.
JavaScript Code:
$("#countBtn").click(function(){
var counter = $("#counter").val();
if(counter > 0 && counter <= 40) {
var mprice = $("#first").val();
var cprice = $("#first").attr("price");
var cPriceX2 = $("#first").val("priceX2");
var cPriceX3 = $("#first").attr("priceX3");
}
else if(counter > 39 && counter <= 60) {
var mprice = $("#second").val();
var cprice = $("#second").attr("price");
var cPriceX2 = $("#second").val("priceX2");
var cPriceX3 = $("#second").attr("priceX3");
}
else {
var mprice = $("#third").val();
var cprice = $("#third").attr("price");
var cPriceX2 = $("#third").val("priceX2");
var cPriceX3 = $("#third").attr("priceX3");
}
}

only write predefined text in textbox using javascript

I want to do in textbox only add predefined text.
<input type="text" class="mytxt" onkeyup="return SplitChar(this.id);">
<script>
function SplitChar(txt) {
var mainval = document.getElementById(txt).value;
var Data = "hello".split('');
var Datas = mainval.split('');
var charLen = mainval;
if (Datas[mainval.length - 1] == Data[charLen.length - 1]) {
return true;
} else {
document.getElementById(txt).value = mainval.substr(0, mainval.length - 1);
alert("Please write as specified example");
return false;
}
}
</script>
in this text box only written "helloo" nothing else
i want to check on keyup event. and whith out use event function
Can anyone give me a suggestion?
Try this code.
Remove this.id in onkeyup="return SplitChar(this.id);" because you aready accessing in JS as var mainvaland add id to input because you accessing its value based on id
function SplitChar() {
var mainval = document.getElementById('txt').value;
var Data = "hello".split('');
var Datas = mainval.split('');
var charLen = mainval;
if (Datas[mainval.length - 1] == Data[charLen.length - 1]) {
return true;
} else {
document.getElementById('txt').value = mainval.substr(0, mainval.length - 1);
alert("Please write as specified example");
return false;
}
}
<input type="text" class="mytxt" id="txt" onkeyup="return SplitChar();">

Categories

Resources