Get value from input box with js [duplicate] - javascript

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 5 years ago.
I have no idea how to get value from input box. Right now when I click BET button it just subtracts 100, I want to achieve so when I enter the value in the text box and hit bet it'll subtract the value which I've entered from the balance. Here is my code:
HTML:
<div>
<input type="text" value=0 name="betAmount">
<button class="betBTN">BET</button>
</div>
JS:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('.betBTN').addEventListener('click', function() {
var toAdd = document.querySelector('div').textContent - 100;
document.querySelector('div').innerHTML = "";
document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd);
});
});
Any suggestions?

Replace your 100 with
document.querySelector("input").value;
This line will get the value of input element
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('.betBTN').addEventListener('click', function() {
var toAdd = document.querySelector('div').textContent - document.querySelector("input").value;
document.querySelector('div').innerHTML = "";
document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd);
});
});
Balance: <div>1000</div>
<input type="text" value=0 name="betAmount">
<button class="betBTN">BET</button>

If you’re talking about the entered value, then the following would do the job:
document.querySelector('input[name="betAmount"]').value;
All input elements, whether they are HTML input or textarea or select etc have a value property which is the actual value of the user data.

Related

Have input element "follow along" as value is updated programmatically [duplicate]

This question already has answers here:
Input value is a string instead of a number
(4 answers)
Closed 3 months ago.
If you run the code snippet below and type (anything) into the input, the input will "follow along" with your text input, and not just show the first few characters indefinitely.
I'm wondering if this is possible to achieve if the input value is changed programmatically, in this example, the "Update Input" button.
const updateInput = () => {
const input1 = document.getElementById('input1');
input1.value += (Math.random()*1000).toString();
}
<input id="input1" style="width:50px" />
<button onclick="updateInput()">Update Input</button>
edit: This question has nothing to do with Input value is a string instead of a number
You need to focus it and then set selection range
const updateInput = () => {
const input1 = document.getElementById('input1');
input1.value += Math.random()*1000;
input1.focus()
input1.setSelectionRange(input1.value.length, input1.value.length);
}
<input id="input1" style="width:50px" />
<button onclick="updateInput()">Update Input</button>

How to make in input the first letter capitalized? [duplicate]

This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 3 years ago.
How to make in input the first letter capitalized? Css method text-transform: capitalize; does not fit.
var positions = $('ul li');
var inputSearch = $('input');
inputSearch.val('').on('input', function(e){
var terms = this.value.toLowerCase().split(/[\s,.]+/);
positions.each(function(){
var text = this.innerText.toLowerCase();
this.hidden = !terms.every(function(term){
return text.indexOf(term) !== -1;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="placeholder">
<ul>
<li>wrew</li>
<li>w</li>
<li>rew</li>
</ul>
$('ul li').each(function(index, elem){
var text = $(elem).text();
text = text.charAt(0).toUpperCase() + text.slice(1);
$(elem).text(text);
});
You can use the code below. This code will track when you press the key, and when you do, it'll get the current value of the input (before the key you pressed is added). It would then check if the last character in the input field is a space. If it is, it'll add to text the key you just pressed, but uppercase. If not, it'll simply add the key you just pressed to text
Then, the next time you press any key, the value of the input would change the the value of text, which would have the first letter of every word capitalized.
var text = "";
var val;
$(".input").keypress(function(e) {
val = $(this).val();
if (val[val.length - 1] == ' ') {
text += e.key.toUpperCase();
}
else {
text += e.key;
}
});
$(".input").keydown(function() {
$(this).val(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Placeholder" class="input" />

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources