I'm using JTube found over here: JTube at github
I'm trying to make a request on keyup instead of on submit. This is the script:
var qsParm = new Array();
function qs() {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0) {
var key = parms[i].substring(0,pos);
var val = parms[i].substring(pos+1);
qsParm[key] = val;
}
}
}
$(function() {
qs();
if(qsParm['search'] == '' || qsParm['search'] == null || qsParm['search'] == undefined)
qsParm['search'] = 'splinter cell';
else
qsParm['search'] = unescape(qsParm['search']);
$('input[name=search]').val(qsParm['search']);
$.jTube({
request: 'search',
requestValue: qsParm['search'],
limit: 10,
page: 1,
success: function(videos) {
$(videos).each(function() {
$('#example').append('<li><img src="'+this.thumbnail+'"><br>'+this.title+' - '+this.length+'</li>');
});
},
error: function(error) {
$('#example').html(error);
}
});
});
As far as I understand the function is ''qs'' So therefore I tried:
$("input").onkeyup(function(){
qs();
return false;
});
Did not work. I tried many other things with no success. Help is appreciated.
Change it to:
$("input").keyup(function(){
qs();
return false;
});
jQuery version of onKeyup is called keyup. In general onXXX are the DOM events and jQuery handlers simply do not have on in them.
You need to call the "sendQS" function (which is anonymous in your example) to actually send the data. Also, the jquery function is keyup not onkeyup.
function sendQS() {
qs();
if(qsParm['search'] == '' || qsParm['search'] == null || qsParm['search'] == undefined)
qsParm['search'] = 'splinter cell';
else
...
}
$("input").keyup(function(e){
sendQS();
return false;
});
Try something like this:
$('#target').keyup(function() {
alert('Handler for .keyup() called.');
});
Related
I've got the following code
$(function(){
var isValid = function(test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-error');
return false;
}else{
element.removeClass('has-error');
return true;
}
};
$('#rta_parties_form').submit(function(event){
var formSubmit;
formSubmit = isValid($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit = isValid($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit = isValid($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit = isValid($('#rta_cl_mob'), $('#div_cl_mob'));
if(!formSubmit){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
});
});
As you can see I'm using formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn')); on four different occasions. My issue: let's say in first 3 instances, it returns false but on the fourth instance, it returns true, then it will submit the form successfully?
Is there any way to check if any of those instances return false or set all the instances to false so form should not be submitted?
I know I can use nested if statements, but then, what is the point of using a function? I wanted to avoid using multiple if statements in my code. That's why I wrote the function; otherwise, I could have just used the function code in my actual code and set formSubmit to false.
Any ideas?
You can use this, more maintainable
var tmp = [$('#div_cl_fn'), $('#div_cl_ln'), $('#div_cl_ph'), $('#div_cl_mob')];
var i = -1;
while (++i < tmp.length)
{
if (!isValidToggle($('#rta_cl_mob'), tmp[i]))
{
event.preventDefault();
break;
}
}
If you want to add something to check, just add an entry into the array
Or
for (var i in toCheck = [$('#div_cl_fn'),
$('#div_cl_ln'),
$('#div_cl_ph'),
$('#div_cl_mob')])
{
if (!isValidToggle($('#rta_cl_mob'), toCheck[i]))
{
event.preventDefault();
break;
}
}
You should use it like
formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit = formSubmit && isValidToggle($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit = formSubmit && isValidToggle($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit = formSubmit && isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'));
You can do the following
var formSubmit1, formSubmit2, formSubmit3, formSubmit4;
formSubmit1 = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit2 = isValidToggle($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit3 = isValidToggle($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit4 = isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'));
if(!formSubmit1 || !formSubmit2 || !formSubmit3 || !formSubmit4){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
Try this...
You can do it in single line...
formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn')) && isValidToggle($('#rta_cl_ln'), $('#div_cl_ln')) && isValidToggle($('#rta_cl_ph'), $('#div_cl_ph')) && isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'))
in this, it will check first one condition and if it is true then It will check further condition otherwise it will take you out.
All validation will be executed.
$(function(){
var formValid,
isValid = function(test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-error');
}else{
element.removeClass('has-error');
formValid = true;
}
};
$('#rta_parties_form').submit(function(event){
var formSubmit;
formValid = false;
isValidToggle($('#rta_cl_fn'), $('#div_cl_fn'));
isValidToggle($('#rta_cl_ln'), $('#div_cl_ln'));
isValidToggle($('#rta_cl_ph'), $('#div_cl_ph'));
isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'));
if(!formValid){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
});
});
Thank you very much everyone but I got what I wanted I'm putting this code here for if anyone else wants to get use of the code in future...
$(function(){
//below is one way using function
var isValid = function(test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-error');
return false;
}else{
element.removeClass('has-error');
return true;
}
};
$('#rta_parties_form').submit(function(event){
var formSubmit = [];
formSubmit[0] = isValid($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit[1] = isValid($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit[2] = isValid($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit[3] = isValid($('#rta_cl_mob'), $('#div_cl_mob'));
var validForm = true;
for (var i = 0; i < formSubmit.length; i++) {
if(formSubmit[i] == false){
validForm = false;
}
};
if(!validForm){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
});
});
This works fine for me, thanks to everyone one more time for your help..
I have a JS function that checks and restricts certain characters typed in input forms.
The code look like this:
var alphaOnly = /[sA-Za-z\söÖäÄüÜ]/g;
var alphaextraOnly = /[A-Za-z\-&/'"\öÖäÄüÜ]/g;
var alphadigitsOnly = /[sA-Za-z\söÖäÄüÜ\s1234567890]/g;
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var mailOnly = /[a-z\.#]/g;
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
It works when I add onkeypress to input like this:
<input type="text" class="span4 register_input" id="firma" name="firma" onkeypress="return restrictCharacters(this, event, alphaOnly);" />
But I want to do that with getElementById in the script. I tried to add this:
window.onload = function() {
document.getElementById("firma").onkeypress = restrictCharacters(this, event, alphaOnly);
}
But it didn't work... Help please.
You can't pass the arguments like that to onkeypress you would need to use a wrapper function
document.getElementById("firma").onkeypress = function (e)
{
return restrictCharacters(this,e,alphaOnly);
};
jsFiddle http://jsfiddle.net/BjU2e/5/
You are assigning to onkeypress the result of restrictCharacters(this,event,alphaOnly) instead of a function delegate. A correct version is in the following jsFiddle : http://jsfiddle.net/xL47r/1/
For future reference :
document.getElementById("firma2").onkeypress = function(e) {
return restrictCharacters(this,e,alphaOnly);
};
You can get this from e.target
document.getElementById("firma").onkeypress = function(e) {
restrictCharacters(e.target,e,alphaOnly);
}
document.getElementById("firma").onkeypress = function(){
return restrictCharacters.call(this/*becauseof 'this.blur()' */, this,event,alphaOnly);
};
You have wrong syntex to bind event with dom .here it is : window.onload = function () {
var ab = document.getElementById("firma");
ab.setAttribute("onkeypress", "restrictCharacters(this,event, true)");
}
I am trying to return false after a conditional statement fail.
I have
$('#btn').click(function() {
$('.title').each(function() {
if (id == $(this).attr('id')) {
alert('The name already exists.')
return false; //I hope my codes would stop here if condition is true
}
})
// my codes still call the doSomething function even if the conditional
//statement is true
doSomething();
})
I want do call the doSomething function ONLY if id != $(this).attr('id).
The codes below gave me what I want but it seems ugly.
$('#btn').click(function() {
var nameExist = false
$('.title').each(function() {
if (id == $(this).attr('id')) {
alert('The name already exists.')
nameExist = true;
return false; //I hope my codes would stop here if condition is true
}
})
if (!nameExist) {
doSomething();
}
})
Anyone has a better approach for this? Thanks a lot!
Switch to a basic for loop.
$('#btn').click(function() {
var elements = $(".title");
for (var i = 0; i < elements.length; i++) {
if (id == elements[i].id) {
alert('The name already exists.')
return false; //I hope my codes would stop here if condition is true
}
}
doSomething();
})
You don't need to iterate thrue the elements, you can get it by the id and class like, #myId.myClass.
$('#btn').click(function() {
if($('#' + id + '.title').length) {
alert('The name already exists.');
} else {
doSomething();
}
});
If you don't mind not exiting the loop early, you can use jQuery filter
$('#btn').click(function(){
var itensWithSameName = $('.title').filter(function(){
return id == $(this).attr('id');
})
if(itensWithSameName.size() > 0)
alert('The name already exists.');
});
I think what you have is fine, but this avoids the extra conditional:
var func = doSomething;
...
if (id == $(this).attr('id')) {
func = $.noop;
...
func();
Here it is:
//Disable KeyboardNavigation
document.getElementById("author").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("email").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("url").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("comment").onfocus = function() {
document.onkeyup = null;
};
//Enable KeyboardNavigation
document.getElementById("author").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("email").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("url").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("comment").onblur = function() {
document.onkeyup = KeyCheck;
};
I believe it's definitely possible to write a better code with a loop but I really don't know how to make it work. I tried the following:
var formfields= ["author", "email", "url", "comment"];
for (i=1; i<=3; i++){
//Don't really know what to put in here.
}
Thank you in advance for your help!
EDIT : Whole code is below. You should know that I got some help to get to this result:
document.onkeyup = KeyCheck;
var pages = [
"http://",
"http://",
"http://",
"http://",
"http://"];
function leftarrowpressed() {
location.href = pages[ Math.max(0, 0 - 1) ];
//The second '0' here changes from 0 to 4, according to the page.
}
function rightarrowpressed() {
location.href = pages[ Math.min(pages.length - 1, 0 + 1) ];
//The second '0' here changes from 0 to 4, according to the page.
}
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
// left arrow key
case 37:
leftarrowpressed();
break;
// right arrow key
case 39:
rightarrowpressed();
break;
}
}
Hope this can help a little more. By the way, thank you everyone. I really don't know which solution to choose.
It looks like what you are doing is trying to prevent keystrokes in an input element from affecting navigation. What you could do instead is check event.target in KeyCheck and only perform the action if it was not triggered by an input element.
function KeyCheck(e) {
var target = e ? e.target : event.srcElement, //standards vs IE
tagname = target.tagName.toLowerCase();
if( tagname !== "input" && tagname !== "textarea" && tagname !== "select") {
//Not from an input, NAVIGATE!
}
}
If using jQuery then you can go a more straight-forward way: inside KeyCheck, check whether any of the elements is focused, and don't do anything in that case. You won't need any of the above.
function KeyCheck(e) {
if($("#author, #email, #url, #comment").is(":focus")) {
return; // ignore if any of these elements has focus
}
// ...
}
Make sure to bind KeyCheck using jQuery too:
$("body").on("keyup", KeyCheck);
var formfields= ["author", "email", "url", "comment"];
for (i=0; i<=3; i++){
var field = document.getElementById(formFields[i]);
field.onfocus = function() {
document.onkeyup = null;
};
field.onblur = function() {
document.onkeyup = KeyCheck;
};
}
or more proper way would be to use something like this
jQuery.each("author email url comment".split(" "), function(i, name) {
$('#' + name).focus(function() {
// do whatever you want to do
}).blur(function() {
// do whatever you wnat to do
));
});
Neat and readable:
var formfields = ["author", "email", "url", "comment"],
i, elem,
blur = function() { document.onkeyup = KeyCheck; },
focus = function() { document.onkeyup = null; };
for (i=0; i<=3; i++) {
elem = document.getElementById(formFields[i]);
elem.onblur = blur;
elem.onfocus = focus;
}
look for the nearest common parent for these elements and add a handler to it. we can use the powers of delegation using the .on() as well as method chaining to bind a hander only to the parent (in this case, 2 handlers for all, not 8 where 2 per element) to take effect on all 4 elements.
var selectors = '#author, #email, #url, #comment';
$('nearest_parent_element').on('focus', selectors, function() {
document.onkeyup = null;
}).on('blur', selectors, function() {
document.onkeyup = KeyCheck;
});
jQuery way:
$("#author, #email, #url, #comment").on({
focus: function() {
$(document).on('keyup', null);
},
blur: function() {
$(document).on('keyup', KeyCheck);
}
});
It all depends on how good you are at JavaScript. I would recommend for you to use event delegation: http://jsfiddle.net/teresko/PkCuZ/3/
It might look a bit complicated , but the add_listener() function would be shared throughout the whole code , so the payload actually looks like this:
var handlers = {
keyout: function(e){
var event = e || window.event,
target = event.target || event.srcElement;
console.log( 'leaving ' + target.name );
},
keyin: function(e){
var event = e || window.event,
target = event.target || event.srcElement;
console.log( 'entering ' + target.name );
}
},
container = document.getElementById('container');
add_listener( container, 'blur' , handlers.keyout );
add_listener( container, 'focus' , handlers.keyin );
This would work with any number of form elements.
As for the add_listener() function , it contains a small fix for blur/focus on IE, and a per-application choice of which method of attaching events to use. It's kinda an universal function which you can just drop in, when you need a common interface for attaching listeners:
var add_listener = (function () {
var fix = {
'focus': 'focusin',
'blur': 'focusout'
};
if ( window.addEventListener ) {
return function ( element, type, callback ) {
element.addEventListener(type, callback, typeof(fix[type]) !== undefined );
};
}else{
return function ( element, type, callback ) {
type = fix[type] || type;
element.attachEvent('on' + type, callback);
};
}
})();
I am trying to use the typeWatch plugin for jQuery. I have this javascript:
<script type="text/javascript">
$(document).ready(function() {
var options = {
callback: function() { alert("a-ok! " + $(this).text); },
wait: 333,
highlight: true,
captureLength: 1
}
$("#customer").typeWatch(options);
});
</script>
And my view's HTML has this:
Method B: <%= Html.TextBox("customer") %>
With this test, if I type "ABC" in the textbox, I am expecting an alert to popup with "a-ok! ABC". Instead the following shows up...
a-ok! function (F) {
if (typeof F !== "object" && F != null) {
return this.empty().append((this[0] && this[0].ownerDocument ||
document).createTextNode(F));
}
var E = "";
o.each(F || this, function () {o.each(this.childNodes, function () {
if (this.nodeType != 8) {
E += this.nodeType != 1 ? this.nodeValue : o.fn.text([this]);}});});
return E;
}
I've tried changing the $(this).text to .val, and I've also tried referencing the input field more directly as $("#customer") but they yield similar results. How can I access just the entered text?
You should use the val() function on the textbox:
$(this).val();
Looking the code of typeWatch version 2.0 I found this:
function checkElement(timer, override) {
var elTxt = jQuery(timer.el).val(); <----------- !!! this...
// Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength
if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text)
|| (override && elTxt.length > options.captureLength)) {
timer.text = elTxt.toUpperCase();
timer.cb(elTxt); <-------------- !!! ...goes here.
}
};
timer.cb is the callback that you set up in the options. So you just add a parameter in that callback function that you use and that parameter will be the text from the input.