How to validate answer by enter key? - javascript

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>

Related

Preventing global jQuery event on single form item

When my JS code loads I call the following which adds a onkeypress event to all text inputs:
$('#myForm input[type=text]').keypress(function(event) {
sysOnEnter(event, $('#myForm input[type=text]').attr('id'), modalId);
});
The function sysOnEnter is to click a button when the user presses the Enter/Return key:
function sysOnEnter(event, id, modalId) {
var key = event.key || event.keyCode;
if (key == 'Enter' || key == 13) {
var val = $('#' + id).val();
setTimeout(function() {
if ($('#' + id).val() == val)
document.querySelector('#' + modalId + ' .btn-primary').click();
},0);
event.preventDefault();
return false;
}
}
The time that I don't want this to happen is when using Google's auto-suggest address form:
<input
id = "autocomplete"
class = "form-control"
placeholder = "Start typing..."
onFocus = "initAutocomplete();geolocate();"
type = "text"
>
Is there an easy way to exclude this particular field from the javascript function?
Use the selector :not(#autocomplete) to exclude the element with the autocomplete id:
$('#myForm input[type=text]:not(#autocomplete)').keypress(function(event) {
console.log('firing event');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text">
<input type="text">
<input type="text" id="autocomplete" placeholder="autocomplete">
<input type="text">
</form>
If the field you want to exclude is known beforehand you can use JQuery .not():
$('#myForm input[type=text]').not("#autocomplete").keypress(function(event) {

$.getJSON() call throwing error

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

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" />

How to not go to next form field on TAB

Trying to search online and can only find how to change field selection..
My question today is the opposite
Is it possible to not go to the next field on tab button press, if yes how can we do that.
Thanks!
$('#blockThisFieldID').keydown(function(objEvent) {
if (objEvent.keyCode == 9) { //tab pressed
objEvent.preventDefault(); // stops its action
return false;
}
})
$("#testform").on('keydown', 'input', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
}
});
<div id="testform">
<input type=text id=test1><br />
<input type=text id=test2><br />
<input type=text id=test3><br />
</div>
As seen in this fiddle
Can you change the tabIndex?
http://www.w3schools.com/tags/att_global_tabindex.asp

Validation on a cloned form

I have a form which is cloned using jquery. Because it is cloned, the validation does not work properly.
I have managed to get it give an alert when the field is not filled in, but it still submits the form after the alert message is cleared.
Any ideas?
Code below...
$(document).ready(function(){
$("ul > li > a").click(function() {
$popupCopy = $("." + $(this).attr("href")).html();
$popupAddClass = $(this).attr("href");
$popupWidth = parseFloat($("." + $(this).attr("href")).attr("title")) + 80;
$("<div class='popupContainer'><div class='popupContent " + $popupAddClass + "'>" + $popupCopy + "</div><img src='images/close.png' class='closePopup'></div>").appendTo("body");
$(".popupContainer").fadeIn(500);
return false;
});
$(".giftName").live("focus", function() {
if ( $(this).val()=="Name") {
$(this).val('');
};
});
$(".giftName").live("blur", function() {
if ( $(this).val()=="") {
$(this).val('Name');
};
});
$('.giftSubmit').live('click', function(){
if( ! checkvalid() ) {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
});
});
function checkvalid(){
var valid = true;
$('.giftName').each(function(){
if (this.value == '' || this.value == 'Name' || this.value == null) {
valid = false;
return;
}
})
return valid;
}
body:
<div class="pageContainer">
<div class="bodyPanel">
<ul>
<li>Gift list</li>
</ul>
</div>
</div>
<div class="popupsHidden">
<div class="giftlist">
<form action="sendGift.php" class="giftForm" method="post">
<input name="giftName" class="giftName" type="text" value="Name" />
<input name="" class="giftSubmit" type="submit" value="Send your promised gift..." />
</form>
</div>
</div>
Instead of listening for the click event on the submit button, try listing for the submit event on the form itself:
$('.giftForm').live('submit', function() {
if ( ! checkValid() ) {
alert('not valid !');
return false;
}
});
In your $('.giftSubmit').live('click' ... function, you need to add return false; after showing your validation failure message. This will stop the event from propagating.
Because the click event is not being stopped, the form is being submitted, despite the validation failure.

Categories

Resources