Removing on keyup from jQuery search script - javascript

I have a jQuery search script which uses the on keyup function to submit the query. How can I make it search when the user presses enter?
Here is my current code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&page=1';
window.location.hash='search/'+query+'/1/';
document.title=$(this).val()+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});

#search_form must be id of <form> !
$(document).ready(function(){
$("#search_form").submit(function(){
var search=$("#search").val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&page=1';
window.location.hash='search/'+query+'/1/';
document.title=search+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});

I have found that I need to do this, have 2 events, one that caters for the enter key and one that ignores the keypress:
jQuery('#search').keydown(function (e) {
if (e.which == 13) {
// Do you work here
}
});
jQuery('#search').keypress(function (e) {
if (e.which == 13) {
return false;
}
});

In general case
$(document).keyup(function( e ) {
if (e.keyCode == 13) {
// execute your code
}
});

Related

Can't type on input box when using e.preventDefault();

I'm trying to call a Ajax for search functionality on my website when user press enter (using keyboard) on html input box. To prevent page loading after pressing enter I'm using e.preventDefault(); in ajax call but then I can't type of input box. It's working fine but can't type on input box. Can you tell me what I'm doing wrong ?
$(document).keypress(function(e) {
e.preventDefault();
var value = $('#txt_name').val();
if(e.which == 13) {
$.ajax({
type:"POST",
url:"doSearchEnter.php",
data:{
'key' : value
},
success:function(res){
$('#showSearchResult').html(res);
}
});
}
});
You can't type into the input because you're suppressing the default behaviour for all keystrokes!
You should only prevent it for the enter key:
$(document).keypress(function(e) {
var value = $('#txt_name').val();
if(e.which == 13) {
e.preventDefault(); // Moved this into here.
$.ajax({ ...
}
});
Move youe e.preventDefault(); inside the condition like:
$(document).keypress(function(e) {
var value = $('#txt_name').val();
if(e.which == 13) {
e.preventDefault();
$.ajax({
type:"post",
url:"doSearchEnter.php",
data:{
'key' : value
},
success:function(res){
$('#showSearchResult').html(res);
}
});
}
});

Using jquery to prevent form from submitting does not work after the first preventDefault

I use the below script to get some data from a database through the response of check.php and then check the data and if all is good i want to submit a form , else prevent it. #order_number is the field i am checking (input of type text) and #seblod_form is the form.
If i dont trigger the second e.preventDefault everything works fine and the form submits ok.When i trigger the second e.preventDefault the form does not submit, it gets a class of busy in the html and even if okToSubmit = true the form does not submit. Any ideas how can i fix this?
<script src="https://code.jquery.com/jquery-2.1.1.min.js">
$(document).ready(function(){
$( document ).on('keydown',function( e ) {
if (e.keyCode == 13){
e.preventDefault(); //prevent form submitting when user presses enter key
return false;
}
});
$( document ).on('keyup','#order_number',function( e ) {
if (e.keyCode != 13){
var value = $('#order_number').val();
var okToSubmit = true;
$.ajax({
type: "POST",
url: 'check.php',
data: {order_number:value},
dataType: 'json',
success: function(data) {
if (data['found'] != 'true' || data['ordernumberused'] == 'true'){
if (data['ordernumberused'] == 'true') {
$('#cck1r_form_order_number').append( $( "<div id='message' style='color:red;'>This order number is already used!!!</div>" ) );
okToSubmit = false;
}
else{
$('#message').remove();
}
$('#order_number').css("border-color", "red");
}
else {
$('#order_number').css("border-color", "green");
okToSubmit = true;
alert(okToSubmit);
}
$('#seblod_form').submit(function(e){
if (!okToSubmit){
e.preventDefault();
return false;
}
else {
return true;
}
});
}//end success
});//end ajax
}
});
});
</script>
This is the updated version of the code:
<script src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> /*hack for invoices - receipts*/
<script>
$(document).ready(function() {
var okToSubmit = true;
$('#seblod_form').submit(function(e) {
if (!okToSubmit) {
e.preventDefault();
return false;
} else {
return true;
}
});
$('input#submit').mousedown(function() {
if(okToSubmit){
$('#seblod_form').removeClass('busy');
}
});
$('input#submit').mouseup(function() {
if(okToSubmit){
$('#seblod_form').submit();
}
});
$(document).on('keydown', function(e) {
if (e.keyCode == 13) {
e.preventDefault(); //prevent form submitting when user presses enter key
return false;
}
});
$(document).on('keyup', '#order_number', function(e) {
if (e.keyCode != 13) {
var value = $('#order_number').val();
$.ajax({
type: "POST",
url: 'http://eshop.wideservices.gr/check.php',
data: {
order_number: value
},
dataType: 'json',
success: function (data) {
if (data['found'] != 'true' || data['ordernumberused'] == 'true') {
if (data['ordernumberused'] == 'true') {
if (!$('div').is('#message')){
$('#cck1r_form_order_number').append($("<div id='message' style='color:red;'>This order number is already used!!!</div>"));
}
okToSubmit = false;
} else {
$('#message').remove();
}
$('#order_number').css("border-color", "red");
} else {
$('#order_number').css("border-color", "green");
okToSubmit = true;
}
} //end success
}); //end ajax
}
});});
</script>
The removeClass seems to do the trick.
You are trying to attach to the submit event every single time you type a key. That is obviously a bad idea as each time you connect it will use it's own function-scoped value of okToSubmit which will will result in true and false calls at the same. Any false in any instance will cause it to preventdefault().
Try declaring okToSubmit at a higher level and hook up the submit event only once.
e.g.
$(document).ready(function () {
var okToSubmit = true;
$('#seblod_form').submit(function (e) {
if (!okToSubmit) {
e.preventDefault();
return false;
} else {
return true;
}
});
$(document).on('keydown', function (e) {
if (e.keyCode == 13) {
e.preventDefault(); //prevent form submitting when user presses enter key
return false;
}
});
$(document).on('keyup', '#order_number', function (e) {
if (e.keyCode != 13) {
var value = $('#order_number').val();
okToSubmit = true;
$.ajax({
type: "POST",
url: 'check.php',
data: {
order_number: value
},
dataType: 'json',
success: function (data) {
if (data['found'] != 'true' || data['ordernumberused'] == 'true') {
if (data['ordernumberused'] == 'true') {
$('#cck1r_form_order_number').append($("<div id='message' style='color:red;'>This order number is already used!!!</div>"));
okToSubmit = false;
} else {
$('#message').remove();
}
$('#order_number').css("border-color", "red");
} else {
$('#order_number').css("border-color", "green");
okToSubmit = true;
alert(okToSubmit);
}
} //end success
}); //end ajax
}
});
});
The other issue:
You are including your jQuery code inside an external JavaScript file request. In a word DON'T!. You should not mix external JS requests and inline script blocks as that will not work on all browsers (and looks really bad) :)
e.g.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"/>
<script type="text/javascript">
...your inline script code here...
</script>

JQuery blur and enter key - blur not working

I'm using the following for inline editing.
I want ajax to fire when enter key pressed or user clicks away (blur)
When enter key is pressed all is ok but AJAX not firing on blur?
// inline editing
$(document).on('blur keypress', 'span[contenteditable=true]', function (e) {
if (e.type == 'blur' || e.keyCode == '13') {
$.ajax({
type:'POST',
url:'/ajax/actions/editGenre.php',
data:{
content: $(this).text(),
id: $(this).attr('rowId')
},
success:function(msg){
$('span[contenteditable=true]').removeClass('inlineEdit').addClass('editAble');
}
});
e.preventDefault();
}
});
Fixed: JSFiddleWiddleBiddleBoDiddle (commented out your AJAX for the fiddle and used an alert to demonstrate)
$(document).on('focusout keypress', 'span.inlineEdit', function (e) {
e.preventDefault();
if (e.type == 'focusout' || e.keyCode == '13') {
$.ajax({
type: 'POST',
url: '/ajax/actions/editGenre.php',
data: {
content: $(this).text(),
id: $(this).attr('rowId')
},
success: function (msg) {
$('span.inlineEdit').removeClass('inlineEdit').addClass('editAble');
}
});
}
});
Blur event does not fire for span tags. Use something else which is meant to receive focus.

Key event for ajax call does not work

I am making an application where, when the user presses Enter, it should make an ajax call.
I used a plugin to browse the items and created jQuery code for the "click" (worked perfectly).
The problem is that when I make it so that pressing Enter calls the ajax code, there is some kind of conflict and it does not work.
Does anyone have any solution or another method?
thanks.
javascript
var main = function () {
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Frss.cnn.com%2Fservices%2Fpodcasting%2Fac360%2Frss.xml'%20AND%20itemPath%3D%22%2F%2Fchannel%22&format=json&diagnostics=true&callback=?";
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
// titulos
var titles = json.query.results.channel.item.map(function (item) {
return item.title;
});
// urls
var urls = json.query.results.channel.item.map(function (item) {
return item.origLink;
});
$(".container-list-podcast ul").append('<li>' + titles.join('</li><li>'));
$(".container-list-podcast ul li").each(function (key, value) {
var text = $(this).text();
$(this).html('<a class="link-podcast" href="' + urls[key] + '">' + text + '</a>');
});
// Load KeyNavigation
a = $('.nav_holder li a').keynav(function () {
return window.keyNavigationDisabled;
});
},
error: function (e) {
console.log(e.message);
}
});
}(jQuery);
///
$(document).ready(function () {
// Call Ajax Click <-- work
$('.container-list-podcast').on('click', '.link-podcast', function (e) {
e.preventDefault();
$('.video').attr('src', this.href);
});
// Call Ajax Key Enter <-- dont work
$('.container-list-podcast').on('keypress', '.selected', function (e) {
e.preventDefault();
if (e.which == 13) { // keyCode 13 == Enter key
$('.video').attr('src', this.href);
}
});
});
jsfiddle
$('body').on('keydown', function (e) {
e.preventDefault();
if (e.which == 13) { // keyCode 13 == Enter key
$('.selected').trigger('click', function() {
$('.video').attr('src', this.href);
});
}
});
You can try binding a keydown event to body or document it will full fill your purpose.
Actually the keypress event will not be triggered by an a element unless it has a focus. It would be more garantee to bind this event to the document.
Change your function to that:
// Call Ajax Key Enter
$(document).on('keypress', function (e) {
if (e.which == 13) { // keyCode 13 == Enter key
$('.video').attr('src', $('.container-list-podcast .selected').prop('href'));
}
e.preventDefault();
});
JSFiddle Example

My Return false is not working in this code..using jquery

$(function () {
$('#form4').submit(function () {
var val = $("#txtNewServiceTypeCategory").val();
$("#ServiceTypeCategoryName").children("option").each(function () {
var $this = $(this);
if (val == $this.val()) {
alert("ServiceTypeCategory Name is already added! Please Choose Differnt Category Name");
return false;
}
});
$('#someHiddenDiv2').show();
$('#STSave').attr('disabled', 'disabled');
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#someHiddenDiv2').hide();
alert('Saved NewServiceTypeCategory Successfully. Thank you!');
},
error: function () {
alert('Error occured! Plese try again later!.');
$('#someHiddenDiv2').hide();
$('#STSave').removeAttr('disabled');
}
});
return false;
});
});
This return false is not working in the above code even if its showing the popup message other things are executing here,
$("#ServiceTypeCategoryName").children("option").each(function () {
var $this = $(this);
if (val == $this.val()) {
alert("ServiceTypeCategory Name is already added! Please Choose Differnt Category Name");
return false;
}
});
What I am doign wrong in this?
Thanks
the return false; in the each loop only breaks the loop, it doesn't return from your submit function, so the rest of your submit function will keep running.
You could set a variable in the loop as to whether to continue the submit and after the loop you could then check whether you need to submit or not.
var exitSubmit = false;
$("#ServiceTypeCategoryName").children("option").each(function () {
var $this = $(this);
if (val == $this.val()) {
exitSubmit = true;
return false;
}
});
if (exitSubmit) {
alert("ServiceTypeCategory Name is already added! Please Choose Differnt Category Name");
return false;
}
You're only exiting the function that starts on line #1 (in your second code block) which will then cause the next line executed to be where you show your hidden div.

Categories

Resources