How to add word from input to another input form - javascript

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>

Related

How to get the number of input tags containing certain text?

My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/

Allow only number digits in input type regex. issue is i am able to type this(1.) , want to prevent it

MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.

Text Box Search / Javascript Function Arrays **not corresponding**

I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>

how to compare equals '=' in javascript

I am doing a calculator program in javascript and HTML. I have a button with a value '=' in it. In that one when a user click on "=" button in calculator. it should start evaluate the input he/she had given so far. But when a user click '=' button i tried to compare like this
$(".calcinput").click(function () {
var res = $(this).val();
if (res == '=') {
//code to handle when '=' is pressed;
}
}
but it didn't work please help me.
Your code is good enough to handle the event .. Just add an extra = in comapre
$(".calcinput").click(function () {
var res = $(this).val();
//if (res == '=') {
if (res === '=') {
//code to handle when '=' is pressed;
}
});
Next check where you used div or button or something else element to represent the button =
If it is button then use val() to extract the value
var res = $(this).val();
If the element is div then it could be innerHTML or innerTEXT
var res = $(this).innerHTML;
//Or
var res = $(this).innerText;
You can add an extra line to check whether you getting proper value of element
var res = $(this).val();
alert(res);
You can also use $(this).val() provided you have non empty value attribute in the button
HTML
<button class ="calcinput" type ="button">1</button>
<button class ="calcinput" type ="button">2</button>
<button class ="calcinput" type ="button" value="=">=</button>
JS
$(".calcinput").on('click',function(){
if($(this).val() === "="){
alert("equal");
}
})
WORKING FIDDLE
use
$(this).text()
to retrieve button text instead of
$(this).val()
in your code
= is text of button element and not value. Due to which .val() returns empty string. hence you need to use .text() instead of .val here:
$(".calcinput").click(function () {
var res = $(this).text();
if (res == '=') {
//code to handle when '=' is pressed;
}
});
check out this Demo . I have done a operation for ADD Simillarly you can do it for all operations ..keep it simple
A<input type="text" class="a" /><br/>
B<input type="text" class="b" />
<input type="button" class="calcinput" />
$(".calcinput").click(function () {
var res1 = $(".a").val();
var res2 = $(".b").val();
alert(parseFloat(res1) + parseFloat(res2));
});

Search in arrays with javascript on write

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

Categories