$.getJSON() call throwing error - javascript

I can't figure out why .getJSON is throwing an error when the call to the parent function is made via a conditional statement. When the if statement is commented out, there does not seem to be an issue and .getJSON gets called. However, I want the user to complete their input (indicated by pressing enter).
The HTML
<div class="text-center searchBar">
<form action="">
<input type="text" id="searchText" />
</form>
</div>
<div class="container displayResults"> </div>
The Javascript:
$(document).ready(function() {
$('#searchText').keyup(function(e) {
var searchItem = $('#searchText').val();
var link = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&exlimit=max&inprop=url&generator=search&gsroffset=&format=json&formatversion=2&callback=?&gsrsearch=' + searchItem;
if(e.which == 13) { //if user returns enter key
wikiCall(link);
}
});
});
function wikiCall(wikiLink) {
$.getJSON(wikiLink, function(searchResults) {
for (var i = 0; i < searchResults.query.pages.length; i++) {
$(".displayResults").append("<div class='searchResultsContainer'><span style='font-weight:bold; font-size:150%; margin-bottom:100px;'>" + searchResults.query.pages[i].title + "</span><br></br>" + searchResults.query.pages[i].extract + "</div>");
$(".displayResults").append("<br>");
}
}).fail(function(jqxhr,textStatus,error){
alert(textStatus+": "+error);
});
}

