Can't see updated HTML input value from Javascript [duplicate] - javascript

This question already has answers here:
Difference between Element.value and Element.getAttribute("value")
(2 answers)
Closed 3 years ago.
If I click the "Show Value" button, it copies the text field value 0.75 to a result label.
But if I change the text field value to something else and click "Show Value", I still get 0.75.
Why is it that the input element's value attribute doesn't change based on the value of the input box?
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('theform');
var edit = form.querySelector("input.parameter");
var btn = form.querySelector("input.showit");
var result = document.getElementById("result");
var n = 0;
btn.addEventListener("click", function(event) {
++n;
result.textContent = "Result: "+edit.getAttribute("value")+" (click #"+n+")";
});
});
<div class="container">
<form id="theform">
<label for="R">R</label>
<input type="number" class="parameter" name="R" value="0.75">
<input type="button" class="showit" value="Show Value">
<label id="result">Result: </label>
</form>
</div>
(It's not just Javascript; if I look at the page in Chrome and open an Inspect window, the element's value never changes from 0.75.)

It's actually updating the value property of the DOM element and not the value attribute. To make it works use value property of the DOM element.
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('theform');
var edit = form.querySelector("input.parameter");
var btn = form.querySelector("input.showit");
var result = document.getElementById("result");
var n = 0;
btn.addEventListener("click", function(event) {
++n;
result.textContent = "Result: " + edit.value + " (click #" + n + ")";
});
});
<div class="container">
<form id="theform">
<label for="R">R</label>
<input type="number" class="parameter" name="R" value="0.75">
<input type="button" class="showit" value="Show Value">
<label id="result">Result: </label>
</form>
</div>

You want to use edit.value not edit.getAttribute('value').
edit.getAttribute('value') is getting the attribute value and not the current value since modifying the input doesn't actually update the default attribute's value.
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('theform');
var edit = form.querySelector("input.parameter");
var btn = form.querySelector("input.showit");
var result = document.getElementById("result");
var n = 0;
btn.addEventListener("click", function(event) {
++n;
result.textContent = "Result: "+edit.value+" (click #"+n+")";
});
});
<div class="container">
<form id="theform">
<label for="R">R</label>
<input type="number" class="parameter" name="R" value="0.75">
<input type="button" class="showit" value="Show Value">
<label id="result">Result: </label>
</form>
</div>

Related

How to change the value of a previous check box that has been selected in JQuery?

Here is what I'm trying to do.
I have the ability to create a form when there is an option to create one in Javascript.
Here is an option to add an address:
<i class="fas fa-plus-circle"></i> <span class="newUrlText">add new address
Here is the form in question:
<input type="text" class="form-control" id="new-address-1-%ID%" name="new-address-1-%ID%" placeholder="Address Line 1">
<input type="text" class="form-control" id="new-address-2-%ID%" name="new-address-2-%ID%"
placeholder="Address Line 2">
<label for="message" class="control-label"><span class="billable-text"><?php _e('Primary Address'); ?></span></label>
<label class="switch" for="primary-%ID%" style="margin-left: 10px;top: 10px;">
<input type="checkbox" class="primary-%ID%" name="primary-%ID%" id="primary-%ID%" />
<div class="slider round gray"></div>
</label>
Here is the javascript that generates the form:
<script language="javascript">
var newAddressIndex = 1;
var addressarray = [];
function addNewAddress() {
var container = getElement("addressContainer");
addressarray.push(newAddressIndex);
var htmlAddress = '<?php echo addslashes(App_String::stripBreaksTabsMultipleWhitespace($newAddress)); ?>';
htmlAddress = htmlAddress.replace(/%ID%/g, newAddressIndex);
var node = document.createElement("div");
node.innerHTML = htmlAddress;
container.appendChild(node);
$('#newAddressCount_'+newAssetIndex).val(newAssetIndex);
++newAddressIndex;
test(addressarray);
}
What I'm trying to do is the following:
If the user selects the checkbox and then decides to select the next checkbox, I would like to change the previous checkbox from selected to no selected.
How would I go about doing that?
Thank you
I found a solution:
What I did was, that I created a function to get the current value of the checkboxes like this:
getAddrValue(addressarray);
Then within the function the follwoing:
function getAddrValue (addressarray) {
$('#primary-'+index).change(function() {
var checked = this.checked ? 1 : 0;
prevCheckbox = index-1;
if (checked == 1) {
if (document.getElementById('primary-'+prevCheckbox) !== null ) {
let inputs = document.getElementById('primary-'+prevCheckbox);
inputs.checked = false;
}
}
});
}

Why isn't my code adding a number with the input field (HTML/Javascript - Beginner)?

