How to call function when input value changes? - javascript

I have tried to find a way to call a function when the value of the input changes, but so far I haven't found anything. All of the things I have tried seemed to work but didn't.
Html:
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rng Crypto</title>
</head>
<body>
<header>
<h1>Crypto ran from randomness!</h1>
</header>
<div>
<input type="radio" name="AP" id="a" onchange="AP()" checked>Absolute<input type="radio" name="AP" id="p" onchange="AP()">Percent<br>
<input type="number" id="input" HERE TO ADD THINGY>
<p id="AP" style="display:inline;"></p><br>
<button id="submit">Submit</button>
</div>
<script src="RngCrypto.js"></script>
</body>
</html>
The things that I have tried are:
<input type="number" id="input" onchange="input()">
<input type="number" id="input" oninput="input()">
<input type="number" id="input" onkeyup="input()">
document.getElementById("input").onchange=input();
document.getElementById("input").oninput=input();

const inputEle = document.querySelector("#input");
inputEle.addEventListener('input', function(e) {
console.log(e.target.value);
})
<input type="text" id="input">
Have you tried adding the 'change' event on the input element.
Edit: adding 'input' eventListener, is one more way to achieve this result.
(refer following code)
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
document.queryselector("#input").addEventlistener('change', function(e) {
console.log(e.target.value;)
})

When I got you right this is basically what you are looking for:
<input class="js-radio-button" type="radio" name="ab" value="absolute"> Absolute<br>
<input class="js-radio-button" type="radio" name="ab" value="percent"> Percent<br>
<button class="js-check-selection">CHECK</button>
<div>
<span>Result is:</span> <span id="result"></span>
</div>
in your javascript you have:
function checkSelectedRadio() {
// get your radios having the name 'ab'
const radios = document.querySelectorAll('input[type=radio][name=ab]');
// reset result container
document.getElementById('result').innerHTML = '';
// loop through the radios
for (let i = 0; i < radios.length; i += 1) {
// check for each radio if it was selected
if (radios[i].checked) {
// set the value of the selected radio to your result container
document.getElementById('result').innerHTML = `Value: ${radios[i].value}`;
// if you need more logic:
if (radios[i].value === 'absolute') {
// do something here if 'absolute' was checked
} else if (radios[i].value === 'percent') {
// do something here if 'percent' was checked
}
}
}
}
// get your button to check radio status like this or fire the function above by your onchange handler
const checkButton = document.querySelector('.js-check-selection');
checkButton.addEventListener('click', checkSelectedRadio);
EDIT after reading your comment:
To detect change of your input field it works like this:
<input type="number" id="input" value="1">
In your JS:
const field = document.querySelector('#input');
function inputCheck() {
console.log('input changed');
// or do something else
}
field.addEventListener('change', inputCheck);

Related

When I hit the submit button, I'm unable to achieve the, "Enjoy your day" on the entire screen after one or all the checkboxes have been checked

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Checklist</title>
<link rel="stylesheet" type="text/css" href="./style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit"
onchange="document.getElementById('formName').submit()">
</div>
<!--<p id="msg"></p> (I tried using this approach and calling the msg within script but I received an error.)-->
</form>
</div>
</body>
<script>
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
var submit = document.getElementById('submit');
var text = document.getElementById('msg');
//My if/else statement alert works perfectly. However, with the presence of const submit, it doesn't work properly (I think it's interfering with my if/else statement). Removing the const submit section allows one to experience the if/else alert statement. The goal of this checklist is to be able to check one or all four checkboxes and have it return the "Enjoy your day" text. However, I would like for that message to cover the screen and be the only thing visible after hitting the submit button. I'm okay with receiving an alert box when it returns false. However, when it returns true, I would like for the message to cover the screen and for the checklist/checkboxes to disappear. I'm not sure where I'm getting my wires crossed.
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
} else {
return true;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
}
</script>
</html>
enter image description here
enter image description here
You are declaring submit twice in the isChecked function. Omit one of the declaration.
Also, you are adding the event listener to the submit button after the return statement, which JS will ignore and won't append any onclick function.
The updated isChecked function should be
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
// Removed the submit variable
var text = document.getElementById('msg');
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
// Returning true after adding the event listener.
return true;
}
Just display the message since it is being called onsubmit
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
if (!workout && !meeting && !lunch && !school) {
alert('Please check a box');
} else {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
}
return false;
}
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit">
</div>
</form>
</div>

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>

live update value if checkbox is checked or not

