Update value of INPUT in externally loaded FORM not working - javascript

total programming novice here - I don't know much of javascript, wasn't programming since university (about 10 years ago) - trying to solve one specific problem on my website.
I am using CRM Bitrix24 and I have an unsubscribe form from this CRM placed on my website. I need to setup the form the way that the email is loaded from URL parameter.
I have done that simply by loading the input and set input.value = "email from URL". My problem is that the form has some kind of validation, and even though there is a text filled in the input field, the form is giving me the error: Field is required.
Screenshot here: https://ibb.co/Ns33GVN
The code of external form look like this:
<script data-b24-form="inline/120/8y7xg2" data-skip-moving="true">(function(w,d,u){var s=d.createElement('script');s.async=true;s.src=u+'?'+(Date.now()/180000|0);var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);})(window,document,'https://cdn.bitrix24.com/b7014957/crm/form/loader_120.js');</script>
My JS:
function emailPopup(){
var params = new window.URLSearchParams(window.location.search);
var email = params.get('email');
const emailCollection = document.getElementsByName("email");
for (let i = 0; i < emailCollection.length; i++) {
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
}
}
} window.addEventListener('load', function () {
emailPopup();
})
I tried to understand how the validation is done, but with no luck. The field has autocomplete = yes, so once it is submitted, next time it's not shooting the error, but the form is sent with the email submited at the first attempt, even though it is showing another one when hitting the SUBMIT button. It seems like it's only showing the email address from URL parameter, but in fact it's using wrong value, it's even empty (first attempt) or wrong (second attempt).
Is there a way how to force the field to pretend it was modified by user? Any ideas?
I have tried to setup similar environment here in jsfiddle: https://jsfiddle.net/e395wf6m/17/
Thanks a lot for any feedback!

I have a theory and it seems to be correct, as I tested it in your fiddle.
My theory is that the validation is done by firing a change event, so you need to trigger it. Luckily JavaScript let us do it:
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
// to trigger the change event
emailCollection[i].dispatchEvent((new Event('change')));
}
As I said, it worked when I tested it on your fiddle, let me know if it works for you =]

Related

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

Angular JS form running only first time

I am at the very beginning with my Angular learning and I implemented this form:
http://codepen.io/jgrecule/pen/WxgqqO
What it is supposed to do is very basic: it consumes Flickr public JSONP feed as per Flicker specs https://www.flickr.com/services/feeds/docs/photos_public/ and renders the retrieved pictures thumbnails
The form I implemented has a submit button as well as a reset one. My problems I am trying too find solutions in the order of their importance are:
The very first time when you typing tags everything works but when u try to submit the request again by either adding a new tag or an user Id or anything it no longer works. I can see this warning in the logs but I have no idea what is causing it WARNING: Tried to load angular more than once.
The reset only works for the thumbnails but not for the other controls in my page
I would like to find a way to show an error message when the user pushes on the search flicker button and both tags and user ids input fields are empty. I tried to implement a custom directive but it was no way to get it working.
Thank you in advance for your inputs.
You are loading Angular more than once.
Your resetForm function doesn't reset the form at all. It just calls $setValidity on two of the form elements. It looks like it does try and reset the form in another part of your code with
document.getElementById("searchCriteriaTags").innerHTML = "";
document.getElementById("searchCriteriaIds").innerHTML = "";
document.getElementById("images").innerHTML = "";
which means you are modifying the DOM directly, about which see point 4.
You can add a simple check as to whether $scope.form.tags === '' and so the same for the other fields in your form.
Having addressed your 3 points, I'm afraid to say your code has bigger problems. You are modifying the DOM directly all over the place and you have a lot of duplicate code, plus lots of very complex conditionals.
EDIT 1 in response to OP's comment:
The Angular way of clearing form fields would be to simply clear the scope objects that the form fields are bound to. In other words it is as simple as doing something like:
$scope.tags = [] // for arrays
$scope.name = '' // for strings
Because the form fields are bound to these scope variables through the ng-model directive, changing the variables will also change the form fields.
Setting an error message when two fields are empty you can do like this:
$scope.checkFields = function(field1, field2) {
var oneEmpty = field1 === '';
var twoEmpty = field2 === '';
if (oneEmpty && twoEmpty) {
// call the failure message here
}
}
EDIT 2 in response comments:
Firstly good to see that your code is looking a lot cleaner. Secondly, the reason it fails is because in your search function you set the search fields to null, eg searchCriteria.tags = null;. You should set them to empty strings instead: searchCriteria.tags = '';.
I don't know what the purpose of checkFields is so I don't know where you want to place it. If you want to show an error message if the fields are empty then I'd say have checkFields() return a boolean and use ng-show to display the error div if checkFields() === false.
HTML:
<div ng-show="checkFields() === false">Fields can't be empty</div>
JS:
$scope.checkFields = function(field1, field2) {
var oneEmpty = field1 === '';
var twoEmpty = field2 === '';
return (oneEmpty || twoEmpty);
}

How do I pass a value from an HTML form submission to a Google Sheet and back to HTML in a Google Apps Script Web App

