JQuery/Javascript: Error Message not displayed on Form - javascript

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.

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

Webpage redirect to submitted text value

I want to create a static webpage which has a text field and a submit button, which after a user submits text it would automatically redirect from localhost/ to localhost/<test_person_submitted> .
Up to this point, this JavaScript is the only thing I was able to clobber together from all of the guides I found
function confirmInput() {
fname = document.forms[0].fname.value;
url = "http://localhost/"
command = (url + fname)
location.replace(command);
}
That does work, but no matter what I added as HTML to invoke the function it doesn't work properly.
Can someone please add a submit form that will properly execute this?
Right now I'm stumped and I just want to consider this small project "complete", rather to just leaving it without ever knowing how it could be resolved.
If you are wondering why I want to do this it's because I'm going to try to invoke some wild-card commands that will return JSON.
And this is just a fun project for me.

Question about web forms, JavaScript validation function unreachable

Good day,
I've been working on this for class. I submitted the assignment and got a good grade - the professor didn't even lower my grade because I wasn't able to get this working, but I'm still frustrated because what I want this to do is to take a look at the Help Request form, alert me that it's checked, and to validate the email address. But the function seems to be unreachable.
I've made this fiddle here:
https://jsfiddle.net/b7j3ekts/
Stack overflow requires that I post code as well, but the fiddle is better I think:
/* This function never fired. I spent alot of time with it and I'm really frustrated and even though I posted my problem online and am going back and forth with
it, I kinda ran out of time to fix it. I was trying to do the part of the assignment where we looked to see if email was checked and then validated the email address. */
if (document.getElementById("contactemailH").checked === true) {
alert("Checked!");
/* Checks the email field to make sure that it's an email address in formHELP */
var emailaddy2 = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (document.forms["formHELP"]["FromAddress"].value.match(emailaddy2)) {
}
else {
alert("Please input a valid email address.");
return false;
}
}
}
The offending code starts at around line 123 of the js file.
Any advice appreciated. :)
-- Mark
if (document.getElementById("contactphoneH").checked === true ||document.getElementById("contactemailH").checked === true ) {
alert("Checked!");
/* Checks the email field to make sure that it's an email address in formHELP */
var emailaddy2 = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\
[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]
{2,}))$/;
if (document.forms["formHELP"]["FromAddressH"].value.match(emailaddy2)) {
}
else {
alert("Please input a valid email address.");
return false;
}
}
You just had misspelled tags.
You seem to need an event listener. The JavaScript loads once, does anything you've marked as immediate, and then it just sits there dormant. If you want a function to run you have to call it by name, or tell JavaScript to watch for an event.
In your case I'd tell JavaScript to wait for the event "blur", which is when an element was focused and then loses focus, so it's great for form fields.
document.getElementById('contactemailH').addEventListener('blur', function(event) {
validateEmail(event.target.value)
})
let validateEmail = function (emailaddy) {
// do your check here
}
Let me know if I'm off-base; I'm reading your fiddle on a mobile and jsfiddle is not mobile friendly at all.

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;

jquery Validate Plugin. Generate random success message, once

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")){

Categories

Resources