I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?
<html>
<head>
<title>sum totals</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
$('input[name="selectedItems1"]').click(function(){
var j = document.getElementById("output");
if (this.checked) {
j.value=j.value+300
}else{
j.value=j.value-300
}
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Place the <script> tag after <form>
Reason:
When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.
Try this :
<html>
<head>
<title>sum totals</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script type="text/javascript">
function calculate(){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var tons = $('#tons').val();
if ( rege.test(tons) ) {
val = parseInt(tons);
var treesSaved = val * 17;
if($('input[name="selectedItems1"]').is(":checked"))
{
treesSaved = treesSaved +300;
}
else
{
treesSaved = treesSaved -300;
}
if(isNaN(treesSaved))
j.value=0
else
j.value=treesSaved;
}
else
alert("Error in input");
}
$(function(){
$('input[name="selectedItems1"]').change(function(){
calculate();
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>

live validation input when min>max in jquery

I want validate input "min" and "max" and give an error. My actual code work when I press submit button. I want validate this in live when the user
complements other fields. When the user go to the next field and max
My actual code:
<!doctype html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>...</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div class="error">
</div>
<form id="a" action="b.php" method="post" enctype="multipart/form-data">
<label>
<input type="number" name="yearMin" value="1900" min="1800" max="2299">
</label>
<label>
<input type="number" name="yearMax" value="2015" min="1800" max="2299">
</label>
<label>
<input type="text">
</label>
<button type="submit" class="button">Start</button>
</form>
<script>
$(document).ready(
function () {
$("form#a").submit(
function () {
var min =$('input[name^="yearMin"]').val();
var max =$('input[name^="yearMax"]').val();
if (min<max)
{
return true;
}
else
{
$('.error').text("min>max");
return false;
}
}
);
}
);
</script>
</body>
</html>
Edit:
<script>
$("input[type=number]").on('keydown keyup',function(e) {
var min = $('input[name^="yearMin"]').val();
var max = $('input[name^="yearMax"]').val();
if (min < max) {
$('.error').text('');
return true;
} else {
$('.error').text("min>max");
return false;
}
});
</script>
Do I think right? text('') doesn't work.
$("input[type=number]").on('keydown keyup',function(e) {
var min = $('input[name^="yearMin"]').val();
var max = $('input[name^="yearMax"]').val();
if (min < max) {
return true;
} else {
$('.error').text("min>max");
return false;
}
});
The keyup event occurs when a keyboard key is released. The keydown event occurs when a keyboard key is pushed. So we will bind this event to the required element.
keyup
keydown

Radiobutton when selected show div and make required

I have a Magento website and there are some delivery options when ordering a product.
There are 2 methods available.
- pick up yourself
- deliver
When you choose radiobutton "deliver" some div with a textarea is visible.
This textarea needs to be required.
But when you select radiobutton "pick up yourself" the textarea is invisible and needs to be NOT required anymore.
I made a fiddle of the items
Can anyone help me with how to do this?
HTML:
<h2>Select delivery method</h2>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method"> pick up
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method"> deliver
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
If you are after a pure js version you can use this method:
function check() {
var items = document.getElementsByName('shipping_method');
var v = null;
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
v = items[i].value;
break;
}
}
var required = (v == "tablerate_bestway");
document.getElementById("deliv-hold").style.display = required ? "block" : "none";
if (required) {
document.getElementById("shipping_arrival_comments").setAttribute("required", true);
} else {
document.getElementById("shipping_arrival_comments").removeAttribute("required");
}
}
http://jsfiddle.net/gv7xh4cg/9/
Basically, iterate over items of the same name and see if they are selected, if they are grab the value from it and use that to show or hide the comments div.
Cheers,
Ian
Here you can see an example of code to do so :
$(document).ready(function() {
var submitMessage = "";
$(":radio").change(function() {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
$("#deliv-hold").hide(250);
}
else {
$("#deliv-hold").show(250);
}
});
$("form").submit(function(e) {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
submitMessage = "Your command is in process. Thank you for purshasing.";
}
else {
if ($("#shipping_arrival_comments").val().length < 1) {
e.preventDefault();
alert("Field 'delivery date and time' missing.");
submitMessage = "";
}
else {
submitMessage = "Deliver is on his way. Thank you for purshasing.";
}
}
if (submitMessage != "") {
alert(submitMessage);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> Test check </title>
<meta charset = "utf-8" />
</head>
<body>
<span>Choose your delivery method :</span>
<form>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method">
<label for="s_method_freeshipping_freeshipping">Pick up yourself</label>
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method">
<label for="s_method_tablerate_bestway">Deliver</label>
<br />
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
<input type = "submit" id="submit_delivery" name = "submit_delivery" />
</form>
</body>
</html>
I used JQuery include (see below the code the script include) to use the DOM selector which is easier to use than plain javascript.
I updated your fiddle (it also makes the textarea required):
http://jsfiddle.net/gv7xh4cg/4/
You should include jQuery for:
$('input.radio').click(function(){
var selectedOption = $(this).val();
var delivlHold = $('#deliv-hold'),
comments = $('#shipping_arrival_comments');
if(selectedOption === 'freeshipping_freeshipping') {
delivlHold.show();
comments.prop('required',true);
} else {
delivlHold.hide();
comments.prop('required',false);
}
});
and than add display: none:
#deliv-hold{padding-top:20px; display: none}
It does what you asked for.

Categories

Resources