I have input-box. I'm looking for a way to fire-up alert() if first character of given string is equal to '/'...
var scream = $( '#screameria input' ).val();
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
It's my code at the moment. It doesn't work and I think that it's because that browser doesn't know when to check that string... I need that alert whenever user inputs '/' as first character.
Try this out:
$( '#screameria input' ).keyup(function(){ //when a user types in input box
var scream = this.value;
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
})
Fiddle: http://jsfiddle.net/maniator/FewgY/
You need to add a keypress (or similar) handler to tell the browser to run your function whenever a key is pressed on that input field:
var input = $('#screameria input');
input.keypress(function() {
var val = this.value;
if (val && val.charAt(0) == '/') {
alert('Boom!');
}
});
Related
I'm working a simple field where only accepts numbers, what I want is to add ".00" at the end of the value while I'm typing. ex. 1000.00.
the problem I cant achieve that format, after 1 digit it adds '.00' and cant type anymore.
I tried the answer here but didn't work.
here is my sample work
$(document).ready(function(){
$("input").keyup(function(){
var val = parseInt($(this).val());
$(this).val(val.toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Hope you can help me.
Thanks.
Use blur function like this:
$("input").blur(function(){
var val = parseInt($(this).val());
if(val){
$(this).val(val.toFixed(2));
}else{
$(this).val(0);
$(this).focus();
}
});
If what you want to do is type 1 and immediately get 1.00, then type 2 and you will get 12.00, then you need to save cursor position (like described here).
So you want to get current cursor position
format the input data
update input element
restore cursor position in needed place (depending on where it should be moved)
Try this:
$( 'input' ).on( 'input', function() {
var val = $( this ).val(),
arr = val.split( '.' );
if ( arr.length > 1 )
$( this ).val( arr[ 0 ] + val.substr( val.length - 1 ) + '.00' )
else
$( this ).val( val + '.00' )
} ).on( 'keypress', function( e ) {
return e.charCode == 46 || ( e.charCode >= 48 && e.charCode <= 57 )
} )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
i think you should try focusout event..
$(document).ready(function(){
$("input").focusout(function(){
var val = parseInt($(this).val());
$(this).val(val.toFixed(2));
});
});
I have this code for autocomplete in an HTML input :
$("#myinput")
.bind("keydown", function(event) {
// don't navigate away from the field on tab when selecting an item
if (event.keyCode === $.ui.keyCode.TAB
&& $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
var results = [],
selectionStart = this.element[0].selectionStart
term = extractLast(request.term.substring(0, selectionStart));
if (term.length > 0) {
console.log(term);
if(/*input has string "where"*/)
results = $.ui.autocomplete.filter(table1, term);
else
results = $.ui.autocomplete.filter(table2, term);
}
response(results);
},
focus: function() {
return false; // prevent value inserted on focus
},
select: function(event, ui) {
var terms = split(this.value.substring(0, this.selectionStart));
terms.pop(); // remove the current input
terms.push(ui.item.value); // add the selected item
this.value =
$.trim(terms.join(" ") + this.value.substring(this.selectionStart)) + " ";
return false;
}
});
What I'm trying to do is if the input has string "where" in somewhere, then it will load autocomplete from table1, otherwise it will load from table2. How can I check if the input has that string? Thanks in advance.
You should use includes method.
var inputValue=$("#myinput").val();
if(inputValue.toLowerCase().includes("where")){
//rest of code
}
Another method is using indexOf method.
if(inputValue.indexOf("where")!==-1){
//rest of code
}
If you want to do this achievment using regex, you can use search method.
if(inputValue.search(/where/i)!==-1){
//rest of code
}
inputValue="awherea";
console.log(inputValue.search(/where/))
If you want the strongest browser support, use String#indexOf
if(this.value.indexOf('where') > -1) {
//doSomething
}
you can get your text value and use indexof to find it .
my_inp = $("#myinput").val();
if (my_inp.indexOf('where') > -1) {
console.log('yes');
}
Try with string#match method use the ternary operator for return true or false
And also Some of the More method
string.indexOf()
string.includes()
console.log('hello everyone'.match("hello") ? true : false)
For jquery you could use the contains() method
console.log($('p').is(':contains("hi")'))
console.log($('p').is(':contains("22")')) // not contains
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>hello hi</p>
I'm using jQuery tagit with Autocomplete. I would like it so that when the user hits enter it will create a tag out of what's been entered if they don't select any of the autocomplete suggestions. If they do key down and select one of the options I would like it to use that value to create the tag instead.
The problem I'm having is when the Enter button is hit it overrides the Select function in autocomplete causing it to create a tag out of what's been typed, not what's been selected.
Here are the snippets from the slightly modified tagit widget
// Autocomplete.
if (this.options.availableTags || this.options.tagSource) {
this._tagInput.autocomplete({
source: this.options.tagSource,
focus: function(event, ui) {
//$(this).val(ui.item.label);
return false;
},
select: function(event, ui) {
// Delete the last tag if we autocomplete something despite the input being empty
// This happens because the input's blur event causes the tag to be created when
// the user clicks an autocomplete item.
// The only artifact of this is that while the user holds down the mouse button
// on the selected autocomplete item, a tag is shown with the pre-autocompleted text,
// and is changed to the autocompleted text upon mouseup.
if (that._tagInput.val() === '') {
that.removeTag(that._lastTag(), false);
}
that.createTag(ui.item.label,'',ui.item.value);
// Preventing the tag input to be updated with the chosen value.
return false;
}
}).data("autocomplete")._renderItem = function( ul, item ) {
var job ="";
if (item.job) job = item.job;
var row = "<a><span class='searchnamedisplay'>" + item.label + " </span><span class='searchjobdisplay'>"+job+"</span><span class='searchnamedisplay' style='width:120px;font-style:italic;color:#A19D9D;'>" + item.specialty + "</span><img src='/images/profile/"+item.value+".jpg' alt='person' width='25' height='25' border='0' style='padding-left:8px;padding-top:2px;' onerror='this.style.display=\"none\"' /><div style='clear:both'/></a>";
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( row )
.appendTo( ul );
};
}
// Events.
this._tagInput
.keydown(function(event) {
// Backspace is not detected within a keypress, so it must use keydown.
if (event.which == $.ui.keyCode.BACKSPACE && that._tagInput.val() === '') {
var tag = that._lastTag();
if (!that.options.removeConfirmation || tag.hasClass('remove')) {
// When backspace is pressed, the last tag is deleted.
that.removeTag(tag);
} else if (that.options.removeConfirmation) {
tag.addClass('remove ui-state-highlight');
}
} else if (that.options.removeConfirmation) {
that._lastTag().removeClass('remove ui-state-highlight');
}
// Comma/Space/Enter are all valid delimiters for new tags,
// except when there is an open quote or if setting allowSpaces = true.
// Tab will also create a tag, unless the tag input is empty, in which case it isn't caught.
if (
event.which == $.ui.keyCode.COMMA ||
event.which == $.ui.keyCode.ENTER ||
(
event.which == $.ui.keyCode.TAB &&
that._tagInput.val() !== ''
) ||
(
event.which == $.ui.keyCode.SPACE &&
that.options.allowSpaces !== true &&
(
$.trim(that._tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"' ||
(
$.trim(that._tagInput.val()).charAt(0) == '"' &&
$.trim(that._tagInput.val()).charAt($.trim(that._tagInput.val()).length - 1) == '"' &&
$.trim(that._tagInput.val()).length - 1 !== 0
)
)
)
) {
event.preventDefault();
that.createTag(that._cleanedInput());
// The autocomplete doesn't close automatically when TAB is pressed.
// So let's ensure that it closes.
that._tagInput.autocomplete('close');
}
}
I have input boxes and textareas that need to be toggled between left-alignment and right-alignment (depending on the user's language, the direction would be different). How can I do this with jQuery?
As I don't know the key code for all Persian letters, I had to do it like this:
var str = $('#item').val(); //this is your text box
var firstChar = str.substr(0,1);
var characters = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
function checkPersian() {
var result = false;
for (i = 0 ; i<32 ; i++) {
if (characters[i] == firstChar) {
result = true;
}
}
return result;
}
if (checkPersian()) {
$('#item').css('direction','rtl');
} else {
$('#item').css('direction','ltr');
}
Here I have completely overhauled Mohammad's script but it's limited to its purpose: scanning if the first letter the user types in is Persian and changing the inputs direction according.
Here it is: jsfiddle.net/uPH7N/4
You can use dir="auto" attribute in modern browsers: Live Demo
<input type="text" dir="auto"><br>
Also you can do it by jQuery like this: Live Demo
$('input, textarea').keyup(function() {
$(this).val().charAt(0).charCodeAt(0) < 200 ? $(this).css('direction','ltr') : $(this).css('direction','rtl');
});
Toggle the elements' css with jquery (assuming the relevant inputs/textareas all have the class textdirectionBoxes):
$('.textdirectionBoxes').css('direction', 'rtl');
and
$('.textdirectionBoxes').css('direction', 'ltr');
What about
jQuery( document ).ready( function(){
var language = navigator.userLanguage || navigator.language;
if( jQuery.inArray( language, ['ar', 'he', 'ur'] ) != -1 )
jQuery( 'input[type="text"], input[type="password"], textarea' ).css( 'direction', 'rtl' );
});
?
edit: fixed little code-bug
function isUnicode(str) {
return (str.charCodeAt(str.length-1) > 255) ? true : false;
}
$('input[type=text]').each(function() {
$(this).keyup(function(e) {
$(this).css('direction',
isUnicode($(this).val()) ? 'rtl' : 'ltr'
);
});
});
In firefox, I made a web page, there are two input text elements: input_text_1 and input_text_2. They behave like password verification: If the content of them is different, i.e. when onblur event of input_text_2 is activated, the onblur's handler will alert something and then select all text of input_text_1.
Actually, this is not easy to be implemented, as I think the events chain is not assured: Maybe, input_text_1 got text selected and then lost focus by some clicking. So, I just hack in the onblur's handler of input_text_1 as follows:
setTimeout("document.getElementById('input_text_1').select()", 100);
Is there a more elegant solution?
following code works fine in FireFox/IE/Opera/Safari/Chrome, but WebKit-based browsers not always take focus into input:
var blurHandler = function() {
var input1 = document.getElementById('input1');
if( this.value !== input1.value ) {
alert( 'Passwords are not equal' );
if( input1.selectionStart ) {
input1.selectionStart = 0;
input1.selectionEnd = input1.value.length;
}
input1.focus();
if( input1.select ) input1.select();
}
};
var input2 = document.getElementById('input2');
if( input2.addEventListener )
input2.addEventListener( 'blur', blurHandler, true );
else
input2.attachEvent( 'onblur', blurHandler );
you can try it http://jsfiddle.net/twilightfeel/3ggP6/3/