search with jquery - javascript

I do a search by the js for my site.
Their code it might look like:
have a form and when the keyup event, it will send post to a file and retrieve data from that file into the html of a div crazy.
but this yourself in trouble. I find the example for "a" is about 3000 results. for example, take a second to send post. so I press "c" will now send the post to the file is "ac" and there are 100 such results takes 0.3 seconds.
eg time I press the letter "a" to "c" 0.2 seconds, it should show results "ac" at 0.5 seconds. then 0.5 seconds later it is the result of "a". ~> Find "ac" into finding "a"
So how do you now when you press "c" then it stopped send post with the value "a" that send post with value "ac".
<form method="post" onsubmit="return checkForm(this.form)">
<div class="search padding">
<input type="text" id="searchbox" name="manga_name" class="input" value="Tìm truyện muốn đọc ..." onfocus="if (value =='Tìm truyện muốn đọc ...'){value =''}" onblur="if (value ==''){value='Tìm truyện muốn đọc ...'}" />
<input type="submit" value=" " id="searchsubmit" class="go"/>
</div>
</form>
<div id="result"></div>
And the script:
<script>
$('#searchbox').keyup(function() {
search();
});
function search() {
var keyword = $('#searchbox').val();
if (keyword != "") {
$('#result').html(loadingText);
$('#result').css('display', 'block');
$.post('/search/',{"keyword":keyword}, function(data){
if (data != "")
{
$('#result').html(data);
}
else
{
$('#result').html('');
$('#result').css('display', 'none');
}
});
}
else {
$('#result').html('');
$('#result').css('display', 'none');
}
}
</script>

// use to delay the callback execution
// so your search will be executed only you stop typing after 0.5(500 ms for example) second
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout(timer);
timer = setTimeout(function() {
callback();
}, ms);
}
}());
$('#searchbox').keyup(delay(search, 500));

You may try;
var timer = null;
$("#text_box").keyup(function() {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(search, 1000);
});
There is a similar question here that I asked before. Always do a search in stackoverflow before posting a question.

Related

how to read multiple value length in javascript?