I'm trying to create a basic time clock web app.
So far, I'm using this script to create this web app which takes the input values and puts them in this spreadsheet for the time stamping part.
I need it to use one of the values from the form and perform a lookup in this sheet (take the longId and find me the name) and return the (name) value to the html page as a verification for the end user that they were identified correctly. Unfortunately, I don't know enough to grasp what I'm doing wrong. Let me know if I need to provide more info.
Edit 1
I'm thinking that I wasn't clear enough. I don't need the user info from entry, I need the user from a lookup. The user will be entering their ID anonymously, I need to match the ID to their info, and bring the info back for them to verify.
Edit 2
Using the link provided by Br. Sayan, I've created this script using this spreadsheet as above to test one piece of this. The web app here spits out: undefined. It should spit out "Student 3" Still not sure what I'm doing wrong.
One way for the next button to grab the student input field:
<input type="submit" onclick="studentName(document.getElementById('student').value)" value="Next..."/>
That sends the value to this func in Javascript.html:
function studentName(value) {
google.script.run
.withSuccessHandler(findSuccess)
.findStudent(value);
}
Which sends it to a findStudent(value) in Code.gs
You do the lookup and the return value goes back to findSuccess( result ) back in Javascript.html. Handle the result from there.
Also consider keeping the stock preventDefault() code that comes with the Web App template in the Help > Welcome Screen.
Please try this one:
(source: technokarak.com)
Also please have a look at:
Retrieve rows from spreadsheet data using GAS
EDIT:
Please make these changes in your function and let us know.
function findValue() {
var data = SpreadsheetApp.openById("15DRZRQ2Hcd7MNnAsu_lnZ6n4kiHeXW_OMPP3squbTLE").getSheetByName("Volatile Data").getDataRange().getValues();
for(i in data) {
if(data[i][3] == 100000003) {
Logger.log("yes");
Logger.log(data[i][0]);
var student = [];
student.push(data[i][0]);
return student;
}
}
}
It is a complicated answer, I have had a lot of success with:
function process(object){
var user = Session.getActiveUser().getEmail();
var key = object.Key;
send(key);
}
function send(k){
var ss =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastR = ss.GetLastRow();
ss.GetRange(lastR,1).SetValue(k);
}
On your html button you will need to have inside the tags
onClick="google.script.run
.withSuccessHandler(Success)
.process(this.parentNode);"
In order for this to work, obviously you will need to have your fields named accordingly.
Edit: The only thing I did not include in the code was a Success handler, which will be in your html of the GAS script. This should point you in a direction that can resolve that.
Hope this helps.

JQuery/Javascript: Error Message not displayed on Form

So basically I have a form where a user is allowed to create a group. An error message is supposed to be displayed if the user does something they are not supposed to for example they enter a group name that already exists. My code is shown below.
Any help would be appreciated.
Just a side note, any error message that is related to the field works fine. For example, if you don't enter anything into a required field, error message is displayed as it should on the form.
I'm not too familiar with that code that's creating the group form, but it seems that
%div{:id => "id___all__"}
may not be creating the field
$('#non_field_errors');
that you're trying to reference in
jQuery.each(errors, function(i, error) {
if (field != '__all__') {
$fieldId = $('#id_'+field);
} else {
$fieldId = $('#non_field_errors');
}
$fieldId.closest('.control-group').addClass('error');
$fieldId.parent().append(
$('<span class="error_span">').addClass('help-inline').append(error));
})
Basically, it SEEMS to me, without being 100% familiar with all this, that you're trying to place the errors into
$('#non_field_errors');
when you should be putting it into
$('#id___all__');
So nothing's happening. Let me know if this points you in the right direction. The loop itself appears to be working fine.

Reading and checking user's entry from a text field in an html form

What I want to do is to have a form field that allows a person to try to guess from a picture what type of bird it is, and if they get it right, it tells them they got it right and gives them the code to be able to get a discount.
Here is the code I'm using within the head tags:
formCheck()
{
var birdName = document.forms[0].birdName.value
if (birdName == "red bellied woodpecker")
alert("That's Correct! Please enjoy 10% off your next purchase by entering the code NAMETHATBIRD92 during checkout.")
else
alert("That's isn't the correct answer! Make sure your answer is very specific and keep trying, you can guess as many times as you want.")
}
Here is what I have within the body tag:
Can you name this bird?
It works here:
www.madhatwebsolutions.com/namethatbird.html
It does not work here, where I really need it to work:
http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
This shouldn't be JavaScript.
Any potential customer will be able to right click and view your JavaScript source and retrieve the code without bothering with the guesswork.
You'll need to query a server with the user input, and the server will need to return a response indicating whether this input is correct or not.
You might want to look at either a normal HTML form submission, or venture into AJAX
Workflow:
User enters guess into textfield
Launch a request to http://yourserver.com/check_bird.your_server_language?guess=theTextFieldValue
Server returns either a success or failure indication
Display response to client
Other things to consider: Are you going to allow your customers to guess multiple times, or restrict them? Are you going to be showing several different birds or not?
in http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
<script type="text/javascript" src="birdname.js"></script> refers to 404 - check the file path
don't use document.forms
var birdName = document.getElementById('birdName').value;

Categories

Resources