How to check users inputed string is in the array in javascript? - javascript

I want my user type a string in input box of html,than i want to check if it is in the array of items or not.I am using this JS code:
var items = ["apple"];
var userInput = document.getElementById("input").value;
function lol() {
document.write(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>
But when i run this every time it gives false.

You need to move
var userInput = document.getElementById("input").value;
into the function, because it assigns the value at start and is never changing.
var items = ["apple"];
function lol() {
var userInput = document.getElementById("input").value;
console.log(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>

You can add an onChange event listener for the input field and change the userInput value for every change in the input field.
var items = ["apple"];
var userInput = document.getElementById("input").value;
function onChangeUserInput (event) {
console.log(event.target.value);
userInput = event.target.value;
}
document.getElementById("input").addEventListener('change', onChangeUserInput);
function lol() {
document.write(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>

I tried to replicate the error. This is my code -
var items = ['apple', 'orange', 'mango'];
var input = 'apple';
console.log(items.includes('apple'));
It works as expected. The problem is that you have called the lol() function in the button. So, the function is called when the page loads and not when it is clicked. Another thing is that you have to move the line in which you get user input into the lol() function.

Related

How to link a button and input field

How do I link a button to an input field? I am trying to create something so that when I click on the button, it will add what was in the text field, to an array (shown below)
const userTags = [];
function addTags(event) {
userTags.push(event.target.__ what do I even put here to get the input data? __)
}
<label>
Tags: <input type="text" name="todoTags"/> <button>Create new tag</button>
</label>
Again, I am trying to link up the button so that when I click it, it will grab the data from the input field, and add that data to the 'userTag' array with the addTags() function.
You can use the event target within your callback function to get the label using const parent = e.target.closest('label'), then use querySelector() to get the input element that is grouped under that label tag using const input = parent.querySelector('input') then set a variable to that value like const inputValue = input.value, then push the value into your array.
Your callback function is placed into an event listener for click.
const btn = document.querySelector('.btn')
const userTags = []
function getValue(e) {
// get the label by traversing up the DOM tree to the closest label element
const parent = e.target.closest('label')
// get the input that lives inside the label element using querySelector
const input = parent.querySelector('input')
// get the inputs value and assign to variable
const inputValue = input.value
// only push values that are not empty
if (inputValue !== "") {
userTags.push(inputValue)
}
console.log(userTags)
}
//event listener for click on btn element
btn.addEventListener('click', getValue)
<label>
Tags: <input type="text" name="todoTags"/> <button class="btn">Create new tag</button>
</label>
let valueArray = []
function getValue(){
let value = document.getElementById("input").value
valueArray.push(value)
document.getElementById("Messages").innerHTML = valueArray
}
<body>
<input type="text" id="input">
<button onclick="getValue()">Click</button>
<div id="Messages"></div>
</body>
Get the element with document.getElementById and then take its value
document.getElementById("Put Id In Here").value

2 textbox that copies each other value while typing, but the other textbox has no comma

I'm currently working with 2 textboxes that copies each other values. But the thing is, my 1st textbox has an autocomma. How could I make my 2nd textbox ignore the comma?
For example. My first textbox value is 1,000 then my 2nd textbox
value should be 1000.
HTML
<input type="text" value="" id="textbox1"/>
<input type="text" value="" id="textbox2"/>
Script
//this function is for my autocomma
function updateTextView(_obj){
var num = getNumber(_obj.val());
if(num==0){
_obj.val('');
}else{
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#textbox1').on('keyup',function(){
updateTextView($(this));
});
});
//this function copies the textbox1 values to textbox value 2
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
You modify the function updateTextView as below:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
$("#textbox2").val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
And then remove the following:
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
In plain JS:
Try the onkeyup() event added to the first textbox. Then replace all commas in the value of the first box with nothing using value.replace(/,/g, ""). And then copy the value of the first input
function update(input) {
var value = input.value.replace(/,/g, "");
document.getElementById("second-textbox").value = value;
}
<input onkeyup="(update(this))" />
<input id="second-textbox" />
to the second.

Add search field result to an empty array

Every time a user types something into a search field, I want it to be added to an empty array I've created. For some reason, my current code only adds an empty string to the array but not the string itself:
Javascript
var myArray=[];
var submit = document.getElementById("submit");
var result = document.getElementById("result").value;
submit.addEventListener("click", function() {
myArray.push(result);
})
HTML
<input id="result" type="text"><button id="submit">Submit</button>

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

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