Hello I have try a lot but can't solve . can any one explain me how I'll drive a JavaScript event after write" in " . I mean i wanted to make a div display:none to display:block after write " in ". that's a auto suggestion issue i've attaching a image the pattern is like that [word] [in] [word].
That's will do onkeyup event.
JS version...
var myInput = document.getElementById('myInput');
var messageBox = document.getElementById('messageBox')
myInput.addEventListener("keyup", checkString);
function checkString() {
var str = myInput.value;
// notice whitespace either side of "in" to prevent false positives
if (str.indexOf(' in ') > -1) {
messageBox.style.display = "block";
} else {
messageBox.style.display = "none";
}
}
#messageBox {
display: none;
padding: 15px;
background: #f2f2f2;
border: 1px solid #e6e6e6;
margin-top: 15px;
}
<input id="myInput" placeholder="Type here">
<div id="messageBox">In was typed</div>
Use input event in jQuery
$('#some_text_box').on('input', function() {
var value = $(this).val();
// do your stuff
// split the value by space and check if it contains 'in'
});
Using jQuery keyup event you can get value which user type in text box while user typing. Then with the use of indexOf javascript method you can compare string with in word. if match found you can display div otherwise hide that div.
Make sure to use toLowerCase() to convert string enter by user in lower case to get perfect match with in word. if user enter in in uppercase it function works fine.
DEMO
What is indexOf() method ?
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.
$('#text').on('keyup', function() {
var value = $(this).val();
if(value.toLowerCase().indexOf(' in ') >= 0){
$('yourdiveselector').show()
}else{
$('yourdiveselector').hide()
}
});
Related
i'm new to js
so i have a simple html element that has contenteditable="true" which i'm using as an input box.
i want the innerhtml to change to "CAN'T BE EMPTY" when the user has typed nothing in the input box ( " " )
and apparently it doesn't work, any tips on how i can do it?
this is my code (which is not working):
HTML:
<p contenteditable="true" id="myparagraph">Input</p>
JS:
if(document.getElementById("myparagraph").innerHTML == ""){
document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}
i've also tried using the LENGTH property, but didn't work either:
var plength = document.getElementById("myparagraph").innerHTML;
var plength2 = plength.length;
if(plength2 == 0){
document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}
It's not empty. It's got a value of Input according to your HTML.
If you want to change the value when the user edits, you need to attach an event listener:
document.getElementById('myparagraph').addEventListener('input', (e) => {
if (e.target.textContent.trim() === '') {
e.target.textContent = 'Cannot be empty';
}
})
<p contenteditable="true" id="myparagraph">Input</p>
Note that I changed the logic from using innerHTML to using textContent because otherwise remaining empty HTML tags can prevent the warning from triggering. (Firefox, for example inserts a <br> when there is no content.)
It would be better to display the warning anywhere than the content of the element you're trying to check. Add an event listener to the paragraph element. In the handler get the textContent from the element, and then show/hide the warning depending on whether that text is empty.
const para = document.querySelector('#para');
const warning = document.querySelector('#warning');
para.addEventListener('input', handleInput, false);
function handleInput() {
const text = this.textContent;
warning.textContent = text ? '' : 'Cannot be empty';
}
#para { border: 1px solid #565656; padding: 0.5em; }
#warning { color: red; }
<p contenteditable="true" id="para">Input</p>
<p id="warning"></p>
I am trying to input strings in a contenteditable div and based on "#" in a string ,go for ajax call .
1) If '#' comes as first character as user input, go for ajax call.
2) If whitespace/tab comes before `'#', go for ajax call
3) If user inputs a string and places cursor manually in between of string and provide whitespace followed by '#' and then whitespace, go for ajax call.
.html
<div contenteditable="true" onkeyup="detectHash($event)"></div>
.js
function detectHash(event){
var input = event.target.innerText.trim();
// check above conditions (1),(2),(3), conditons true,
// go for ajax call
$().ajax({
success:function(){
}
}}
}
You can use a regex to pass these rules:
1) If '#' comes as first character as user input, go for ajax call.
2) If whitespace/tab comes before `'#', go for ajax call
(3 is the same as 2)
Rule 1: ^# ^ = start of line
Rule 2: \s# \s = any whitespace, including tab
Example snippet, these can be combined into a single regex, but left as separate for demonstration (as with noajax/goajax classes - for the snippet only)
$("div").on("input", detectHash);
function detectHash(event) {
var input = event.target.innerText.trim();
if (input.match(/^#/) || input.match(/\s#/))
{
$("#out").removeClass("noajax").addClass("goajax");
} else {
$("#out").removeClass("goajax").addClass("noajax");
}
}
div#inp { border:1px solid #ccc; height:200px; width:200px; }
div.noajax { background-color: red; height:5px; width:200px; }
div.goajax { background-color: green; height:5px; width:200px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='inp' contenteditable="true"></div>
<div id='out' class="noajax"></div>
Alternatively, you can use .indexof but might need an extra if you also need to check for tabs, whereas .match with \s handles this for you.
if (input.indexOf("#") === 0 || input.indexOf(" #") >= 0)
So I have this function:
function inputCheck()
{
var check = document.forms["drinkList"]["quant1"].value
if (isNaN(check))
{
window.alert("Input numbers only");
return false;
}
}
I am using this code to check if the user has entered a character into a textbox. If they did, then it will display an alert saying that it only accepts numbers.
Thing is, I have 11 more text boxes I have to run this function under.
Is there anyway I can get this to work, without recreating 11 more functions?
The other textbox names are:
quant2,
quant3,
quant4,
quant5,
whip,
cream,
sugar,
chocolate,
caramel2,
NOTE: I am also using onchange to make it a live check.
Sorry, didn't read clearly earlier. This should do, I guess.
<input onchange="inputCheck(this)">
function inputCheck(elem){
var check = elem.value;
if (isNaN(check))
{
window.alert("Input numbers only");
return false;
}
}
A more efficient way to hook an event to multiple inputs is to hook an event to a parent (like, say, <body>), and check the target of the events bubbling up:
var names = ['quant2', 'quant3', 'quant4', 'quant5', 'whip', 'cream', 'sugar', 'chocolate', 'caramel2'];
document.body.addEventListener('keyup', function (e) {
// skip event if it was NOT triggered on a matching element
if (names.indexOf(e.target.name) === -1) { return; }
// code to process event...
});
As asides:
Use <input type="number">. This is a facility provided by the browser, it will work immediately at input-time, among other niceties (like providing a number-only keypad on mobile devices instead of a full keyboard). Here's documentation and browser support for further reading.
I recommend checking the built-in feature input type=number
However, if you really want to check it for yourself you could do something like:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function numberOnly() {
var value = this.value;
if (!isNumber(value)) {
console.dir('not a number!'); // replace this with your ALERT
this.classList.add('error');
} else {
this.classList.remove('error');
}
}
var inputs = document.querySelectorAll('.number-only'); // selects all the inputs that have the class .number-only
[].forEach.call(inputs, function(input) {
input.addEventListener('keyup', numberOnly); // validate the input using the numberOnly onkeyup
});
input {
display: block;
margin: 5px;
border: 1px solid #aaa;
padding: 5px 10px;
}
input.error {
outline-color: #f00;
border: 1px solid #f00;
position: relative;
}
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
why don't use jquery,it can select all textbox if add same class, example:nonNumberTextbox.
$("#drinkList .nonNumberTextbox").each(function(index, node) {
if (isNaN(node.value)) {
window.alert("Input numbers only");
return false;
}
});
In your code isNaN(check) will always return false. This is because the .value property of an input element always returns a string and isNaN of a string is false.
You need to coerce check to a number before passing it to isNaN. I would suggest using the unary operator +. You also need to make sure that check is not empty or an all white-space string because the unary plus will those will coerced them to 0.
if (check.trim() === '' || isNaN(+check)) {
Alternatively depending on your needs you could use parseInt or parseFloat which will return NaN when parsing an empty or all white-space string.
if (isNaN(parseInt(check, 10))) { // if only integers are allowed
}
if (isNaN(parseFloat(check))) { // if integers and decimals are allowed
}
Yet another alternative would be to use a regular expression to validate the string without coercion.
if(!/^\d+$/.test(check)) { // if the number needs to be an integer
}
if(!/^\d+(?:\.\d*)?$/.test(check)) { // if the number can be an integer or a decimal
}
Try if this works
var textboxes = ['quant2', 'quant3', 'quant4', 'quant5', 'whip', 'cream', 'sugar', 'chocolate', 'caramel2'];
for (var i = 0; i < textboxes.length; i++ ){
var check = document.forms["drinkList"][textboxes[i]].value;
if (isNaN(check)){
window.alert("Input numbers only");
break;
}
}
What I'm going after is a code that will gather all my text input fields and detect whether or not they have any input. If so I'd like for there to be a glow effect added, if they're left empty or they delete the data and leave it empty I'd like for the glow effect to turn off.
So far from everything I've found this is what I came up with so far, it doesn't work of course, but it's the best I could try to rationalize.
function glow(){
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
if (text.value ==null){
text.style.boxShadow="#8fd7d2 0px 0px 22px";
}
else
remove.style.boxShadow;
}/**function**/
I used the .getElementsByClassName because the getElementsById didn't support multiple IDs as it seems, but if there's another more efficient way of gathering them all please share.
Simple solution can be adding class having glow with javascript:
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
text[0].className = text[0].className + " glow";
DEMO
Note: If you want to add glow class to each input then you have to iterate through loop and add class to each element. Because text is
HTMLCollection of elements.
You need to get the value of each element, not of the HTMLCollection returned by document.getElementsByClassName; Array.prototype.forEach can help with this. Then, a value can’t be null, but empty.
Edit: Wait a minute… you want the glow effect if the element has an input, right? Then your if-else statement is the wrong way around.
This is the correct function:
function glow() {
"use strict";
Array.prototype.slice.call(document.getElementsByClassName("tex_inp01 tex_inp02")).forEach(function(a) {
if (a.value !== "") {
a.style.boxShadow = "0px 0px 22px #8fd7d2";
}
else {
a.style.boxShadow = "";
}
});
}
You have a couple of mistakes in your existing code (as presented in the question): (1) text.value ==null - do not check against null, because an inputs value will never be a null. Check its length. (2) remove.style.boxShadow; - I think that was a typo. It should have been text.style.boxShadow = 'none'.
..to be a glow effect added, if they're left empty or they delete the
data and leave it empty I'd like for the glow effect to turn off..
You can check if the input has been left empty by simply checking the length of the value. However, to check if the input has been entered and then deleted you will have to keep a flag to keep track of that. You can do that by hooking up the change event on inputs and then setting a flag via data attribute. Later when you are checking each input for applying a style, along with the length also check this attribute to see if the input was edited out.
Here is a simple example putting together all of the above (explanation in code comments):
var inputs = document.getElementsByClassName("a b"), // returns a collection of nodelist
button = document.getElementById("btn"); // just for the demo
button.addEventListener("click", checkInputs); // handle click event on button
[].forEach.call(inputs, function(elem) { // iterate over all selected inputs
elem.addEventListener("change", function() { // handle change event
this.setAttribute("data-dirty", true); // set a data attribute to track..
}); // .. a flag when it is changed
});
function checkInputs() {
[].forEach.call(inputs, function(elem) { // iterate over selected inputs
var isDirty = elem.getAttribute("data-dirty"); // check the dirty flag we set
if ((elem.value.length > 0) || (isDirty)) { // if empty or changed
elem.style.boxShadow = "none"; // reset the style
} else {
elem.style.boxShadow = "#f00 0px 0px 5px"; // else apply shadow
}
});
}
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<button id="btn">Check</button>
If you wanted to validate the inputs while the user is typing, you can use keyboard events to check the value of the input(s):
document.querySelector('input[type="text"]').addEventListener('keyup',
function(event){
var element = event.target;
if (element.value.trim() === '') {
element.classList.add('empty');
} else {
element.classList.remove('empty');
}
});
See fiddle for example: http://jsfiddle.net/LrpddL0q/.
Otherwise this could be implemented the same way without the addEventListener to perform as a one-off function.
Jquery can help you as the following
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$(".MyInput").bind('keypress', function () {
$('.MyInput').css("boxShadow", "#8fd7d2 0px 0px 22px");
});
$(".MyInput").bind('keydown', function () {
if ($(".MyInput").val() == "") {
$('.MyInput').css("boxShadow", "none");
}
});
});
</script>
HTML:
<input type="text" value="" class="MyInput" />
this code working only online If you need to download Jquery library visit this
https://jquery.com/download/
I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm
First, create a simple Div Layout with some text in the divs and search bar above it.
<div class="search_bar">
<form><!--The Field from which to gather data-->
<input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
</form>
</div>
<!--Containers With Text-->
<div class="container">
<div class="container_of_hc">
<div class="horizontal_containers">Cat</div>
<div class="color">Black</div>
<div class="color">White</div>
<div class="color">Orange</div>
</div>
<div class="horizontal_containers">Dog</div>
<div class="horizontal_containers">Rat</div>
<div class="horizontal_containers">Zebra</div>
<div class="horizontal_containers">Wolf</div>
</div>
CSS:
.container {
width: 100%;
}
.horizontal_containers {
height:10%;
border: solid 3px #B30015;
font-size: 45px;
text-align: center;
}
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
var str = $("#searchfield").val(); //get current value of id=searchfield
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
if (str.length == 0) {
//if searchfield is empty, show all
$(".horizontal_containers").show();
}
Last, we do the actual hiding of the divs if the length of str is not 0:
else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$("div:contains('" + str + "').horizontal_containers").show();
$("div:not(:contains('" + str + "')).horizontal_containers").hide();
}
});
The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
$(".container .color").show();
} else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$(".container div:contains('" + str + "').color").show();
$(".container div:not(:contains('" + str + "')).color").hide();
}
Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.
Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
for adding a :contains_nocase() selector with jQuery 1.8