Dynamic JavaScript to allow character input after limited with preventDefault - javascript

I have a dynamic JavaScript rules engine in which based on criteria such as a dropdown is not changed, then I prevent any characters from being entered with:
$(document).on('keypress',"[id^="+condtionID+"]", function(event){
event.preventDefault();
});
However, if I change the dropdown to a value which does allow for any character, the textbox refuses to then allow for input.
Examples of IDs:
Select: ID="selectNumber435"
Input: ID="condtionID435"
Every row dynamically created into the table ends with the same random number created.
Problem is that once I do not allow any input, I tried:
return true; did not work
Even another condition in which I only allow numeric, I change to a dropdown value that allows for all input and it "holds on to" thinking it should ONLY allow numeric.
I would prefer to not have to make the user delete the dynamically created row, there has to be a way to allow for typing characters into the input box again. Some sort of "Reset" ...

You can simply dettach the attached event:
$(document).off('keypress',"[id^="+condtionID+"]");

Related

How to restrict from entering a decimal value in input type number?

So I want to have an input of type number <input type="number"> and I want to RESTRICT users from ENTERING DECIMAL VALUE
Note: I'm hiding the spin buttons of the input type text. Know more here
EDIT: ANYTHING WILL WORK! EVEN JAVASCRIPT!
I searched a lot but found nothing.
I did find this answer but it basically blocks the use of any other key on the keypad except the number keys, so the basic problems occur such as the user cannot use backspace and cut the number entered, another problem is the user cannot use tab to change focus onto the next input.
Thank You!
Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...
document.querySelector('input').addEventListener('input', e => {
e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>
But you really should not do it! For at least the following reasons:
Forbidding user input is, by and large, perceived as disrespectful and drives users away. In short, it reduces any user engagement metric you can think of (funneling, sales, visits, sharing, etc...). Don't take my word for it. Do some A/B testing: present the same form with and without blocking user input and look at the results.
Form elements are just tools to help users give you data. But they are completely by-pass-able. If you give me a form I can send whatever I want using it, by simply opening the browser console. The validation must be done on server side. If you're using the value to do something on client side, sanitize the input value in the method, without changing user input.
A respectful way to inform users decimal values are not valid is by making the input :invalid, using the pattern attribute ( e.g: pattern="[0-9]"), styling accordingly (e.g: :invalid { border-color: red }), and displaying an appropriate message.
Don't delete or block user input. They'll do it themselves if you tell them why the value is invalid.
When following web standards, your solution lasts. When you come up with hacks, there will always be the odd device in which your hack doesn't work. You don't know where things will be in 1-2 years from now, nevermind 5 or 10.
Last, but not least, have a closer look at Constraint Validation. You'll need to know and use it when creating quality UX and accessible forms.
This is one option for creating an input element using javascript to limit the values that can be entered. I create an array of allowed keys, including all the digits, backspace, and tab as you specified. I added an event listener for the keydown event, and if the key pressed is not in the allowed group, I prevent the default action, or prevent the value from being entered.
I also added an event listener to the paste event, as you could right click paste and enter information that does not meet the criteria. Instead of trying to validate pasted values I disable pasting all together.
If you have any questions, please ask.
const allowedKeys = [..."0123456789", "Backspace", "Tab"];
const myInput = document.querySelector("input");
myInput.addEventListener("keydown", e => {
const key = e.key;
const allowed = allowedKeys.includes(key);
if (!allowed) e.preventDefault();
});
myInput.addEventListener("paste", e => e.preventDefault());
<input type="number">

Filling Input fields having credit card formatting using js

I was wondering if there is a way to fill the input fields having type text and have inbuilt js event to evaluate what is being entered means, when a user types in any number it evaluates and checks the type of card and also put automatic spaces in between. But while setting the value with javascript i.e. element.value = 'xxxxxxxx'; the formatting doesn't happen and the site evaluates the card number invalid. so how to programmatically achieve this. I am working on an extension which could auto fill card details.
I have tried using element.dispatchEvent(Keyboardevent) but it won't work.
the website on which i am trying is made on top of angular.
I have found a workaround. It was something like changing the value and then dispatching an event. Since I was working with angular I needed to dispatch input event. Related codes are:
element.value = 'anything';
//dispatching input event after setting value ( tested for angular)
element.dispatchEvent(new Event('input')) ;

Simulate a button on the keyboard being pressed, add the value of that keypress to text input

My objective is to be able to run a function that simulates a key being pressed on the keyboard, and then the value of that key being inserted into an input field. My reasoning for this is that I am using a js framework that automatically filters data based off of the input but it only filters the data when the input is typed in. Using document.getElementById('search_box').value will obviously populate the input with text. But doing this doesn't trigger the data to be filtered because the input text technically isn't typed in. So I was wondering if it was possible to run a function that would basically simulate keys being pressed and then inserting the value of those keys into an input field.
function populateField() {
document.getElementById('search_box').value = "mr"; //this needs to be changed to insert the value via keyboard
document.getElementById('search_box').focus();
}
According to filter.js's main repo's Issues #154: Can I trigger a filter programatically with jquery like $("#filterid").val("bla").change() ?
$("#filterid").trigger('change') will work. It also depend upon events: change, click etc
i.e
$('#searchbox').val("father").trigger('keyup')
In the example page , I used $('#searchbox').val("father").trigger('keyup') to add "father" to search and trigger a filter effect.

jQuery check if input field characters are highlighted

Background
I have a page that has 3 input elements which takes currency numbers
These input element of type number with jQuery handles which letting up to 2 decimal placing. If user tries to input 3rd decimal, it does not print which is great.
However...
Issue
When input already has valid 2d.p input such as 12.11 and wishes to highlight the field characters (such as click drag highlight to blue) to change/overwrite all, the jQuery handler think that its 3rd decimal input and does not print BUT what it actually needs to do is to overwrite the whole and start from the beginning.
So
Is there a way to check if the input field characters are highlighted?
I know that there is a way around this if my input has type="text" and just use selectionStart and selectionEnd BUT I want to keep it as type="number".
Code: jsfiddle DEMO
Any other suggestion to jQuery code handling 2 decimal place, I would appreciate
If I am understanding your issue correctly, try the following minimal update to detect if the user has 'highlighted' the input value:
if (CharAfterdot > 3 && !window.getSelection().toString()) { return false; }
So if a 'selection' is found via the above method (not empty / undefined) the code allows further input (in your case overriding via highlight).
Updated fiddle:
https://jsfiddle.net/qtr30w05/3/

Javascript Disabling Multiple field objects onchange

I was using the following script to disable multiple field objects when one field was selected, I have changed the fields so that they no longer have a default value of zero but can have varying values:
JS
function disablefield(fieldObj)
{
var fields = new Array('Seat_1200', 'Seat_1230', 'Seat_100','Seat_130','Seat_500','Seat_530','Seat_600','Seat_630','Seat_700','Seat_730','Seat_800','Seat_830');
for(var i=0; i<fields.length; i++)
{
fieldObj.form[fields[i]].disabled = (fieldObj.value!=0 && fieldObj.name!=fields[i]);
}
return;
}
Can anyone suggest a way to detect the current value of the fields seat_xxxx (which are loaded dynamically) integrate it into the above script then disable the all fields when the value one changes. Or alternatively if the field is de-selected i.e. the user changes his mind and selects another option, then the field is set to zero automatically to satisfy the above script re-enabling all the selection options.
In response to the problem from the author I have a new code set.
I would use a Jquery button set to represent all the tables you have. Then selectively disable them based on the result. Below is a fiddle
http://jsfiddle.net/05cpss80/
Buttonsets are really just classed checkboxes but they give you what you need.
<input type="checkbox" id="check1"><label for="check1">Table1</label>
As such you can add additional classes to them to stop them from "checking"
$('#check2').attr("disabled", "disabled");
I would recommend you add some css to make it more obvious, but try the fiddle. Click 2, then the button and it will no longer work. (Thus when they make a selection you call disable on whatever tables you need)

Categories