Search in arrays with javascript on write - javascript

I have an html page with two input text boxes.
With javascript, I declare two arrays with numbers and names.
number - name:
1 - John
2 - Sarah
3 - Peter
When I write the number on input A, i need the name appears on input B, and if i write the name on input B i need the number appears on input A
Example: I write "Sarah" on input B and number "2" appears on input A
Example 2: I write "1" on input A and "John" appears on input B

if you're using pure js you need define a onkeyup event in your input and change the 2 array by a map(hash or dictionary) here the code:
<input id="name" type="text" onkeyup="SearchText(this.value)"/>
<input id="value" type="text" onkeyup="SearchId(this.value)"/>
<script>
function SearchText(val) {
txt = document.getElementById("value")
if (val.toLowerCase() in Persons) {
txt.value = Persons[val.toLowerCase()];
} else {
txt.value = '';
}
};
function SearchId(val) {
txt = document.getElementById("name");
for (p in Persons) {
if (Persons[p] == val){
txt.value = p;
break;
} else {
txt.value = '';
}
}
};
</script>
Persons is a map:
Persons = {
'john':1,
'sara':2,
'peter':3
};
this fiddle can help you:
Example Fiddle

Related

create a text box accepting only 0-9 and get these numbers appear in another text box by adding "1" to each number

I have two text box fields , I created the first one accepting numbers only from 0-9 by regular Expression and get them appears again in a second text box field; I need when you type any number in the first text box field, these numbers appear in the second text box by adding "1" to each number
for example:
when you input "0" in the first field ==> the second field shows "1"
when you input "1" in the first field ==> the second field shows "2"
.....
when you input "9" in the first field ==> alert appears to tell you that "the series is ended, you cannot type 9"
this is the JS code
var n1 = document.getElementById('numbers-1').value,
n2 = document.getElementById('numbers-2').value;
function numbersOnly(input) {
var regex2 = /[^0-9]/;
input.value = input.value.replace(regex2, "");
var n2 = document.getElementById('numbers-1').value;
document.getElementById('numbers-2').value = n2;
}
and this is the HTML Code
<input type="text" maxlength="10" id="numbers-1" oninput="numbersOnly(this)"><br>
<input type="text" id="numbers-2">
thanks guys
You can do it like this,
let me know if any more explanation needed
function numbersOnly(input) {
var regex2 = /[^0-9]/;
var val = parseInt(input.replace(regex2, ""));
if(!isNaN(val)) {
if(val.toString().indexOf('9') > -1) {
document.getElementById('numbers-1').value = "";
document.getElementById('numbers-2').value = "";
alert('the series is ended, you cannot type 9');
}
else{
document.getElementById('numbers-2').value = val+1;
}
} else {
document.getElementById('numbers-1').value = "";
document.getElementById('numbers-2').value = "";
}
}
<input type="text" maxlength="10" id="numbers-1" oninput="numbersOnly(this.value)"><br>
<input type="text" id="numbers-2">
Try this one
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="number" type="number" max="9" min="0" ng-keyup="print()" required><br><br>
<input ng-model="answer" type="number">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.print = function()
{
if($scope.number >= 9)
{
alert('the series is ended, you cannot type 9');
$scope.number = "";
}
else
{
$scope.answer= $scope.number + 1;
}
}
});
</script>
</body>
</html>

How to detect when a user types a string in an input type number?

I have a form with an input type number. I want to display a message when the user types a string.
When I try to retrieve the value of the input, I always get an empty string.
When I type a number it works fine but not with a string...
I tried with both jQuery and javascript.
var inputVal = $(this).val();
var inputValJs = document.getElementById("myInput").value;
console.log(inputVal); // if 99 => 99 if test => ''
console.log(inputValJs); // if 99 => 99 if test => ''
How should I proceed ?
Input type number only allow you to enter numbers
var inputValJs = document.getElementById("myInput").value;
console.log(inputValJs);
<input type="number" id="myInput" name="tentacles" value ="33">
If you really need an input text you can do the following:
The event input captures the changes in the input text.
var messageElem = document.querySelector('#myMessage');
document.querySelector('#myInput').addEventListener('input', function(e) {
if (this.value === '' || /^[0-9]+$/.test(this.value)) {
messageElem.textContent = "";
} else {
messageElem.textContent = "Only numbers";
}
});
<input type="txt" id='myInput'>
<p id='myMessage'>
Number type input only accept number value.
To retrieve input value, use event listener :
var myValue = '';
document.getElementById("myInput").addEventListener('input', function(e) {
myValue = e.target.value;
console.log(myValue);
});
<input type="number" id="myInput">

How to add word from input to another input form

