For the numeric input element, is there a way to check if there is only a minus input? I can do this in a bad way in the example below. I'm looking for a more precise, simple method that I can access via the element.
When input is only - => numberInput.value equals to empty string also innerText and innerHTML equals to empty string.
var lastKey;
var checkNegativeSign = function() {
let numberInput = document.querySelector("input");
if(lastKey === '-') {
document.getElementById("result").innerText = "is negative";
} else {
document.getElementById("result").innerText = "";
}
}
var onKeyUp = function(event) {
// Should check Escape, ctrl etc.
lastKey =event.key;
}
<html>
<body>
<input type="number" onkeyup="onKeyUp(event)" />
<button onclick="checkNegativeSign()">Check Negative Sign</button>
<div id="result"> </div>
</body>
</html>
You could do
let sign = Math.sign(Number(document.querySelector("input").value))
console.log(sign === 1? "positive": "negative")
Related
how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>
This question already has answers here:
Get first word of string
(12 answers)
Closed 1 year ago.
I want to get only the first value from copy-paste value.
For example:
my copy text is: Lorem Lipsum Test
So when I copied this above text and paste it into the HTML input filed there need to come only "Lorem" I don't need other text
Is there any way to achieve these things?
Thanks in advance.
it only returns always the first word from string input and you have to clear for copy new value then it's show first word of the new copied string.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#getfirstword").on("keyup", function(e) {
debugger
// do stuff!
var str = $(this).val();
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
var firstWord ="";
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
firstWord = str1[i].split(' ')[0];
}
$("#input1").val(firstWord);
})
});
</script>
</head>
<body>
<input id="getfirstword" />
<input id="input1" disabled/>
</body>
</html>
You can add an input event to see what you are trying to add to your element. This code will split your pasted text and only add the first word.
const input = document.querySelector('input');
const log = document.getElementById('values');
input.addEventListener('input', updateValue);
var previousValue = "";
function updateValue(e) {
log.textContent = e.data;
if (e.data && e.inputType == "insertFromPaste") {
if (e.data.length > 1) {
let val = e.data.split(" ")[0];
let str = previousValue + val;
e.target.value = str;
}
}
previousValue = e.target.value;
}
<input placeholder="Enter some text" name="name"/>
<p id="values"></p>
I need to place a limit for the number of commas entered in the text area
I tried these links but it dint help
Limit the number of commas in a TextBox
The comma in the textBox
Iam using php. Is it possible to implement php or javascript here.
You should wait for DOMContentLoaded event, and afterwards bind the textarea with a callback for the "input" event:
const MAX_COMMAS = 3;
document.addEventListener("DOMContentLoaded", function(event) {
let textarea = document.getElementById('textbox');
textarea.addEventListener("input", function(event) {
let matchCommas = this.value.match(/,/g);
if (Array.isArray(matchCommas) && matchCommas.length > MAX_COMMAS) {
this.value = this.value.substring(0, this.value.length - 1); // remove the last comma
alert("MAX COMMAS EXCEEDED!");
}
});
});
<textarea id="textbox" cols="40" rows="4"></textarea>
HTML:
<textarea id="textarea" rows="20"></textarea>
JavaScript:
var textarea = document.getElementById('textarea');
var maxCommas = 5;
var filterCommas = function(event) {
var textCommas = this.value.match(/[,]/g);
if(textCommas.length >= maxCommas && event.key === ',') {
event.preventDefault();
return false;
}
}
textarea.onkeydown = filterCommas;
textarea.onkeypress = filterCommas;
textarea.onchange = filterCommas;`
https://jsfiddle.net/xL04qb8c/2/
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}
I can't figure out how to convert the text typed into a text input box (txtQuestion) into all lower case, i.e. typing "input" or "INpUt" will be read the same and output the same result.
Use toLowerCase() function. Eg: "INPuT".toLowerCase();
exampleFunction = function(){
//First we get the value of input
var oldValue = document.getElementById('input').value;
//Second transform into lowered case
var loweredCase = oldValue.toLowerCase();
//Set the new value of input
document.getElementById('input').value = loweredCase;
}
<input id="input" type="text" onkeyup="exampleFunction()" />
You have to choose the events that you want to watch and then return to the input the same value but lowercase:
function InputLowerCaseCtrl(element, event) {
console.log(element.value)
return element.value = (element.value || '').toLowerCase();
};
InputLowerCaseCtrl.bindTo = ['blur'].join(' ');
document.addEventListener('DOMContentLoaded', function() {
var input = document.querySelector('.input-lowercase');
return input.addEventListener(InputLowerCaseCtrl.bindTo, InputLowerCaseCtrl.bind(this, input));
});
<input class="input-lowercase" type="text" />
You can convert any string input to lowercase using the String.prototype.toLowerCase function
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
For you example with an input for txtQuestion.
var inputStringLowerCase = inputTxtQuestion.value.toLowerCase();
https://jsfiddle.net/fbkq2po4/