I am trying to figure out how to do something but can not figure out the correct terminology to do so.
What I am trying to do is have a textbox (#price) that when clicked once it will open up a pdf calculator that will then either prefill the textbox when completed or will then allow the user to enter the amount in. But I also want this to work if the textbox is "tabbed" over to also instead of the onClick. (Maybe onBlur) Basically anytime that textbox is used I need it to work like that. But how do I make the onClick know when the amount is ok to be entered or if the calculator needs to open?
What also makes this tricky is I need to have an On/Off switch basically a checkbox that when checked it allows that pop up pdf calculator and when its not checked it just ignores it and allows the price to be entered still.
Does anyone have any suggestions or pointers in how I can achieve this goal?
1. A textbox (#price) that when click once it will open up a pdf calculator
Use jQuery's click() handler or bind("click", ...)
var $price = $("#price");
$price.click(function() {
$("#pdf_calculator").fadeIn();
});
2. But I also want this to work if the textbox is "tabbed" over to also
Use the focus event to know when an input is active (i.e, has been "tabbed" to). Alternatively, the blur event can be used if you want to know when a user is "leaving" the input field. ('blur' is the opposite of 'focus')
$price.on("focus click", function() {
$("#pdf_calculator").fadeIn();
});
3. But how do I make the onClick know when the amount is ok to be entered or if the calculator needs to open?
Grab the amount typed in by the user, convert it to a numerical value, then perform your validation steps.
$price.on("focus click", function() {
// Do some validation checking on the amount entered.
var enteredValue = parseFloat($price.val());
if (!isNaN(enteredValue) && enteredValue > 0) {
$("#pdf_calculator").fadeIn();
}
});
4. What also makes this tricky is I need to have an On/Off switch basically a checkbox that when checked it allows that pop up pdf calculator and when its not checked it just ignores it and allows the price to be entered still.
Simply check that the checkbox is checked using jQuery's is(":checked") then combine the steps above, and your fully working code looks like this:
var $price = $("#price");
$price.on("focus click blur", function() {
// your checkbox element
var checkbox = $("#show_calculator");
// Check if the checkbox is checked
if (checkbox.is(":checked")) {
// convert the entered string to a number
// then validate it according to your needs
var enteredValue = parseFloat($price.val());
if (!isNaN(enteredValue) && enteredValue > 0) {
// if all conditions are met,
// show the pdf calculator
$("#pdf_calculator").fadeIn();
}
}
});
Click here to review a working jsfiddle of these ideas.
As for the pdf form (and getting values in and out again of a pdf form) there isn't a straight-forward method that doesn't involve a 'hack' (that may or may not work across different browsers). If the pdf only has ONE input, then you can capture the keyboard events on your form popup, and send them back to the HTML form (which is an ugly hack), but if this were my project, I would just convert the pdf functionality to javascript, and then you have all the freedom you need, and your calculator is 100% compatible with the rest of your application.
Hope this helps!
The event(s) you are looking for is onFocus and onBlur. I would bind a function to the onFocus event that first checks if the corresponding checkbox has a "true" (or "checked") value, then continue if it does and do nothin if it doesn't.
I'd create an example in jsfiddle for you if I wasn't answering this from my phone.
Bind event handler to focus event (blur is for when control looses focus).
$("#price").on({
"focus": eventHandler
})
Then in your eventHandler() check if calculator needs to be invoked, by checking if it's already opened: $("#calculatorDiv").is(":visible"), and checking if your checkbox is 'checked': $("#checkboxId").is(':checked'), and depending on that open it.
Related
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')) ;
I have a task where I need to automate Sign in form authentication. For this example, I'll show you Tiktok authentication form (Mobile interface, not desktop. E-mail and password option)
If I enter text values into the fields programmatically, the Login button won't become active, and if I manually focus on the fields with a mouse click, the value disappears. These are two lines of code I run to put the value in:
let email_input = document.getElementsByName("email")[0];
email_input.value = 'sample#email.com';
I understand it needs to trigger a certain event to assign a value into it's JS model, but I can't figure out how to do it. I have tried sending change or input events onto this text field with no luck using this code:
let email_input = document.getElementsByName("email");
email_input[0].value = 'sample#email.com';
custom_event = new Event('input');
email_input[0].dispatchEvent(custom_event);
// tried also change, textInput like so:
custom_event = new Event('change');
email_input[0].dispatchEvent(custom_event);
But this does not seem to help.
So my goal is to put values into both fields Email and Password in the way it will be detected and Log in button would become active.
Any suggestion would be much appreciated
You should first focus needed input element and then execute document.execCommand with insertText command:
let email_input = document.getElementsByName("email");
email_input[0].focus();
document.execCommand('insertText', false, 'sample#email.com');
With this method input\textarea value modification should be captured by all major frameworks including Angular and Vuejs. This modification will be processed by frameworks the same way as if user pressed "Paste" option in browser main menu.
It all depends...
Who/what are you? A normal browser user? A bot? The browser author?
Because code like this is useless...
let email_input = document.getElementsByName("email")[0];
What document are you referring to? Who's document? Did you inject this instruction into the page and executed it?
You're not telling us where you're coming from, but anyway...
If you are the browser author, or you can run JavaScript macros from your browser (ie: the Classic browser) then you can do something like this...
var Z=W.contentWindow.document.querySelectorAll('input[type="password"]');
if(Z.length>0){
Z[0].value='password123';
Z=W.contentWindow.document.querySelectorAll('input[type="email"]');
if(Z.length>0){Z[0].value='email#abc.com';}
}
To automatically populate such fields, and if you also want you can SubmitButtonID.click() the submit button for as long as the isTrusted property is not tested by the website.
Continued...
Test if normal (non-custom) submit button exists and click...
Z=W.contentWindow.document.querySelectorAll('input[type="submit"]');
if(Z.length>0){
if(Z[0].hasAttribute('disabled')){Z[0].removeAttribute('disabled');} <--- Enable it if disabled
Z[0].click(); <--- automate click
}
I have a DataGrid with a search function and I want the Website to automatically refresh the grid with every key pressed in the search bar, just like modern search engines do. Imagine it like Pressing enter after every key pressed, or clicking on the search button. The only way in Mendix to do it is with external Widgets (cant use them cause most of them Arent able to search for related entities in the database) or to use JavaScript Snippets which I did.
I have already tried to programmatically press enter, but I cannot get the Code to do it.
Another Option I tried was to programmatically click the search bar after every key pressed which in itself works but the Problem here was that the selection jumps out of the Input field and onto the search button and there is also no Input in the search field.
Option 1: Programmatically clicking the search button
defining the Elements on the page
var dataGrid = document.querySelector('.mx-datagrid.mx-name-grid1');
var itemsSelect = dataGrid.querySelector('.mx-grid-search-input.mx-name-searchField1')
var searchButton = dataGrid.querySelector('.mx-grid-search-controls > button.mx-grid-search-button')
defining the function
function clickSearchButton() {
searchButton.click();
};
triggering the function with every Change in the input
itemsSelect.onkeypress = function(){clickSearchButton};
Option 2: Programmatically hit Enter
It's Pretty much the same Code as above and the way I would prefer it.
I tried many variants but the only Thing I want in the end should look like this:
itemsSelect.onkeypress = function(){*call a function to programmatically press enter*};
I tried Solutions from all over the place for example:
Is it possible to simulate key press events programmatically?
I want to press enter key by programmatically when user do some stuff in js
and many other Sources, some claiming that it is not possible because of security reasons. Is that true?
I'm trying to solve this since around two weeks, with Pretty much no success. Have I overlooked anything, is there another solution that I did not think of? Not using Mendix is not an Option. It's for a huge Project at work.
First, figure out the class and the id of the textfield and the button you are interested in. Usually those start with mx-name- prefix. In this example they are called mx-name-confirmPasswordInput and mx-name-confirmChangePassword.
Then, use the HTML Snippet custom widget to insert this piece of Javascript in your page:
(function() {
document.addEventListener("keydown", function(e) {
if (e.keyCode !== 13) return; // ignore if the pressed key is not 'Enter' key.
var inputField = document.querySelector(".mx-name-confirmPasswordInput input");
var btn = document.querySelector(".mx-name-confirmChangePassword");
if (inputField && btn && document.activeElement === inputField) {
inputField.blur && inputField.blur(); // not necessary any more in 7.22 and up
btn.click();
}
});
})();
That should do the trick!
Scenario: I have a form with several accordions (that are expandable divs), each one has some required fields, the user is free to collapse or expand them, so, in some cases, there are non filled mandatory hidden fields (because collapse) when form is submitted.
Problem: In Chrome, no errors appears to user, only in the console you can read:
An invalid form control with name='' is not focusable.
I've found plenty of answers to this issue. I exactly know why is this happening, but I've not found any solution to my problem.
What i've tried: Before submitting the form, expand all accordions to make visible all required fields so I can allow browser to focus element and show Required field message (see update)
Desired solution: identify id of mandatory field that requires a content, to expand it's accordion container and focus the field
UPDATE:
Solution found expanding all collapsable divs by javascript is not working in all cases, so IS NOT a solution.
QUESTION: there is some way can I show the field before validation?? If no... Can I focus or identify a hidden mandatory field when submitting form.
I personally would go with Niet the Dark Absol's suggestion about checking fields when changing section and displaying warning flags (I think it would give a better user experience).
But if you want to continue with the check on form submission, there's a way of tricking the browser into doing what you want by using JavaScript. The browser identifies and highlights the first invalid field that is visible when the page validates (for IE and FF it will highlight all the invalid fields that are visible); so, before the form validation happens, you'd need to run a quick check and open the accordion section that contains the first invalid field.
The key is to run that check before the HTML5 validation happens. That means that onsubmit is not good enough, as the browser will validate before the submit event. You need to run the code when the submit button/image is clicked, as that click event happens before the browser validates the fields.
You didn't specify if it was for jQuery UI or Bootstrap, so here are examples for both (the code is similar, just changing the way to handle opening/closing the accordion):
JQUERY UI ACCORDION
You can see a working demo for jQuery UI on this JSFiddle: http://jsfiddle.net/ma8v32ug/1/. The JavaScript check would be like this:
// save the accordion in a variable as you'll need it later
$accordion = $("#accordion").accordion();
// when the submit is clicked
$("#myForm input[type='submit']").on("click", function(event) {
// traverse all the required elements looking for an empty one
$("#myForm input[required='required']").each(function() {
// if the value is empty, that means that is invalid
if ($(this).val() == "") {
// find the index of the closest h3 (divide by 2 because jQuery UI accordion goes in pairs h3-div. A bit hacky, sorry)
var item = $(this).closest(".ui-accordion-content").prev().index() / 2;
// open that accordion section that contains the required field
$accordion.accordion("option","active", item);
// stop scrolling through the required elements
return false;
}
});
});
BOOTSTRAP ACCORDION
Note: this is valid for version 3.3.4 of Bootstrap. I haven't checked in older or newer versions.
One important thing to take into account for Bootstrap is that you cannot use the .collapse({toggle: true}) functionality because the animation takes more time than what the browser needs to validate the form, and the result will be unexpected (normally, the browser will stop the animation to point at the error, and it will not be the field that you want).
A solution to that is to do the toggle without animation, just by changing the .in class in the panels, and adjusting the target panel height. In the end, the function would look really close to the one for jQuery UI, just changing slightly:
// when the submit is clicked
$("#myForm input[type='submit']").on("click", function(event) {
// traverse all the required elements looking for an empty one
$("#myForm input[required='required']").each(function() {
// if the value is empty, that means that is invalid
if ($(this).val() == "") {
// hide the currently open accordion and open the one with the invalid field
$(".panel-collapse.in").removeClass("in");
$(this).closest(".panel-collapse").addClass("in").css("height","auto");
// stop scrolling through the required elements
return false;
}
});
});
You can see it working on this JSFiddle: http://jsfiddle.net/ma8v32ug/2/
This is probably all kinds of bad user-experience, but I don't know much about that so I won't go into it XD Basically, as you can tell just from the practicality issues you're facing as the programmer, hiding required fields is bad.
I would suggest implementing validation yourself, such as in change events. Check for the validity of all input elements within that accordion section, and if any of them fail you can put a warning flag on the accordion's header bar and disable the submit button.
Only when all fields pass validation do you then enable the submit button and allow the user to continue.
Of course, this does defeat the purpose of the native validation that HTML5 provides, but you're already using non-native accordions so you kind of have to go non-native for your validation to work.
Simple question (I guess)...
I'm in an "edit-some-element" html form.
As the page load, the form is filled with current element attributes (eg. name, etc.)
I could modify some input fields or even decide not to do that but I click the same on submit button because is the only available one.
MY QUESTION:
is there a property/attribute of the input elements containig the initial input values that I can access to compare them with the current ones when I click on submit button?
In other words:
is there a fast way to check if at least one input field has been changed before submitting the form? (so to stop the event if an update isn't really necessary)
(and I mean "really changed" not considering as changes when I modify something but rewrite it as it was before)
I'd like a minimal example:
How to check if a simple input-text "name" has been changed
P.S.
Of course, to trigger the "check-if-something-changed" function,
if I decide to use pure javascript I would use onSubmit event while using jQuery I would use something like:
$('#formMod').submit(function(){ ...
Thanks.
You can use the input element defaultValue dom property:
function validateInput(input) {
if (input.value == input.defaultValue) {
alert("Please change field.");
return false;
}
return true;
}