I am creating an ajax live search, I am using fill function. so when I clicked the word that pop up when I search it will fill to another input form. but I want when it fill its not replace the older word.
for example I have input1 and input2. input1 is for search and input2 is for fill the word that i choice. for example i already choice word1 from input1. word1 will fill input2.
like this input2 = word1
but when i search another word in input1 i want that word i choice not replace input2 but add it. for example i choice word2 so in input2 will be
like this input2 = word1, word2
here my live search script
function fill(Value) {
$('#tag_list').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#tag").keyup(function() {
$('#display').show();
var name = $('#tag').val();
if (name == "") {
$("#display").html("");
$("#display").hide();
}
else {
$.ajax({
type: "POST",
url: "../cari/tag.php",
data: {
search: name
},
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
my tag.php code
<div class="result" onclick='fill("<?php echo $caris['id_t']; ?>,")'>
You can append values like below
function fill(Value) {
var $tagList = $('#tag_list');
var previousVal = $tagList.val();
if(previousVal) {
previousVal += ", ";
}
$tagList.val(previousVal + Value);
$('#display').hide();
}
Your can use Addition assignment :
The addition assignment operator adds the value of the right operand
to a variable and assigns the result to the variable. The types of the
two operands determine the behavior of the addition assignment
operator. Addition or concatenation is possible. See the addition
operator for more details.
Syntax
Operator: x += y
Meaning: x = x + y
for your case :
var query = '';
$('#search').on('click',function(){
fill();
});
function fill() {
query += $('#input1').val() + ',';
$('#input2').val(query.slice(0,-1));
/* The slice function will remove the last caractere from string ',' */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input1" id="input1">
<input type="text" name="input2" id="input2">
<button id="search">search</button>

Post data to 2 dimensional array javascript

I have source, like this :
<label>Name:</label>
<input type="text" name="text1"/>
<label>Weight:</label>
<input type="text" name="text2"/>
<button onclick="myfunction">Add</button>
<p id="demo"></p>
<script>
var array = new Array();
function myFunction() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
if(text1 == "" || text2 == ""){
alert("Empty!!");
}else{
array = {'data' : [{"Text1" : text1, "Text2" : text2}]}
}
}
</script>
My question is, how do i post value each of text to 2 dimensional array in java script? technically, we can post value to 2D array again and again, so the array will looks like:
var data = {{text1,text2},....,{text-n,text-n+1}}
Then figure it out in table based on 2D array. I have tried, but still not work. I'm not proficient with javascript. Really need help..
You can push a new element to your array every time the button is clicked. The use this array.
var array = [];
function change() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
if (text1 == "" || text2 == "") {
alert("Empty!!");
return;
}
array.push({
'data': {
"Text1": text1,
"Text2": text2
}
});
console.log(array);
}
Also, you are trying to get element by Id but no Id is assigned to input elements. I corrected that in the this Fiddle. This is working, take a look.
You need to use Jquery for this
var array = {
'x': { a: 'aaa', c: 'xxx' },
'y': { b: 'bbb', d: 'yyy' }
};
Use Jquery here
$.post( '/herp.php', array, function(d) {
// process response here
});
Put your input in a form, then use serializeArray in jquery.

How do you add the values from input fields and update another field with the result in jQuery?

Preamble: I'm more of a PHP/MySQL guy, just starting to dabble in javascript/jQuery, so please excuse this dumb newbie question. Couldn't figure it out from the Docs.
I have a form without a submit button. The goal is to allow the user to input values into several form fields and use jQuery to total them up on the bottom in a div. The form kinda looks like this but prettier:
<form>
Enter Value: <input class="addme" type="text" name="field1" size="1">
Enter Value: <input class="addme" type="text" name="field2" size="1">
Enter Value: <input class="addme" type="text" name="field3" size="1">
etc.....
<div>Result:<span id="result"></span></div>
</form>
Is it possible to add these up? And if so, can it be done anytime one of the input fields changes?
Thanks.
UPDATE:
Brian posted a cool collaborative sandbox so I edited the code to look more like what I have and it's here:
http://jsbin.com/orequ/
to edit go here:
http://jsbin.com/orequ/edit
Sticking this right after the </form> tag should do it:
<script>
function displayTotal() {
var sum = 0
var values = $('.addme').each(function(){
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#result').text(sum);
}
$('.addme').keyup(displayTotal);
</script>
Here's a demo: http://jsbin.com/iboqo (Editable via http://jsbin.com/iboqo/edit)
Any non numeric or blank values will be disregarded in the calculation (they'll be given a value of zero and hence not affect the sum).
function sumValues() {
var sum = 0;
$("input.addme").each(function(){
var $this = $(this);
var amount = parseInt($this.val(), 10);
sum += amount === "" || isNaN(amount)? 0 : amount;
});
$("#result").text(sum);
}
$(function() {
sumValues();
$("input.addme").keyup(function(){
sumValues();
});
});
Working Demo
(function(){
var context = $("form"), elements = $("input.addme", context);
function getSum(elements) {
var sum = 0;
$(elements, context).each( function() {
var v = parseInt(this.value);
v === parseInt(v,10) ? sum += v : sum = sum;
})
return sum;
}
$(elements).bind("keyup", function() {
$("#result").text( getSum(elements) );
});
})();
isolated scope and context, included dealing with non-integer values, function getSum should rather return a value than do something itself.
Try this:
$(".addme").bind("change",function(){
var _sum = 0;
$(".addme").each(function(i){
_sum += parseInt($(this).val());
});
$("#result").val(_sum);
});

Categories