how to validate on blank input search box - javascript

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>

Related

Need to limit the comma(,) entered in textbox

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/

How to take an input that is equal to 10 and perform a function that says awesome to the screen

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');
}

Preventing form submit based on entering the same numbers in the box input

I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
and here I am disallowing users to enter the same numbers in the box, but what I really want is to prevent the form submit instead
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 3 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
this is my form prevent default
$("form#customer-summary").submit(function(e){
e.preventDefault();
alert("prevent submit");
});
How can I combine these two parts so I dont allow users to submit same numbers in the box ?
var inputNode = document.getElementById('my_account');
var customer_summary = document.getElementById('customer-summary');
customer_summary.addEventListener('submit',function(e){
if(!is_unique(inputNode.value)){
e.preventDefault();
alert("prevent submit");
}
});
function is_unique(val){
for(var i=0;i<val.length;i++){
if(val.indexOf(val.charAt(i)) != val.lastIndexOf(val.charAt(i))){
return false;
}
}
return true;
}
I think this should do the trick. Working jsfiddle: https://jsfiddle.net/m31h1zhg/2/.

Intercept input entering

Is there a way to intercept the value the user inputs before it ever even appears in the element? I tried to use Object.defineProperty but it appears to not work for InputElement.value since
var value;
Object.defineProperty($('input')[0], 'value', {
get: function() {return value},
set: function(val) {console.log(val); value = val;}
});
doesn't appear to change any behavior. Or is oninput/onchange the only option? Since I'd rather have my code executes before the browser's.
http://jsfiddle.net/zpmu1xcu/
If you want to detect input before the text is entered by the browser, you can use the Element.onkeydown property. This event fires as soon as the key is pressed down, before the browser interprets the action.
var demo_i = document.getElementById('demo_i');
var demo_d = document.getElementById('demo_d');
demo_i.onkeydown = function(e) {
demo_d.textContent = e.which;
// Returning false stops the event from going any further
return false;
}
<input id="demo_i"><div id="demo_d"></div>
is this what you are looking for?
function InterceptInputValue($input) {
var value = $input.val();
// intercept value that changes and saved to value variable
$input.keydown(function(e) {
value += String.fromCharCode(e.keyCode);
return false;
});
this.getValue = function() {
return value;
};
}
var i = new InterceptInputValue($("input"));
$("input").blur(function() {
alert('input value is: ' + i.getValue());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
I think you're only option is keyup.
It is the only one that can capture the data and not leave any behind.
Using the snippet below, type test in each of the text boxes.
The code tries to reset the value to blank with each key stroke.
keyup is the only one that deletes the input with each stroke.
keydown clears the last character typed, once you leave the field.
keypress leaves the last character typed in the input field
var tbxKeyDown = document.getElementById('tbxKeyDown');
var tbxKeyUp = document.getElementById('tbxKeyUp');
var tbxKeyPress = document.getElementById('tbxKeyPress');
// [Jedi mind trick] ==> you entered nothing
tbxKeyDown.addEventListener('keydown', testKeyDown, false);
tbxKeyUp.addEventListener('keyup', testKeyUp, false);
tbxKeyPress.addEventListener('keypress', testKeyPress, false);
// Remove anything entered
function testKeyDown() {
tbxKeyDown.value = '';
}
function testKeyPress() {
tbxKeyPress.value = '';
}
function testKeyUp() {
tbxKeyUp.value = '';
}
KeyDown = <input type="text" id="tbxKeyDown" value="" />
<br/><br/>
KeyUp = <input type="text" id="tbxKeyUp" value="" />
<br/><br/>
KeyPress = <input type="text" id="tbxKeyPress" value="" />

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Categories

Resources