I have a showPreview option for an entered URL on my site just like Facebook shows a preview of the URL.
When the User enters the url, the following condition gets verified:
$('#text').keyup(function(e) {
allowPosting = true;
if ((e.which === 13 || e.which === 32 || e.which === 17) && trim($(this).val()) !== "")
}
Key code:
13 - Enter
45 - Insert
17 - control
Now the function is being called when the user copy and pastes the URL or Selects the URL from the preview and presses Enter key
What I want:
The preview should be shown if the user types in the URL, even if the user does not press the enter key or copy and pastes the URL.
What should I do?
Here is your code, this will do everything you wrote:
$('#text').keyup(function(e) {
allowPosting = true;
if (/(^|\s)((http:\/\/|https:\/\/)[a-zA-Z0-9!*'();:#&=+$,\/?#[\]\-_.~]+)/.test($("#text").val()) && trim($(this).val()) !== "")
{
// DO STUFF
}
});
It will also check if the input is a link or not, so that the user can enter "http://google.com/" and not e.g. "asdf"!
check the .val() after every keyup, not only on Enter, and if it is an URL, do the rest
Try change in place of keyup :
$('#text').change(function(){...});
Related
I am trying to stop cursor from deleting the word before it if the word before is "Hi Harry" in input type text . I am trying to restrict cursor from deleting text, if user started deleting text and
text before it matches "Hi Harry" before it then stop deleting this text. The user also should not override the "Hi Harry text" by selecting and typing another character. "Hi Harry" must not be deleted or replaced by user by any action.
Any solution that fulfills the requirement may help.
.html
<input id="target" type="text" value="Hi Harry">
js
$( "#target").keydown(function(e) {
if (e.which == 8 && e.target.value === "Hi Harry") {
// backspace or delete key
return false;
// here I want to stop cursor from deleting if user started deleting text and
//text before it if matches "Hi Harry" then stop deleting this text.
}
});
As you may know by now, to prevent the user from deleting with backspace or delete, you can preventDefault on the events for e.which == 8 or e.which == 46.
What if the user selects the text or clicks in between "Hi Harry?" You need to also handle some text selection events. See the snippet below[1]:
// monitor key down function
var initialValue = $("#target").val();
$("#target").keydown(function(e) {
if (e.target.selectionStart < initialValue.length) {
//prevent user from typing stuff in between "Hi Harry"
e.preventDefault();
return;
}
if ((e.which == 8 || e.which == 46) && e.target.value === initialValue) {
// backspace or delete key
// backspace is 8, delete is
e.preventDefault();
}
});
// monitor text selection and force to deselect
function handleSelections(e) {
e.preventDefault();
var endPoint = initialValue.length;
if (e.target.selectionEnd > initialValue.length + 1) {
endPoint = e.target.selectionEnd;
}
if (e.target.selectionStart < initialValue.length) {
e.target.setSelectionRange(initialValue.length, endPoint);
};
}
// prevent any selection of text until after "Hi Harry"
$("#target").get(0).addEventListener('select', handleSelections);
// prevent cursor positioning anywhere within "Hi Harry"
$("#target").get(0).addEventListener('click', handleSelections);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="target" type="text" value="Hi Harry">
[1] Tested on Google Chrome 78
You could just call the preventDefault method of the event argument that is passed to the callback function when these conditions are met :
BACKSPACE (e.which === 8) is being pressed.
the input's value is currently equals to Hi Harry.
a better approach is to store the initial value of input thus you'll be able to write anything as its initial value.
const inp = $("#target"), /** referening the input **/
initVal = inp.val(); /** store its initial value **/
/** keydown event handler **/
inp.on('keydown', e => {
e.which == 8 && inp.val() == initVal && e.preventDefault();
/**
* backspace and current value is the same as the initial value then just don't allow the backpace functionnality at this moment.
* if the conditions aren't met, simply the line won't work thus allow inputing.
**/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="target" type="text" value="Hi Harry">
I have a page wherein a user can click a button to post something. This works in a similar fashion as facebook.
When the user presses enter, the post will automatically be saved and displayed. When the user presses shift and enter, I was expecting a new line but it doesn't seem to work. I am using JQuery for that function. What could be wrong with this code ? I saw this solution while researching.
$("#someTextArea").keypress(function(event){
if(event.which == 13 && !event.shiftkey) {
// ajax
}
});
Try using event.keyCode and event.shiftKey(capital K [camel-case]);
For your task something like this should do:
var Keys = {
ENTER: 13
};
$("#someTextArea").keypress(function (event) {
if (event.keyCode == Keys.ENTER) {
if (event.shiftKey) {
// make a new line
} else {
//submit the text
}
}
});
I am new in Firefox OS. I have a search box.
After pressing the submit button it shows results perfectly. But I want to add keyboardevent like press enter button it will show result.
Try this:
$("#SearchText").keydown(function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
//stop CR & do submit here instead
document.forms["myform"].submit();
return false;
}
});
It intercepts every key press in the search text field and checks for Return.
Yesterday i wrote a question here but the way i did that request was kinda confusing.
Now I'll try it different.
I have a barcode handscanner which just scans the barcode and writes the input into an input field.
It's just the same as a guy who typs 10 digits and presses return in less then 5ms.
example : 2134463342 + return
Now i have a form which was set to autofocus on reload and i can get the input from the scanner.
I want to be able to do scans and passing them into a database without entering the input field.
example: User does something else like browsing the webpage than the user scans something without entering the input field.
I have copied some code from a site:
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function(){
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
// assign value to some input (or do whatever you want)
$("#barcode").val(barcode);
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
$("#barcode").keypress(function(e){
if ( e.which === 13 ) {
console.log("Prevent form submit.");
e.preventDefault();
}
});
The code works fine, my Question is:
Is it possible to do that operation without entering the input field/form?
thanks
#alexMmM
did you tried CSS to hide the inputbox??? style= display:none or style= visibility:hidden property ???
It hides your input box and gives a virtual feel that it has been done without entering into input fields...
I've got an order page on my site. Some order items can have decimal quantities, some can't.
What's the best way to prevent the user from entering decimal quantities? (Apart from an alert box and setting the field to zero)?
Intercept key events for the field, detect illegal characters upon input, keep them from getting entered in the field and add a temporary msg near the field (inserted into the page) that explains what characters or values are allowed. pop up alerts are a bad way to give feedback in the middle of typing.
Then, validate again before submission because there are other ways to get data into fields (drag/drop, copy/paste, etc...) that you might not have caught everything.
Here's a jQuery example of both an integer only and a decimal only field with temporary messages displayed when invalid keys are typed:
Working jsFiddle: http://jsfiddle.net/jfriend00/CkDTy/
$(".integer").keypress(function(e) {
if (e.which < 48 || e.which > 57) {
showAdvice(this, "Integer values only");
return(false);
}
});
$(".decimal").keypress(function(e) {
// 46 is a period
if (e.which != 46 && (e.which < 48 || e.which > 57)) {
showAdvice(this, "Decimal numbers only");
return(false);
}
if (e.which == 46 && this.value.indexOf(".") != -1) {
showAdvice(this, "Only one period allowed in decimal numbers");
return(false); // only one decimal allowed
}
});
function showAdvice(obj, msg) {
$("#singleAdvice").stop(true, false).remove();
$('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
$("#singleAdvice").delay(4000).fadeOut(1500);
}
Here's a little jQuery that prevents non-numerical inputs:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if(currValue.search(/[^0-9]/) != -1)
{
// Change this to something less obnoxious
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
});
});
You can add an event (on key press) and detect if a decimal point has been pressed by the user or not. Also on form submission, use regular expressions to check if the submitted data is correct (because the user can forge the data using live editor like firebug). Also make sure to double check that on your server side in case if user disabled javascript.
for example:
<input type="text" onkeypress="checkDecimal();" />
<input type="submit" onclick="checkBeforeSubmit();" />
function checkDecimal() {
// your code goes here
}
function checkBeforeSubmit() {
// your code goes here
}
You better to use the same function cause it's basically the same thing and invoke it from both events.
On server side, check the submitted data again