I want to detect if a user types one of the strings of my list and then output in what string the user typed in the console.
HTML
<input id="input"></input>
JS
window.onload = function(){
var input = document.getElementById('formula');
var strings = ["string1", "string2", "string3", "string4"]
formula.onkeypress = function (e) {
if (input.value.includes(strings)) {
console.log("Input contains a the string:" + string???)
}
};
}
Try using String.indexOf() and Array.filter()
window.onload = function() {
var strings = ["string1", "string2", "string3", "string4"];
/* replaced `formula` with `input` */
document.getElementById('input').oninput = function(e) {
var find = this.value;
if (0 < find.length) {
var matches = strings.filter(function(s) {
return -1 !== s.indexOf(find);
});
console.log('find string', find, ', matches found', matches);
}
};
};
<input id="input" />
You are fetching element by the wrong ID. The ID of the input is input, and not formula. Ignoring this typo, you need to check the inclusion in the array instead. Replace this:
if (input.value.includes(strings)) {
with this:
if (strings.includes(input.value)) {
Additionally, using keypress event doesn't serve the purpose as the updated value will be fetched after you press one more key. Use oninput instead.
Edit 1:
You can use Array#some to check if the input value contains any string from the array.
window.onload = function() {
var input = document.getElementById('input');
var strings = ["string1", "string2", "string3", "string4"]
input.oninput = function(e) {
if (strings.some(str => input.value.includes(str))) {
console.log("Input contains a the string:" + input.value)
}
};
}
<input id="input"></input>
use like it:-
formula.onkeypress = function (e) {
if (strings.includes(input.value)) {
console.log("Input contains a the string:" + input.value)
}
};
There are several issues in your code:
The id is incorrect for input element
You need to use onkeyup event to get the immediately typed character
You need to use includes() in array type variable.
window.onload = function(){
var input = document.getElementById('formula');
var strings = ["string1", "string2", "string3", "string4"]
input.onkeyup = function (e) {
if (strings.includes(input.value)) {
console.log("Input contains a the string:" + input.value)
}
};
}
<input id="formula" />
If you want to make an autocomplete form : Autocomplete
Related
I am using the following in and attempt to get a user's letter guess to appear on screen, but when I check the devtools the keypress is being returned to the array like [ , , , , , ,]. No letters. Ideas?
var letguessText = document.getElementById("letguess")
var guessArray = []
document.onkeypress = function(event) {
var guess = event.key
guessArray.push(String.fromCharCode(guess));
letguessText.textContent = guessArray;
}
You don't need fromCharCode as the event.key is the character. Here is an example.
var letguessText = document.getElementById("letguess")
var guessArray = []
document.onkeypress = function(event) {
var guess = event.key
guessArray.push(guess);
letguessText.textContent = guessArray;
}
<p id="letguess">Start typing</p>
When I submit the form and I try to get the Roomsno input value its showing like
this-
Array ( [0] => 1,2 ); why???
How can I send it so that it will come as a real array means like this-
Array([0]=>1 [1]=>2)
<input type="hidden" class="form-control" name="Roomsno" id="Roomsno" required>
<script>
var rmidarray = []; // new Array()
var rmnoarray = [];
$('.roomtype').change(function() {
roomss_id = $(this).attr('data-id');
no_room = $(this).val();
var check = rmidarray.includes(roomss_id);
if (check == true) {
// alert('hi')
index = rmidarray.indexOf(roomss_id);
// alert(index);
rmnoarray.splice(index, 1, no_room);
// rmnoarray[index].push(no_room);
} else if (check == false) {
// alert('by');
rmidarray.push(roomss_id);
rmnoarray.push(no_room);
} else {
alert('No rooms Selected!!!')
}
$("#Roomsno").val(rmnoarray);
});
</script>
As the value is in array format so Rather than setting the value directly use jason.stringfy-
Ex.
$("#Roomsno").val(rmnoarray); //Instead of this one
$('#Roomsno').val(JSON.stringify(rmnoarray)); //This one worked for me
And when i try to get the value i use json.decode and the value will come as array and we can use it normally as we use array. The array will come like- Array([0]=>1[1]=>2)
Trying to make a web page that will get each letter a user inputs and output it in a phonetic alphabet. For example (user types: Hello)(Output: Hotel , Echo , Lima, Lima, Oscar). This is what I have so far just need some guidance on how to get the value of each letter and compare it to like an Array to get the output.
//define UI variables
const userInput = document.querySelector('#input');
const phoneticAlphabet = ["Alpha"," Bravo","Charlie"];
//load all event listeners
loadEventListeners();
function loadEventListeners() {
//add submit event
form.addEventListener('submit', submitInput);
}
//submit user input
function submitInput(e) {
console.log(userInput.value);
if (userInput.value === '') {
alert('Add Input');
}
e.preventDefault();
}
I presume that you would like to replace non-convertible characters from the input. For the same, I am using regular expression. I have also added the response in a "p" tag. And the code runs on clicking "Submit".
Update:
Extended my array for all alphabets :)
Update 2:
Thanks #CharlieBatista for pointing out. Now, the input accepts uppercase characters as well.
//define UI variables
const form = document.phoneticForm;
const userInput = document.querySelector('#input');
const output = document.querySelector('#output');
const phoneticAlphabet = ['Alpha','Bravo','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu'];
//load all event listeners
loadEventListeners();
function loadEventListeners() {
//add submit event
form.addEventListener('submit', submitInput);
}
//submit user input
function submitInput(e) {
e.preventDefault();
var value = userInput.value;
if (value === '') {
alert('Add Input');
} else {
value = value.replace(/[^a-zA-Z]/gi,'');
userInput.value = value;
value = value.toLowerCase();
var outputArr = [];
for(var i = 0; i < value.length; i++){
outputArr.push(phoneticAlphabet[value.charCodeAt(i)-97]);
}
output.innerHTML = outputArr.join(', ');
}
}
<form name="phoneticForm">
<input type="text" id="input">
<input type="submit">
</form>
<p id="output"></p>
You can use the key property on the keydown event of the field to get the character that was pressed.
Then check if the key is a printable key using key.length === 1 (see this answer).
If the key is printable, convert it to uppercase, then to its character code using String.prototype.charCodeAt() and then subtract 65 from it (character A). This will give you the index in your array.
If this index is within the bounds of the array, access the array and print the character.
const phoneticAlphabet = ['Alpha','Bravo','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu'];
document.querySelector('#input').addEventListener('keydown', e => {
const isPrintable = e.key.length === 1;
console.clear();
if (isPrintable) {
const idx = e.key.toUpperCase().charCodeAt(0) - 65;
if (idx >= 0 && idx < phoneticAlphabet.length) {
const phoneme = phoneticAlphabet[idx];
console.log(phoneme);
}
}
});
<input type="text" id="input">
Trying to get all checkboxes with the class 'testclass' to check if they are checked, if so, add their value to theString.
$('.testclass').each(function () {
if (this.checked) {
var x = this.val();
theString += x + ";";
}
});
It seems to be getting stuck at the part where it gets the val?
You can use :checked with class .testclass to get the checked elements with specific class:
$('.testclass:checked').each(function() {
console.log(this.value)
});
just seen the code and it seems that your problem is this:
this.val();
try changing either to this:
this.value
or
$(this).val(); //<---------jQuery version
Your Problem
The problem with your code is this is a DOM element and not a jQuery object. You would need to change
var x = this.val();
to
var x = this.value;
//or
var x = $(this).value; //slower
Better solution
You can use :checked in your selector to get the checkboxes that are selected. You can than use map() to get the values.
var values = $(".testclass:checked") //get the checked checkboxes
.map(function () { //Map loops through each element in the jQuery object produces a new jQuery object containing the return values.
return this.value;
})
.get() //gets the newly created array
.join(","); //joins the array with commas as a seperator
using $.map
try this
var theString=$('.testclass:checked').map(function(n){
return this.value;
}).get().join(','); //get the checked value and join it with ,
alert(theString);
theString will have all the checked values commaseperated...
Try below code for get all checked checkbox value
$('.testclass:checked').each(function () {
var x = this.val();
theString += x + ";";
});
Try
var values = $('.testclass:checked').map(function(idx, el) {
return $(el).val()
}).get();
Not using jQuery :
checkedList = [].slice.call (document.querySelectorAll ('.testclass:checked'))
.map (function (el) { return el.value; })
.join (';');
Demo at http://jsfiddle.net/jstoolsmith/AeXWs/
Please have a look at http://jsfiddle.net/2dJAN/54/
$('.check').on("click",function(){
$.each($('.testclass'), function(){
if($(this).is(':checked')){
alert($(this).val());
}
});
});
try
$('.testclass:checked').each(function() {
alert(($(this).value))
});
var theString = "":
$('.testclass').each(function () {
if ($(this).checked) {
theString += $(this).val()+";";
}
});
UPDATE: My bad, missed the part of question, where you needed values too.
I making one application which contains 2 input box and one input button.My qestion is when user enter some input eg. "I used to going somewhere" then my result should be "I UD GNG somewhere." For that i am using this code http://pastebin.com/vHkhASdZ
Please,anyone have idea how to solve then pls reply me asap. I solved my issue in php but in case of javascript i don't have any idea. Here is my output link in php http://codepad.viper-7.com/SQvO6Y
I want my result in javascript.Pls anyone know then give reply.
Use this function
var replaceText = function () {
var inputval = document.getElementById('first_text').value;
var arr = {
"going": "GNG",
"used to": "UD",
"as soon as possible": "ASAP",
"to do fast": "tdf"
}
for(var key in arr) {
if (typeof (arr[key]) !== "undefined") inputval = inputval.replace(key, arr[key])
}
document.getElementById("second_text").value = inputval;
}
Do something like this. Define word replace as map.
var wordmap = {
going: 'GNG',
'used to': 'UD',
'as soon as possible': 'asap',
'to do fast': 'tdf',
..
}
and define function that iterates every word in the input string.
function replace( text ) {
var input = text.split(' ');
var outputval = []
for (var i in input) {
outputval.push( wordmap[input[i]] || input[i] )
}
return outputval.join(' ');
}
And use it like this
var output = replace( document.getElementById('first_text').value );