Value will blink only once at the html text box - javascript

while loop in javascript
function calc(){
var one = document.getElementById("fv").value;
var two = document.getElementById("sv").value;
var one1 = parseInt(one);
var two1 = parseInt(two);
var total = 0;
if(one1<=two1){
while (one1 <= two1){
total = total+one1;
one1++;
total=total;
}
document.getElementById("tv").value = total;
}}
calc() //call function
</script>
<form>
There are some confusion using while loop in java script. can i use while loop for those type of calculation?
<p>"Calculation of sum between two numbers"</p>
<h5>First Number</h5><input type ="text" value="1" name="firstv" id="fv"><br>
<h5>Second Number</h5><input type="text" value="100" name="sectv" id="sv"><br>
<h5>Value</h5><input type="number" value= "" name="tv" id="tv"><br>
<button onclick="calc()" value="click">Calculate</button><br>
</form>
</body>
</html>

You need to stop the button from actually submitting the form. If you make sure that your Javascript function appears before your html and your button looks like this:
<button onclick="calc(); return false;" value="click">Calculate</button>
Then it should work properly
If you need to call the first calc() before the button is clicked, you need to do it when the document is ready:
document.addEventListener("DOMContentLoaded", function(event) {
calc();
});
Example

Related

how to extract a javascript variable from a function

I want to retrieve the variable x from the function, but this code does not work
who has an idea
thank you
function myFunction(){
var x = document.getElementById("nom").value;
//document.getElementById("demo").innerHTML =x ;
return x;
}
response = myFunction();
document.getElementById("deux").innerHTML =response ;
<form class="form">
<label>Entre ton nom</label>
<input type="text" id="nom" name="Nom" placeholder="Nom" value="" class="form-control">
<input type="button" name="Envoyer" class="btn btn-default" value="Envoyer" onclick="myFunction();">
</form>
<script src="test-envois.js"></script>
<p id="deux"></p>
<p id="demo"></p>
From what can I see in the code is that you want to add the response to the deux id when you click on the button
The problem in that is that response executes the moment you load the page.
You need to add that logic inside the function like this:
function myFunction() {
var x = document.getElementById("nom").value;
//document.getElementById("demo").innerHTML =x ;
// let response = myFunction();
document.getElementById("deux").innerHTML = x;
}
And now it executes when you click the button
If I understand right, you want whatever the user inputs in the form "nom" to be displayed in the paragraph tag "deux"?
if that’s the case you could just do:
function myFunction() {
var x = document.getElementById("nom").value;
document.getElementById("deux").innerHTML = x;
}
you can enclose all the code into one function, no need to separate it
function myFunction(){
var x = document.getElementById("nom").value;
affichepanier(x);
}
function affichepanier(val)
{
var variableOfFunction1 = val;
document.getElementById("deux").innerHTML =variableOfFunction1 ;
}

Unable to get user input from input field and assign it to another div's innerHTML

I know that this question sounds silly but i am curious why i can avoid this problem in JavaScript. Now in the code below i have given :
var btn=document.getElementById("btn");
btn.onclick = function get() {
var x = document.getElementById("text").value; // --> HERE
document.getElementById("para").innerHTML = x;
};
get();
<input type="text" id="text" value="">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
Now when i assign the variable x inside the function ,after the ("text") i get the .nodeValue instead of getting the .value. Is that a problem with my code editor or i have an error, because every time i put a name inside the input field it shows the result inside the paragraph it appears and fast also disappears
So I see 2 problems here:
You didn`t close your script tag.
You are calling get(); but the function does not exist in that scope but is only assigned in the onclick event.
This should do the trick:
var btn=document.getElementById("btn");
btn.onclick = function get() {
var x = document.getElementById("text").value;
document.getElementById("para").innerHTML = x;
};
<input type="text" id="text" value="HELLO">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
I have preset the value to "HELLO", but you can change it as you want, and it will deliver the value requested when clicking on the button.
I think your only problem may have been how you were declaring the event listener, I declared it as an event listener on the button listening to the 'click' event.
I also edited 'x' to be 'userInput' so it is more clear what it is trying to achieve.
var btn = document.getElementById("btn");
btn.addEventListener('click', function () {
var userInput = document.getElementById("text").value;
document.getElementById("para").innerHTML = userInput;
});
var btn=document.getElementById("btn");
btn.onclick = function () {
var x = document.getElementById("text").value; // --> HERE
document.getElementById("para").innerHTML = x;
};
btn.onclick()
<input type="text" id="text" value="hello">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
This is a working example of what you are trying to do. You can't declare a function in that context as it's anonymous. My example works perfectly, but you should do something more like
function get() {
//Do something
}
btn.onclick = get;
get();
I am not sure whether this will solve or not. However, I suggest you by giving an onclick event inside the input tag.
<input type="submit" value="submit" id="btn" onclick="get()">
<script>
function get() {
var x = document.getElementById("text").value;
document.getElementById("para").innerHTML = x;
}
</script>`

How to get a <input> id number into a var (Math)