for practice as a beginner I am trying to take a number from a text field, have the user press a button that adds 2 to that number, and then displays it through HTML. However, for some reason I keep getting NaN when applying the code below.
//Setup
var num1 = document.querySelector(".input-box").value;
var btn = document.querySelector(".btn");
//Add
var sum = parseInt(num1) + 2;
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to move the num1 and sum the inside the event listener
//Setup
var btn = document.querySelector(".btn");
//Add
btn.addEventListener('click', (e) => {
e.preventDefault();
// get the number
var num1 = document.querySelector(".input-box").value;
// add 2
var sum = parseInt(num1) + 2;
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to calculate the sum inside the click function. Right now it is calculating before the butten is clicked, when the page loads, which means the input is empty.
as mentioned above you need to resolve after the button is clicked. you could change your variables to function variables.
//Setup
var num1 = function() {return document.querySelector(".input-box").value};
var btn = document.querySelector(".btn");
//Add
var sum = function() {return parseInt(num1()) + 2};
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum();
})
make the input type = number for better validation
make the button type = submit cause this is form and you need to submit
add submit event to the form cause you can't prevent default without submit event
select input inside the event and convert its value to number by adding + before it
// select from
var form = document.getElementById("form");
form.addEventListener('submit', (e) => {
e.preventDefault();
// select input and convert its value to number
var num1 = +document.querySelector(".input-box").value;
document.querySelector("#output").innerHTML = num1 + 2;
// wipe out form after submit
form.reset();
});
<div class="sign">
<h1>Calculate</h1>
<form id="form">
<input type="number" class="input-box" placeholder="Enter Number">
<input class="btn" type="submit" value="Add 2">
</form>
<h1 id="output"></h1>
</div>

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

how to display the array of values for the single field using jquery?

Here I need to get all the values entered in the input field. But it echoes only the first value.
ie. When I press the + and give some values, I need to get that value too.
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('#package').change(function() {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
alert(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add"></div>
</div>
$('.package').change(function() {
You are using an ID in your input type="text". IDs are only used once. If you want to add the listener to all of your textfields use classes.
In addition to that the .change(function() is only once called, when the dom is ready. That will be a problem too. So the change listener is not added to the generated textfields. Maybe you use something like...
$('.package').on('change', 'input', function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add">
</div>
</div>
<script type="text/javascript">
var addInput = function(e) {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
});
alert(arr);
};
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input class="packageclass" type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
$('.packageclass').unbind().bind('change', addInput);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('.packageclass').unbind().bind('change', addInput);
</script>
Just using loop you can get the particular value from loop.
for (var i = arr.length - 1; i >= 0; i--) {
arr[i];
//work with arr[]
}
I have used event delegation to capture the events and take appropriate action.
In this, you can add a event listener to your parent element i.e., click to the .body in my case. When I click on the .add button, the event propagates and .body click handler gets invoked. By checking for event.target we can find out the origin of event and add or remove the divs.
Similary we can listen for the change event of the input boxes and take appropriate actions.
$('#body').click(function(e) {
if(e.target.className === 'add') {
$('#body').append(`
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
<button class="remove">-</button>
</div>
`);
}
if(e.target.className === 'remove') {
$(e.target).parent().empty();
}
});
$('#body').change(function(e) {
console.log(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="body">
<h6>Sales Package </h6>
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
</div>
</div>
Just add class="packageclass" to the input when creating your clone variable.
https://jsfiddle.net/289xvmu7/
var clone = '<div class="add1"><input type="text" name="selprice" class="packageclass"/> <input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';

Displaying content of form input element in another field using javascript onFocus event

PROBLEM: I want Javascript to calculate the sum of two numeric inputs from a user and display the sum in the third field immediately the user tabs into or clicks on the field.
ERROR: Firefox, Chrome and Safari all display zero when the third field is on focus; however, in fairness to Firefox, it reluctantly displays the required result after refreshing; others don't. I suspect an error in my code which I cannot identify, please help.
window.onload = function() {
var input1 = document.getElementById('bk').value;
var input2 = document.getElementById('softw').value;
input1 = Number(input1); // convert input to number
input2 = Number(input2);
input3 = input1 + input2; // Sum the inputs
document.getElementById('total').onfocus = function() {
document.getElementById('total').value = input3;
return input3;
}
}
<html>
<body>
<div id='fm_div'>
<form action="#" method="GET" id='form1'>
<p>Qty of Books:
<input type="text" name="bkqty" id='bk'>
</p>
<p>Qty of Software:
<input type="text" name="software" id='softw'>
</p>
<p>Total:
<input type='text' id='total'>
</p>
<p>
<input type='submit' value='send' id='submit'>
</p>
</form>
</div>
</body>
</html>
You are setting input1 and input2 on window load function. But the textboxes will not have any value on load. change your window.onload function as below
window.onload = function() {
document.getElementById('total').onfocus = function() {
var input1 = document.getElementById('bk').value;
var input2 = document.getElementById('softw').value;
input1 = Number(input1); // convert input to number
input2 = Number(input2);
input3 = input1 + input2; // Sum the inputs
document.getElementById('total').value = input3;
return input3;
}
}
<div id='fm_div'>
<form action="#" method="GET" id='form1'>
<p>Qty of Books:
<input type="text" name="bkqty" id='bk'>
</p>
<p>Qty of Software:
<input type="text" name="software" id='softw'>
</p>
<p>Total:
<input type='text' id='total'>
</p>
<p>
<input type='submit' value='send' id='submit'>
</p>
</form>
</div>

Categories