I tested your software and I get only one mistake: keyup instead of keypress plus stop propagation.
In the following your code:
function wikiCall(wikiLink) {
$.getJSON(wikiLink, function(searchResults) {
for (var i = 0; i < searchResults.query.pages.length; i++) {
$(".displayResults").append("<div class='searchResultsContainer'><span style='font-weight:bold; font-size:150%; margin-bottom:100px;'>" + searchResults.query.pages[i].title + "</span><br></br>" + searchResults.query.pages[i].extract + "</div>");
$(".displayResults").append("<br>");
}
}).fail(function(jqxhr,textStatus,error){
alert(textStatus+": "+error);
});
}
$(function () {
$('#searchText').keypress(function(e) {
var searchItem = $('#searchText').val();
var link = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&exlimit=max&inprop=url&generator=search&gsroffset=&format=json&formatversion=2&callback=?&gsrsearch=' + searchItem;
if(e.which == 13) { //if user returns enter key
wikiCall(link);
e.preventDefault();
}
});
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<div class="text-center searchBar">
<form action="">
<input type="text" id="searchText" />
</form>
</div>
<div class="container displayResults"> </div>
The sequence of events when you type a character is:
keydown , keypress, keyup .
For the first two events you have the possibility to prevent, while you cannot prevent the character typed on keyup event.
The keyup event is the last event for which you listen and you can only say: ok, this is the character I take an action but I cannot prevent the effect of this charcter, like form submitting.
When you type new line the results of the three events are:
keydown keyCode=13 which=13 charCode=0
keypress keyCode=13 which=13 charCode=13
keyup keyCode=13 which=13 charCode=0

Related

Using ENTER key to replace button click?

<body>
<form>
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
I have a very simple HTML file with minimal javascript included. When I click the button, it works perfectly. But when I hit the ENTER on the keyboard to simulate the button click, it will also run through the code, but then an error happens at the end.
On Firefox and Chrome, it'll return an error "Not Found". On w3schools, it'll return "The file you asked for does not exist". And on stackoverflow, it'll just disappear.
What am I missing? Where is the error? What's the trick to making the ENTER key act just like the mouse click?
HTML form has onsubmit attribute on them. onsubmit handles the enter functionality. You have to set the type="submit" on the button, also you need to set the onsubmit on form passing the event to your function so that you can prevent the default action of the form ( that is to send the request to backend ) by doing e.preventDefault.
<body>
<form onsubmit="calc(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="submit">read</button>
</form>
<br>
<label id = "calculated"></label>
<script>
function calc(e) {
// Will stop the form from sending the request to backend
e.preventDefault()
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
If you want to just prevent ENTER from doing anything including running the code....
The following code (yours with a couple more lines... will prevent Enter from doing anything:
<body>
<form onsubmit="return mySubmitFunction(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
return false;
//document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function mySubmitFunction(e) {
e.preventDefault();
return false;
}
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
Why was this happening? since the form element itself has a submit and the enter key is a key pressed which also does a form submit.... so you need to prevent the form from submitting... mySubmitFunction() <- this prevents the form from submitting ... and a change to your keyup event listener - if you do not want enter to even create the click you change this:
event.preventDefault();
document.getElementById("btn").click();
to this :
event.preventDefault();
return false;
//document.getElementById("btn").click();
As I have already did in the code example. or leave it like you had(the event listener keyup) and the Enter key will only act as a click.

Automatic keypress on page load

I have an input area where a value has been preset. I would like to make it so that on page-load the "enter" button is pressed on the keyboard to submit the value.
Here is the code:
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
}
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
A solution where I would not need to press enter and the value is submitted is also welcome!
I guess code below would work.
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
console.log('triggered')
player_name = $(this).val();
logged = 1;
}
})
const event = new Event('keypress')
event.which = 13
document.querySelector('#login-input').dispatchEvent(event)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
The doc
If you want it to run after page loaded, use onload event. The solution may look like this:
<script>
function f() {
// Test it:
// alert("Hello, page loaded!");
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="f()">
If you do want user to have a glimpse on your pre-filled login form and inform about what is happening, you may make a delay with setTimeout function, which will fire in 0.5 sec after onload event happened.
<script>
function f() {
$('#some_element').text('Signing you in...');
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="setTimeout(f, 500)">
Or you can call the event handler with a faked keypress like this:
function kpress(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
console.log(player_name,logged);
}
}
kpress.call($('#login-input').keypress(kpress),{which:13});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
I use the output from the jQuery event binding as the object context for the Function.prototype.call() method and add a "simplified" event object as {which:13}.

Do a function if specific word is submitted in textbox

how would I get a textbox perform a function if a specific word is submitted. I have a robot that jumps on mousedown and I want it to jump if I write jump or write move in the textbox it does the move function. I tried few things but couldnt get it to work
Heres the code
<form id="formDiv" action="" >
Command the robot!: <input type="text" size="50" onkeydown="keyCode(event)">
</form>
<div id="canvasDiv" width="500" height="10"></div>
<script type="text/javascript" src="robotti.js"></script>
<script type="text/javascript">
prepareCanvas(document.getElementById("canvasDiv"), 500, 500);
document.getElementById("canvasDiv").onmousedown = function() {
jump(); }
//document.getElementById("canvasDiv").onkeypress = function() {
//move(); }
document.getElementById("canvasDiv").window.onkeypress = function(event) {
if (event.keyCode == 41) {
move();
}
}
</script>
This should work -:
var text = getElementById("canvasDiv").value;
if(text.includes("move") || text.includes("jump")){
jump();
getElementById("canvasDiv").value = "";
}
Please use onkeyup instead of onkeydown
<!DOCTYPE html>
<html>
<body>
<input type="text" id="canvasDiv" onkeyup="keyCode()" value="">
<script>
function keyCode(e) {
var text = (document.getElementById("canvasDiv").value).toLowerCase();
if(text == 'jump' || text == 'move'){
//call jump function here
alert("jump");
}
}
</script>
</body>
</html>
You shouldn't use HTML attributes like onkeydown etc. Use an EventListener instead. Register one on your input field, grab its value and check (either via switch or if...else) what the user entered. According to the user's input, execute your functions.
document.querySelector('input[type="text"]').addEventListener('keyup', function() {
switch (this.value) {
case 'move':
console.log('move!'); // Your actual function here
this.value = ''; // Reset value
break;
case 'jump':
console.log('jump!'); // Your actual function here
this.value = '' // Reset value
break;
}
});
Command the robot!: <input type="text" size="50">
Further reading:
Why is inline event handler attributes a bad idea in modern semantic HTML?
document.querySelector

How to validate answer by enter key?

I have created an input box, which gets validated by using the tab key, but it needs to be validated after pressing the enter key.
Here, the tick mark symbol is displayed only after I type the correct answer and then press tab. Then it goes to the next input box and also validation occurs.
But the validation needs to occur when I type the correct answer and hit the enter inside the input box itself.
For that I tried this JS code:
$(document).keypress(function(e) {
if(e.which == 13) {
checktxt(h,v,w,c)
}
});
function checktxt(h,v,w,c) {
var th=$("#"+h).val();
var tv=$("#"+v).val();
if(th.toLowerCase()==tv.toLowerCase()) {
$( "."+c ).show();
$( "."+w ).hide();
} else if(tv.toLowerCase()=="") {
} else {
$( "."+c ).hide();
$( "."+w ).show();
}
}
But also it does not get validated when I press the enter key.
And my HTML code is
<div>
<input id="texthidden1" type="hidden" value="877" />
<input id="textvisible1" type="text" value="" onblur="javascript:checktxt('texthidden1','textvisible1','wrong1','correct1');" />
<div class="wrong1"><img src="../images/smallwrong.png"/></div>
<div class="correct1"><img src="../images/smallgreen.png"/></div>
</div>
I also need the tick image to be disappeared when i erase the content of the input box.
The problem with you code is this part in your keypress listner
checktxt(h,v,w,c)
h,v,w and c are undefined here, since the code for onblur events working fine and you want to replicate the same on enter press, you need to defined these variable in you keypress event.
If you check your html , you are passing the ids of all elements to to checktxt function in your JS.
Do the same inside keypress listener as well.
$(document).keypress(function(e) {
if(e.which == 13) {
checktxt('texthidden1','textvisible1','wrong1','correct1')
}
});
$(document).keypress(function(e) {
if (e.which == 13) {
checktxt('texthidden1', 'textvisible1', 'wrong1', 'correct1')
}
});
function checktxt(h, v, w, c) {
var th = $("#" + h).val();
var tv = $("#" + v).val();
if (th.toLowerCase() == tv.toLowerCase()) {
$("." + c).show();
$("." + w).hide();
} else if (tv.toLowerCase() == "") {} else {
$("." + c).hide();
$("." + w).show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="texthidden1" type="hidden" value="877" />
<input id="textvisible1" type="text" value="" onblur="javascript:checktxt('texthidden1','textvisible1','wrong1','correct1');" />
<div class="wrong1">
<img src="../images/smallwrong.png" />
</div>
<div class="correct1">
<img src="../images/smallgreen.png" />
</div>
</div>

Javascript/jQuery : Detect both return key press and submit button press simultaneously

I have an input field and an "add" button below it. What the add button basically does is, it appends a new input field to the document. What I am trying to do here is, while typing in an input field if return key press is detected the function that calls the addition of new input field is fired the same function that is fired when the add button is clicked.
Can I incorporate the detection of return key press in the following somehow?
$('.addNewSite').on('click', function(){
var idNewInput = "site" + numInputFields;
$('.inputFieldsSettingsPanel').append('<input type="text" class="tracksiteInput" id = "' + idNewInput + '"></input>');
$("#" + idNewInput).focus();
});
I think you want this http://jsfiddle.net/naeemshaikh27/cy84t4pz/
function fun(){
$('body').append('<input type="text"/>');
}
$('.addButton').on('click', fun);
$('body').on('keypress','input', function(e){
if (e.keyCode == 13) {
fun();
}
});
something like this? e.which in the keypress() is what you're looking for to see what button is pressed. in this case, 13 is equivalent to the enter key
$(document).ready(function() {
$('.add').on('click', function() {
var html = '<input type="text" class="field" /><br/><br/>';
$('.form').append(html);
});
$(document).on("keypress", ".field", function(e) {
if(e.which == 13) {
$('.add').trigger('click');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="add" href="#">add</a><br/><br/>
<div class="form">
<input type="text" class="field" /><br/><br/>
<input type="text" class="field" /><br/><br/>
</div>
You cant detect enter keypress on the input and trigger the button's click event.
$("button").on("click", function(e){
$("body").append($("<input>").attr("type", "text"));
});
$(document).on("keypress", "input", function(e){
if(e.which == 13) $("button").trigger("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Input</button>
var i;
var inputs=document.getElementsByClassName('add');
for(i=0;i<inputs.length;i++){
inputs[i].addEventListener('keyup',function(event){
if(event.keyCode){if (event.keyCode=="13" ){createNewElem();
}}
//if(event.which){if(event.which =="13"){alert('return pressed');}}
});
}
function createNewElem(){
var newinput=document.createElement('input');
var inptype=document.createAttribute('type');
inptype.value="text";
newinput.setAttributeNode(inptype);
var inpclass=document.createAttribute('class');
inpclass.value="add";
newinput.setAttributeNode(inpclass);
document.body.appendChild(newinput);
}
<input type="text" class="add" />

Categories

Resources