I got a input number into a var. I subtracted it to a number.
Thank you vicodin for helping me! I fixed it and it works! (I changed names for my program)
<!DOCTYPE html>
<html>
<body>
<p></p>
<span><input type="number" id="guess1"><p id="g1s"></p></span>
<input type="button" onclick="Calculate()" value="Calculate">
<script>
function Calculate() {
var GuessCon1 = document.getElementById("guess1").value;
var GuessCon1sub = GuessCon1 - 500;
document.getElementById("g1s").innerHTML = GuessCon1sub;
}
</script>
</body>
</html>
You assigned a string "numb1" to variable g. If you want to get the value of the input, you need to find that element (e.g. with document.geElementById method) and take a value from it.
Also, you want to trigger calculation, for example by a button click. I added a code in a snippet, you can run it and play around with it to get the idea.
var button = document.getElementById("substract")
button.onclick = function() {
var g = document.getElementById("numb1").value
var a = 578;
var x = g - a;
document.getElementById("demo").innerHTML = x;
}
<input type="number" id="numb1">
<input type="submit" id="substract">
<p id="demo"></p>
Related links:
Input Text value Property
onclick event

JS - Attach the same function to many html forms

I am trying to make an e-commerce-like webpage (for practice) wherein a click on any of the buttons would update the cart value by the number (quantity) specified on the input element.
So far, I was only able to update the cart from the first form because when I try to assign the function on every form using a loop, the cart updates for a millisecond then returns to zero. I assume its because of the scope.
I know there's an easier way to do this without manually assigning the function for every document.forms[n]
JS
window.onload = function()
{
var getForm = document.forms[0];
var numItems = 0;
getForm.onsubmit = function(event)
{
event.preventDefault();
var getInput = getForm.elements["num-item"].value;
if(parseInt(getInput))
{
numItems = numItems + parseInt(getInput);
var getCart = document.getElementById("item-count");
getCart.innerHTML = numItems;
getForm.reset();
}
else
{
alert("Please enter a valid number");
}
}
HTML
Cart:
<div class="basket">
<p><i class="fa fa-shopping-basket"></i></p>
<p id="item-count">0</p>
</div>
HTML Form: For brevity, I'm only posting 1 form example, but in reality, I have 6 other forms that are exactly the same.
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="text" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
Loop through all of the forms by querying the selector (using whatever method you prefer, depending on performance requirements and markup flexibility -- I've used getElementsByClassName) and executing a for loop.
Inside the loop, bind a function to the "submit" event using addEventListener. You can define the function in-line (as I've done), or define the function elsewhere, assign it to a variable, and reference the variable when binding to the event.
Within the event listener function, you will refer to the form that was submitted as this.
On top of the changes described above, I've made some minor changes to your code:
Your previous version was overwriting the contents of the cart each time. This may have been on purpose, depending on whether you have one "basket" for each item or one overall (this wasn't clear in the question). So, rather than initialize numItems to zero, I've initialized it to the current number of items in the cart.
Consider using input type="number" HTML form elements. They're supported by nearly every browser and only accept digits -- they also have up/down arrows and can be set with the scroll wheel. On browsers that don't support them, they fall back to a basic text input.
var forms = document.getElementsByClassName("buy-form");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", function(event) {
event.preventDefault();
var numItems = parseInt(document.getElementById("item-count").innerHTML);
var getInput = this.getElementsByClassName("num-item")[0].value;
if (parseInt(getInput)) {
numItems = numItems + parseInt(getInput);
var getCart = document.getElementById("item-count");
getCart.innerHTML = numItems;
this.reset();
} else {
alert("Please enter a valid number");
}
});
}
<div class="basket">
<p><i class="fa fa-shopping-basket"></i></p>
<p id="item-count">0</p>
</div>
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="number" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="number" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="number" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
You can use the jQuery selector.
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(document).ready(function() {
$('.buy-btn').click(function(){
$(this).parent('form').submit();
});
});
</script>
<form class="buy-form">
<label>Quantity:</label>
<input type="text" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
The code above will setup a function for each HTML elements that has the css class buy-btn.
You can select anything using parent, children, prev, next or find function from jQuery.
Of course this is just a basic exemple I'm showing here, and again some simple example could be :
$('.buy-btn').click(function(){
$(this).parent('form').submit();
//var itemCount = $('#item-count').html();
//itemCount++;
//$('#item-count').html(itemCount);
var numItem = $(this).prev('.num-item').val();
$('#item-count').html(numItem);
});
Unfortunately, you're going to have to loop through the elements in your JavaScript and assign the function to each, however you can do it a bit simpler with some querySelector methods thrown in:
window.onload = function() {
var getCart = document.getElementById('item-count');
var forms = document.querySelectorAll('.buy-form');
var numItems = 0;
var isNum = function(n) {
return(!isNaN(parseFloat(n)) && isFinite(n));
};
var handler = function(e) {
(e || event).preventDefault();
var getInput = this.querySelector('.num-item').value;
if(isNum(getInput)) {
numItems += parseInt(getInput);
getCart.innerHTML = numItems;
this.reset();
} else {
alert("Please enter a valid number");
}
};
for(var i = 0, len = forms.length; i < len; i++) {
forms[i].addEventListener('submit', handler);
}
};

when javascript function alter html input text ,I want the input text trigger a event like calling other JS function

I try to use onchange but it just work when you alter the text by focusing the mouse cursor on it , but when alter the text by using function its not do anything
<input type="button" value="TestButton" onclick="AlterText()" />
<br />
<input id="txtbox1" type="text" onchange="AlertMe()" />
<script>
var counter = 0;
function AlterText(){
counter=counter +1;
document.getElementById('txtbox1').value = counter;
}
function AlertMe(){
alert("Done!..");
}
</script>
You can call it yourself.
var counter = 0;
function AlterText(){
counter=counter +1;
document.getElementById('txtbox1').value = counter;
AlertMe.call(document.getElementById('txtbox1'));
}
function AlertMe(){
alert("Done!..");
}
Input onchange doesn't fire for programattic changes, you need to fire it yourself with
document.getElementById('txtbox1').onchange();

Categories

Resources