jquery Validate Plugin. Generate random success message, once - javascript

Yesterday I posted this question which is answered but it lead to another problem.
I have the following code using jquery validation plugin:
//array of success messages and randomly select one
var messages = ["Good!", "Great!", "Awesome!", "Super!", "Nice!","Yay!", "Success!", "Ok!", "Perfect!","Sweet!" ];
function successMessage(label) {
return messages[Math.floor(Math.random() * messages.length)];
}
Then my validation code success
...success: function(label) {
if(!$(label).hasClass("valid")){
label.addClass("valid").text(successMessage());
}
}...
What is happening is that each time the form is being valid (on keyup or foucus) it regenerates a success message. I figured since i was adding the class "valid" a logical step would be to check if the label has the "valid" class and is so don't add a message because it already has one. This however isn't working. Any other ideas would be great.
Edit: So after further research and thinking. I'm pretty sure the problem is that the class of "valid" is being removed and added each time time form is validated (on keyup, submit, etc) I think the easiest thing to do may be to select the value of the label and look to see if the result matches the array, if so then don't do anything else add a success message. I could be wrong. I also don't think I articulated the question the best the first time. It just looks silly to have the validation message change while the user is typing.
EDIT 2 After the many suggestions for clarification and example code I am posting this link http://jsfiddle.net/Ye3Ls/20/ if you type into a field until you get a success message then keep typing you'll see what the problem is. I'm using the validation plugin found here Thanks for all your patients as I sort though how to get this to work. I think i may need to use something like in_array or has_value()

Don't need label as a parameter for successMessage.
function successMessage() {
return messages[Math.floor(Math.random() * messages.length)];
}
I believe that if label is already a jQuery object doing this: $(label) will create a new label jQuery object attached to jQuery. Try this:
if(!label.hasClass("valid")){
label.addClass("valid").text(successMessage());
}
Or
if(label.not(".valid")){
label.addClass("valid").text(successMessage());
}
Or even better:
label.not(".valid").addClass("valid").text(successMessage());
[EDIT] after question asked in comment
if(label.text() === ''){
label.not(".valid").addClass("valid").text(successMessage());
}
else {
label.addClass("valid");
}
I'm assuming that you need to add the valid class to label. If you don't then remove the else statement.
I'm also assuming that the only way for text to be in label is through successMessage. Therefore, you will not need to add any text to label. It will stay the same.
On a side note, if the plug-in is changing the classes of your HTML elements then that is a serious side-effect of the code and I personally wouldn't put up with that.
Now the more logical thing that is probably happening is that you are reloading your content after doing your submission. If that is true then all the jQuery manipulations to the DOM you did before submission will be lost, because of new content be reloaded.
It would be really important in the future to add a link to the actual plug-in and more complete code to work with. #Nick Craver uses jsfiddle.net and I use jsbin.com to post sample code. This can be a more collaborative effort on all our parts to be able to reproduce and solve the problem.
[EDIT 1A]
Here it is
The problem is that the label is being created more than once. This plug-in in my opinion is not so easy to work with.
I had to change the error placement and success logic.
errorPlacement: function(label, element) {
// position error label after generated textarea
var name = element.attr('name');
if ($('#' + name + '_label').length === 0) {
label.attr('id', name + '_label');
label.insertAfter(element);
if (element.is("textarea")) {
label.css({'padding-left': '105px'})
}
}
},
success: function(label) {
var name = label.attr('for');
$('#' + name + '_label').not('.valid').removeClass('error').addClass('valid').text(successMessage());
}

It looks like you mean to say:
$(label).addClass("valid").text(successMessage());
rather than:
label.addClass("valid").text(successMessage());

If label is a variable, and label.addClass("valid") works fine, why don't you verify using:
if(!((label).hasClass("valid"))){
instead of
if(!$(label).hasClass("valid")){

Related

Update value of INPUT in externally loaded FORM not working

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 =]

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)!

select2 - get current search text

I'm using select2 and fetching available options from the server with this query function
var recipientsTimeout;
this.loadRecipients = function (query) {
clearTimeout(recipientsTimeout);
recipientsTimeout = setTimeout(function(){
data.transmitRequest('lookupcontacts', { search: query.term }, function(resp){
query.callback({ results: resp.items });
});
}, 500);
};
It uses our own ajax layer, and delays searching until the user stops typing, and it works fine. The only small issue is that if the user types some text, then immediately backspaces over it, my last timeout will still fire, and an ajax request will be fired, and ignored. This doesn't cause any problems, but it's less than optimal.
Is there any (preferably non-brittle) way to fetch whatever the current text is? It seems as though the query object sent in has an element property, which is a jQuery wrapper of the original hidden input I set select2 up with, but there's no direct way I can see to get the actual textbox that the user is typing in. Obviously I could inspect it and easily figure out the dom pattern and build up a selector from the hidden element back to what the user is typing in, but I really hate doing that, since the specific layout could easily change in a future version.
So what is the best way to get the currently entered text, so I could do a quick check on it when the setTimeout expires, and I'm about to run my ajax request.
I'm using 4.0.3 and the way I did it is this:
$("#mySelect2").data("select2").dropdown.$search.val()
The hidden input element (where you initialize select2 on) gets a data property select2, which contains references to all elements, that are used by select2. So you could do something like this:
var hiddenInputSelector = '#e1',
select2 = $(hiddenInputSelector).data('select2'),
searchInput = select2.search;
if($(searchInput).val() === '')
clearTimeout(recipientsTimeout);
This is not in the docs though, so it might change in the future.
In select2 version 4.0.3 this works for me, whereas the others did not:
$('.select2-search__field')[0].value;
I do something like this to get the current search term:
list.data("select2").search[0].value;

Test the existence of User/System DSN in XPages

in my xpage I have an editbox for user to enter the name of the ODBC data source. Then onBlur I want to test whether the user entered value is valid/exist in the ODBC list. If there is error/exception, I want the error to be displayed in a 'Display Error' control I have in the xpage. I'm not sure where to start. Never done something like this before(even in LotusScript). Somebody enlighten me please?
I wouldn't do that in an onBlur event. Your user might want to change something else and you hit her with a slow operation. What you should do:
have a test button
gray out the "save" button until the test was successful
In any case: have a look at the extension library. It has the RDBMS connectivity build in (use it, don't reinvent the wheel). Copy the code from there.
Ok, apparently this is what I need. Maybe I should polish my question asking skill. Thanks to those who help though.
Referring to here, I create 3 field/editbox: 'ODBC/DSN Name', 'username', 'password'. For 'ODBC/DSN Name', I put an xp:validateExpression and put the following code for the expression part:
var odbc:string=getComponent("inputText1").getValueAsString();
var url:string="jdbc:odbc:"+odbc;
var usr:string=getComponent("inputText2").getValueAsString();
var pwd:string=getComponent("inputText3").getValueAsString();
try {
java.lang.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
var con:java.sql.Connection=java.sql.DriverManager.getConnection(url,usr,pwd);
return true;
} catch (e) {
return false;
}
Not sure whether I utilized the xp:validateExpression or xpages itself the right way but that's what customer request and seems to be working now.
Better to write in onchange event of the item that you need to validate. Because we usually do the partial refresh for that event right? So It prevents the item from entering the value.
Simply try to write that in onchange event. But my opinion is that I used to write the validations for non- secure items in Jquery. Because that is very easy and gives nice outlook.

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