How to retrieve the value of an input on keyup? - javascript

What I am trying to achieve is to output the actual value/text so that I can save it into a variable, but the console gives me a number indicator and it keeps adding to it each time I keyup.
<input id="usp-custom-3" type="text">
var country1 = $("#usp-custom-3").html();
$("#usp-custom-3").on("keyup", function() {
console.log(country1);
});

There's two issues with your code. Firstly you need to get the val() of the input, not it's html(). Secondly, you need to retrieve the value every time the event happens, so place it within the event handler, like this:
$("#usp-custom-3").on("keyup", function() {
var country1 = $("#usp-custom-3").val();
console.log(country1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="usp-custom-3" type="text">

Related

How do I get the value of input tag using javascript

Why do I get a empty string "" when I try to get the value of my input field instead of the number I gave.When I type billAmount in the console window,I get "" returned.Why is that?
var billAmount = document.getElementById('bill-id').value;
<html>
<input type="number" id = "bill-id" class="bill-input" placeholder="0">
</html>
Your code only executes once.
If you want to update the variable everytime the user changes the value of the input, listen for the input event:
var billAmount;
document.getElementById("bill-id").addEventListener('input', function(){
billAmount = this.value;
console.log(billAmount);
})
<html>
<input type="number" id = "bill-id" class="bill-input" placeholder="0">
</html>
First, your webpage loads the input element in the DOM. Then, the javascripts starts running. It rapidly collects the input's value which is empty. Presuming the only line of JS is var billAmount = document.getElementById('bill-id').value;, it finishes its jobs. Your JS doesn't detect any change of the input's value. You should add an event listener and change the variable each time you enter something.

Javascript - Display input inside div

So this is probably an easy one, but I'm just not doing it right. My goal is to send the user input from this textbox:
<input type='text' placeholder='Form Name...' id='formNameInput' required>
Into this Div:
<div id="code_output"></div>
I'm trying to make it appear in real time, and so far I used this to try and do so, but it doesn't work:
document.getElementById("code_output").innerHTML += document.getElementById("formNameInput").value;
Why doesn't it show? Does my code need something to trigger the Javascript?
You're close, but the issue is that you're not using an event handler. The script is executing your code once, as soon as possible (before you have the chance to enter anything into the text input). So, you have to add some sort of event listener so that the copying happens at the appropriate time. Something like below:
document.getElementById('formNameInput').addEventListener('keyup', copyToDiv);
function copyToDiv() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
<input type='text' placeholder='Form Name...' id='formNameInput' required>
<div id="code_output"></div>
You need to do that whenever the value of formNameInput changes. For that you need an event.
Your code should look like:
document.getElementById("formNameInput").addEventListener('input', function () {
document.getElementById("code_output").innerHTML += this.value;
});
function change() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
document.getElementById('formNameInput').onkeyup = change
maybe this is what you are trying?
You need to attach an event listener to your input that executes a function any time an input event occurs on the field:
formNameInput.addEventListener('input', function(e) {
code_output.textContent = e.target.value
})
<input type="text" placeholder="Form Name..." id="formNameInput" required />
<div id="code_output"></div>
Please note that the above code takes advantage of the fact that browsers automatically create a global variable for each element with a unique id attribute value, and this variable has the same name as the value of the id.
If the concept of events is new to you, this might be a good place to get started:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Form number input not transferring to javascript as a variable

I want to use the input value of a form element in a javascript function. However when I declare the variable it doesn't pull the input value from the form. Instead the debugger is just saying; ""
My code is as follows.
HTML:
<input type="number" name="stack" id="stack" min="1" max="600" placeholder="Big Blinds" required>
Javascript:
var stack = document.getElementById("stack").value;
Any advice would be great. Thanks.
It seems like you are getting the value while the input element is still empty. Your code that sets the variable doesn't seem to be encapsulated inside of a function that is run at a time after the input element has had data inputted into it, so the code runs immediately.
You need to make sure that you are getting the value after a value has been inputted.
This is accomplished by adding an event handling function that fires at a particular time. There are a variety of events you can work with (keyup, keydown, input, the form's submit, a button click, etc.). Here's an example of getting the value when a button is clicked.
// Get a reference to the button that will trigger the event function
var btn = document.getElementById("btn");
// Get a reference to the input element (do this outside of the function that
// will need it so you don't wind up scanning the document for it over and over).
// Also, set the variable to the element itself, not a property of the element so
// that if you ever need a different property, you don't have to scan the document
// for the element again:
var input = document.getElementById("stack");
// If you intend to use the value of the element across several functions, declare a
// variable that will hold the value outside of all of them.
var stack = null;
// Set the button up to call a function when it gets clicked.
btn.addEventListener("click", function(){
// When clicked, get the value
stack = input.value;
// Do whatever you want with the stored value.
console.log(stack);
});
<input type="number" name="stack" id="stack" min="1" max="600" placeholder="Big Blinds" required>
<button id="btn">Get Value</button>

Change value of two input fields to the same value, regardless of which field is used

I have two fields on my product's page, using the class '.qty'. What I want to achieve is that when I enter a value in either of the input fields, both of these input fields are filled with that value.
My current code is this:
function updateProductAmount() {
jQuery('.add-to-cart .qty').each(function() {
var productAmount = this.value;
jQuery('.add-to-cart .qty').val(productAmount);
// Requires more work.
});
}
I'm calling this code with an onchange inside the input text elements.
This code, however only works one way. When the first input element is changed, it copies the value to the last input element. However, when the last input element is changed, it changes back to the value of the first input element.
Can anyone point out to me what I'm doing wrong and help me out?
Thanks in advance.
Try the following:
$(document).on('change','.add-to-cart .qty', function(){
$('.add-to-cart .qty').val($(this).val());
});
Js Fiddle Example
Try passing the used inputfield as parameter.
ex:
to check which field was used.
You could also pass a reference to 2nd field (if it is intended that you stick to two fields. Something along the lines should do the trick
<input type="text" value="" name="qty" class="qty" onchange="updateProductAmount(this, jQuery('.add-to-cart'))"/>
<input type="text" value="" name="add-to-cart" class="add-to-cart" onchange="updateProductAmount(this, jQuery('.qty'))"/>
and on the script-part
function updateProductAmount(caller, fieldToChange) {
jQuery(fieldToChange).val(caller.value);
}
If I understand, you need change value of siblings
jQuery( '.add-to-cart .qty' ).on( 'change' , function () {
jQuery( this ).siblings().val( jQuery( this ).val() );
} );
Try this :
$(document).ready(function() {
$(".qty").on("input",function(){
$(".qty").not($(this)).val($(this).val());
})
})
Final code :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" class="qty" value="" />
<input type="text" class="qty" value="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".qty").on("input",function(){
$(".qty").not($(this)).val($(this).val());
})
})
</script>
</body>
</html>
Here is a JS fiddle of what you are trying to do.
function updateProductAmount() {
$('.qty').val($(this).val());
}
$(".qty").change(updateProductAmount);
https://jsfiddle.net/ahmedhawas7/zx3sqxft/
The problem here is that you are setting each value for each input. If you trace the code you'll see something like this:
Change the first input
updateProductAmount is invoked
.each is called so we run your function for all elements matching the '.add-to-cart .qty' selector (both inputs)
We save off the value of "this" input, which will be the first input found by .each, or the input we actually changed
Then the code "jQuery('.add-to-cart .qty').val(productAmount);" will set the value of "productAmount" to all elements that match the '.add-to-cart .qty' selector, which is both inputs. This means that input 2 now has the value of input 1, like we wanted.
Our .each now moves to the second element in the list, retrieves the value of that second input which is equal to the value of the first element by step 5, and sets the value of both inputs to that (which doesn't actually change anything since they both have this value already).
Now, as you can see, if the second input is changed the same order of operations occurs. This means that the first input will be examined first, and its value will be given to all inputs matching the selector, overwriting the value of the second input with the first. Therefore, it doesn't matter what the value of the second input is because by the time the .each gets there it has already been overwritten with the value from input 1.
As others have said, the solution here is to simply find all matching elements you would like to update with jQuery and set them to this.value. Using the jQuery val function updates the value of all matched elements, eliminating the need for a .each loop:
function updateProductAmount() {
$('.add-to-cart .qty').val(this.value);
}
The value of this within jQuery's each() is the value of the object for this iteration of each(), not the element on which the event was fired. You need to store the value to which you are changing the input prior to entering the each().
You then use a second jQuery statement with the each() with the same selector to change the value. This causes all values to be first changed to the first <input>'s value, then changed to the second <input>'s value, then to the third, etc. However, by the time you get to changing all <input> values to the second <input>'s value, the second <input>'s value has already been changed to the value of the first <input>. Effectively, this results in all <input>s following the value of the first <input> without being able to change any input other than the first.
Example showing value of this within each():
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
$('.add-to-cart input.qty').each(function() {
console.log('This points to id: ' + this.id + " ::value=" + this.value);
var productAmount = this.value;
$('.add-to-cart .qty').val(productAmount);
// Requires more work.
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>
Minimally changed, functional: store productAmount before the each():
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
var productAmount = this.value;
$('.add-to-cart input.qty').each(function() {
$('.add-to-cart .qty').val(productAmount);
// Requires more work.
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>
In addition:
There is no need to change the value for the element on which the event is being fired. Thus, you can use .not($(this)) to remove it from the jQuery object over which you are iterating with each().
You, potentially, are iterating over elements that are not <input>s. You can change your selector to only select <input> elements.
Having removed the var productAmount = this.value; from within your each() it is no longer necessary to explicitly iterate over the jQuery object using each(). You can use jQuery's implicit iteration to change the value using val().
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
var productAmount = this.value;
$('.add-to-cart input.qty').not($(this)).val(productAmount);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>
Now that you are not using each(), this will refer to the element on which the event is fired. Thus, there is no need to first store the value in a separate variable. However, if you are expecting to iterate over a large number of elements, then using a separate variable will be slightly faster than getting the value from the element in each iteration.
Final code:
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
$('.add-to-cart input.qty').not($(this)).val(this.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>

How to call functions with variable parameters

I'm trying to type text into the textbox and when I click the button have it alert me the text. I can't seem to get the variable to work in the function. I'm not sure if "var i = document.getElementById('apple').value;" is correct.
document.querySelector("input[type=button]").addEventListener("click", function(event){
alert(i);});
<form>
Enter:<br>
<input type="text" name="inputbox" id="apple">
<input type="button" name="alert" value="alert">
</form>
<script>
var i = document.getElementById('apple').value;
document.querySelector("input[type=button]")
.addEventListener("click",function(event){
alert(i);});
</script>
Demo: http://codepen.io/michaelaharvey/pen/QyKvme
I also tried:
var i = form.inputbox.value;
but that didn't work either
document.querySelector("input[type=button]")
.addEventListener("click",function(event){
var i = document.getElementById('apple').value;
alert(i);
});
You need to query for the value at the time of click.
The problem is that you are storing the element's value in a variable when the DOM loads. Therefore when the click event is fired, the value property is an empty string (or whatever the value was when the DOM loaded).
Retrieve the value when the click event is fired instead:
Updated Example
document.querySelector("input[type=button]").addEventListener("click", function(event) {
var value = document.getElementById('apple').value
alert(value);
});

Categories