I am working on a barcode scanner and currently have a problem where I need the barcode to read 2 different value lengths, currently I have it set to submit the value at 9 length.
<span>
<input type="text" id="IC-input" name="IC" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
now i need it to read from 12 value as well but it auto submits when the value hits 9 digits. I have tried OR function .
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 12 || value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
i also tried the Else function
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 12){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
else if(value.length == 9){
theButtonIsPressed(value);
}
}
But it would always read the first 9 value and leave the 3 other value unread. Does anyone have a solution for this? Thank you in advance.
Seems like you are listening to the keypress. Use a timer to cancel it. Basic idea of a debounce method.
var timer;
function autofill(value){
if (timer) window.clearTimeout(timer);
if(value.length === 9){
timer = window.setTimeout( function () {
processIt(value);
}, 50);
} else if(value.length === 12){
processIt(value);
}
}
function processIt(value){
console.log('here', value);
}
BUT That is a bad solution. Typically you set up the scanner to fire a tab or enter press so you know it is done. I would check to see if that is happening and listen for that instead. You can then just listen for that and you know the scanner is done.
var inp = document.getElementById("barcode");
inp.addEventListener("keydown", function (evt) {
if (["Tab", "Enter"].includes(evt.key)) {
evt.preventDefault();
console.log('scanner is done', evt.target.value);
}
});
<input type="text" id="barcode" />
The problem is that the autofill function runs to press the button as soon as the input box has 9 characters. It is because you are running the autofill function by the 'onkeyup' event listener attached to the input tag.
The solution is to run the autofill function after making sure there is a full length value intended. Good luck.
For a most common scene, the scanner will trigger such event one by one: focus, input character....input final 'Enter' character, so you have to take attention to the last event.
<script type="text/javascript">
window.addEventListener("load", function () {
var ic = document.getElementById("IC-input");
ic.addEventListener("focus", function (args) {
ic.value = "";
});
ic.addEventListener("keyup", function (args) {
if (args.key == "Enter") {
autofill(ic.value);
}
});
});
function autofill(value) {
console.log("Autofill:" + value)
//console.log(9 digits);
button = document.getElementById("theButton");
if (value.length == 9) {
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
</script>
<span>
<input type="text" id="IC-input" name="IC" onkeyup="input_keyup" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>

Instant validation with optional function for number calculation with instant result

I want to show the error instantly until the request is filled right. It means that I want the user to get the number he is typing instantly without clicking the button...
Here is my code (also found on JSFiddle):
HTML:
<input type="number" id="myNumber" value="Error">
<button onclick="myFunction()">Click</button>
<p id="Error"></p>
JS:
window.myFunction = function() {
var err = " is not 1000!"
var num = document.getElementById("myNumber").value;
if (num == 1000) {
alert("No Errors!");
} else {
if (num !='') {
document.getElementById("Error").innerHTML = num+err;
}
else {
document.getElementById("Error").innerHTML = err;
}
}
}
I'm looking for a simple solution to use a function inside until the number is calculated, so to just show the "is not 1000" while typing something other than 1000 (like 1, 100, 1001 110011 etc..) can also be fine..
$("#myNumber").on("input",myFunction);
Dont wait for a click, but for an input. The upper is in jquery, pure js:
document
.getElementById("myNumber")
.addEventListener("input",myFunction);
or inline:
oninput="myFunction()"
you can call myFunction() on keyup event for your input box.
window.myFunction = function() {
var err = " is not 1000!"
var num = document.getElementById("myNumber").value;
if (num == 1000) {
alert("No Errors!");
document.getElementById("Error").innerHTML = "";
} else {
if (num !='') {
document.getElementById("Error").innerHTML = num+err;
}
else {
document.getElementById("Error").innerHTML = err;
}
}
}
<input type="number" id="myNumber" onkeyup="myFunction()" value="Error">
<button onclick="myFunction()">Click</button>
<p id="Error"></p>

Case not working on second input?

I am trying to create a text based game that takes information inputted in the browser and translates it into an action and runs it. I am able to get it to work for the first answer but after it displays the outcome of the first answer it doesn't seem to load the second. Also once you submit anything all the cases show up and are appended to the screen without any input. Any idea how to fix this issue or make sure the case keeps repeating?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Lord of the Deahsticks</title>
<link href="css/text-game.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="info">
<h1 class="title">Lord of the Deathsticks</h1>
</div>
<div class="gameboard">
<div class="event">
<p>Hello this is the game!</p>
</div>
<div class="event">
<p>You are awoken by a sound...You need to get up already, you're going to be late for you shift at the slave factory!</p>
</div>
</div>
<form>
<input type="text" id="action" name="what to do">
<input type="submit" name="button">
</form>
<script src="js/controllers/controller.js"></script>
<script src="js/model/characters.js"></script>
<script src="js/JQuery/jquery-3.1.0.js"></script>
<script src="js/JQuery/text-game-JQuery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</body>
</html>
Main js/jquery
var template = function(action){
return '<div class="event"><p>'+ action +'</p></div>'
};
var display = function(input){
if(input !== "") {
var html = template(input);
$(html).appendTo('.gameboard');
} else {
alert("You need to imput an appropriate answer");
}
$('#action').val("");
$('#mydiv').scrollTop(($('#mydiv').height()*2));
};
var main = function(){
$('form').submit(function(){
event.preventDefault();
var action = $('#action').val();
var input = action.toLowerCase();
display(action);
interact(input);
return false;
});
};
$(document).ready(main);
Controller:
var where = "intro";
var wait = function(){
};
var interact = function(input) {
switch(where) {
case "intro":
if (input === "stay in bed") {
display("you sleep for 2 more hours");
where = "police";
} else if (input === "wake up") {
display("You wake up and head to the slave factory");
where = "on route";
} else {
display("You need to submit a valid response");
}
break;
case "police":
display("You are awaken by three slave police standing at your bed!");
wait();
display("Our records show this is you third offence citizen #000986642, you will now be sent for disciplinary reconditioning. Prepare to be detained.")
wait();
display("what will you do? -Go with them? -Fight them? -Try to Escape");
if (input === "go with them") {
display("You are escorted to the deathcamp");
where = "deathcamp1";
} else if (input === "fight them") {
display("You jump out of bed and prepare for a fistfight");
where = "fistfight";
} else if (input === "try to escape") {
display("you attempt to jump through your window");
where = "window1";
} else {
display("You need to submit a valid response");
}
break;
}
};
You have the right idea and your code works. It's just you might need to rethink some of your logic and maybe add some more error handling (if needed).
I've updated your code:
var interact = function(input) {
switch(where) {
case "intro":
if (input === "stay in bed") {
setTimeout( function() { display("you sleep for 2 more hours"); }, 1000);
setTimeout( function() { display("You are awaken by three slave police standing at your bed!"); }, 3000);
setTimeout( function() { display("Our records show this is you third offence citizen #000986642, you will now be sent for disciplinary reconditioning. Prepare to be detained."); }, 5000);
setTimeout( function() { display("what will you do? -Go with them? -Fight them? -Try to Escape"); }, 7000);
where = "police";
} else if (input === "wake up") {
display("You wake up and head to the slave factory");
where = "on route";
} else {
display("You need to submit a valid response" + where);
}
break;
case "police":
if (input === "go with them") {
display("You are escorted to the deathcamp");
where = "deathcamp1";
} else if (input === "fight them") {
display("You jump out of bed and prepare for a fistfight");
where = "fistfight";
} else if (input === "try to escape") {
display("you attempt to jump through your window");
where = "window1";
} else {
display("You need to submit a valid response");
}
break;
}
};
You want to have the output in the stay in bed command, that way it will only happen once. Then you use the next case to present the next output or error message if necessary. Good luck on your story!
Also you'll find .setTimeout(function, milliseconds) useful for your waiting logic. I've included it in the answer as well ;)
Working sample.

setInterval on IE10

The setInterval function does not work on I.E. 10. I have a web page that when a form is submitted, it will trigger a long process on the server for downloading a file. I use setInterval to repeatly poll the server for progress so that the user gets some kind of update on the progress.
The ProgressServlet will only get called once only. I did not test this on another web browser because it is "illegal" to use another browser in my company.
<script>
var myVar;
function validateForm()
{
//validation logic omitted
myVar = setInterval(getProgress(), 1000);
return true;
}
function getProgress() {
//ProgressServelt will return progress of the long process on the server
$.get("ProgressServlet", $.now(), function(res) {
if (res != "9999" || res == "No value avaliable") {
$("#progress").html(res);
} else {
$("#progress").html("Stopped: " + res);
clearInterval(myVar);
}
});
}
</script>
<form method="post" action="CreateServlet" name = "create">
Change Number(s):<br>
<input type="text" name="change" id="change">
<p></p>
<input type="submit" value="Download" onClick="return validateForm()">
</form>
<p></p>
<button id="send" name="send">Display</button>
Change
myVar = setInterval(getProgress(), 1000);
to
myVar = setInterval(getProgress, 1000);
That is: pass the function, not what it returns.

Not Getting HTML TextBox Value in Javascript function? Have searched, but didn't find convincing answer

I'm a beginner trying to get the HTML from a textbox to be used in an if/else statement.
This is my HTML code:
<label id="label1">
Enter any Number:
</label>
<input type="button" id="Button1" value="button" />
<input type="text" id="TextBox1" name="myname" />
And my JavaScript code is:
<script type="text/javascript">
//<![CDATA[
var buttonElement = document.getElementById("Button1");
var txt_value =document.getElementById("TextBox1").value;
buttonElement.addEventListener('click', function() { Clicked(txt_value) }, false);
function Clicked(txt_value) {
if (txt_value == 7) {
alert("You are 7");
}
else { alert("You are not 7"); }
}
//]]>
</script>
I observed that
var txt_value =document.getElementById("TextBox1");
and then
buttonElement.addEventListener('click', function() { Clicked(txt_value.value) }, false);
The above example works absolutely fine.
Can someone please tell me what is wrong with:
var txt_value =document.getElementById("TextBox1").value;
I don't know why I'm getting an empty txt_value
The reason is that you are getting the value in txt_value before the user enters anything; hence the value is always empty.
IF you change your code to this:
var txt_value =document.getElementById("TextBox1");//removed .value
And the function Clicked to:
function Clicked(txt_value) {
if (txt_value.value == 7) { //added .value
alert("You are 7");
}
else { alert("You are not 7"); }
}
Should work.
Here's a jsfiddle
Move the getting of the value into the click handler...
var textbox1 = document.getElementById("TextBox1");
document.getElementById("Button1").onclick = function () {
var txt_value = textbox1.value;
if (parseInt(txt_value, 10) === 7) {
alert("You are 7");
} else {
alert("You are not 7");
}
};
Now you get the value that is in the textbox when the page loads.
Here is a JSFiddle to test this.
Update Improved the efficiency by caching the textbox. Removed the addEventListener to an onclick (more browser support)

Categories