Javascript/JQuery error message didn't hide in Safari - javascript

In my registration form I have some validation logic which works perfectly fine in Chrome but in Safari error message don't disappear below form after filling empty fields. It looks like show() and hide() doesn't work and I don't now why because based on this https://www.quirksmode.org/dom/events/index.html it should worked.
if (registrationsForm.length > 0) {
var emailField = $('#users-registrations-email');
var emailConfirmationField = $('#users-registrations-email-confirmation');
var emailInvalidMsg = $('.bank-employees-users-registration__registrations__not-identical-email');
var obligatoryInvalidMsg = $('.bank-employees-users-registration__registrations__email--invalid');
submit.on('click', function(e) {
e.preventDefault();
if (emailField.val() !== emailConfirmationField.val() && emailField.length > 0) {
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
emailConfirmationField[0].setCustomValidity('Incorrect confirmation email');
if (emailField.val() !== '') obligatoryInvalidMsg.hide();
} else {
emailConfirmationField[0].setCustomValidity('');
}
validateEmail();
var invalidInput = $('input:invalid');
if (invalidInput.length === 0 && !fileInput.hasClass('invalid')) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateInput();
}
});
}
Function which is responsible for input validation:
function validateInput() {
$('input').change(function() {
if ($(this).is(':valid')) {
$(this).removeClass('invalid');
}
});
}
Edit
This is a code snippet from view
new.html.erb
<div class="floating-label bank-employees-users-registration__registrations-input--wrapper">
<%= f.email_field :email, class: "bank-employees-users-registration__registrations-input floating-field", id: "users-registrations-email", placeholder: t('.email'), required: true, aria_required: true %>
<%= f.label :email, t('.email'), class: "floating-label-placeholder" %>
<span class="bank-employees-users-registration__registrations__not-identical-email">
<%= t('.email_not_identical') %>
</span>
<span
class="bank-employees-users-registration__registrations-input--invalid-msg bank-employees-users-registration__registrations__email--invalid"
id="bank-employees-users-registration__registrations__email--invalid">
<%= t'.obligatory' %></span>
<% if #registration_form.errors.full_messages_for(:email).first %>
<div class="alert alert-danger">
<div class="error-explanation">
<%= t('activerecord.errors.models.user.attributes.email.taken') %>
</div>
</div>
<% end %>
</div>
Edit2
Maybe this will be helpful - as you see there are some email validations where two email address has to be equal. When I provide different email address it shows me error message that they are not equal but if I correct them, the error will be changed to - this field is required. I was trying to implement this solution jquery .show() and .hide() not working in safari - adding spinner to <a href but without any positive results.

Why not get rid of all that and use HTML5 fields? They have client-side validations that work across browsers and you can validate input on the server side using model validations, let Rails deal with all that.
I know it may be a bit of upfront investment into refactoring all that but otherwise things will only get worse in the long term if you keep doing what you're doing.
Also look at the Bootstrap form gem in case you're using Bootstrap.

Related

How to call flash on the client-side?

CODE:
login.ejs
<script>
req.flash('success_msg', 'You have logged in');
</script>
header.ejs
<div class = "alertMessage">
<% if (success_msg != false){ %>
<span class="alert alert-success containerMargins">
<%= success_msg %>
</span>
<% } %>
<% if (error_msg != false){ %>
<span class="alert alert-danger containerMargins">
<%= error_msg %>
</span>
<% } %>
</div>
SITUATION:
This has nothing to do with using flash on the server-side and displaying the message on the client-side: it already works perfectly for me.
This has to do with calling flash from the client or replicating the same behaviour from the client with some other library.
QUESTION:
The code I showed of course does not work on the client-side, what can I do to replicate that behaviour on the client-side ?
The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.
So you need code which:
Stores some data somewhere that the client can access between pages
Reads that data
Deletes it after being read
Start by picking somewhere for option 1 (such as localStorage, or a cookie). The rest should be trivial - the original module is about 80 lines of code, including about 50% comments — to implement (but specific to which choice you make).
Here is the solution I used:
<div class = "alertMessage">
<span class="alert alert-success containerMargins" id="successDiv"></span>
<span class="alert alert-danger containerMargins" id="errorDiv"></span>
</div>
<script>
if (localStorage.getItem("success_msg_local") != null) {
document.getElementById("successDiv").innerText = localStorage.getItem("success_msg_local");
document.getElementById("successDiv").style.display = "inline-block";
window.localStorage.clear();
}
else if (localStorage.getItem("error_msg_local") != null) {
document.getElementById("errorDiv").innerText = localStorage.getItem("error_msg_local");
document.getElementById("errorDiv").style.display = "inline-block";
window.localStorage.clear();
}
</script>
and replacing req.flash('success_msg_local', 'You have logged in') by:
localStorage.setItem('success_msg_local', 'You have logged in');

Rails and jQuery: How to select input from a specific form

I have a rails app with a job model, and on the index page, each job has a form. I need to be able to access the specific form everytime the submit button is selected, so I can take the input for the form and perform some jQuery validation with it.
Here is some of my index.html page.
<ul>
<% #unassigned.each do |job| %>
<li>
<div class="row new-message">
<div class="small-12 columns">
<%= form_for #message do |f| %>
<%= f.text_area :body, {placeholder: 'enter a new message...'} %>
<%= f.hidden_field :job_id, value: job.id %>
<%= f.submit 'send message', class: 'button small radius secondary message-button', "data-job-id" => job.id %>
<div id="message<%= i %>-validation-errors"> </div>
<% end %>
</div>
</div>
<li>
<% end %>
<ul>
And here is the javascript/jQuery where I try to select the input from a specific form
var messages;
messages = function() {
$('.message-button').click(function(e) {
var id = $(this).data('job-id');
messageValidation(e, id);
});
function messageValidation(e, id) {
var body = $('#message_body').val();
var div = '#message' + id + '-validation-errors';
if(body == "") {
$(div).html('');
e.preventDefault();
$(div).html('<small style="color:red"> Message body empty </small>');
}
};
};
$(document).ready(messages);
The index page will have a form for each job, and I want there to be front end validation that checks when the button is submitted, that the body field is not empty. It works fine the first time, but after going back to the index page, and trying to validate a second time var body = $('#message_body').val(); always seems to be empty, whether I put anything in the body or not. I believe it has something to do with the fact that since there is the same form for each job, there are multiple #message_body id's on the same page, and it is selecting the incorrect one. I am new to jQuery and javascript can someone please help me
You cannot have multiple elements with same id on a page. What you can do is add a class identifier to those elements.
In your case, simple set class="message_body" to your elements and select them as shown below:
$('.message-button').click(function(e) {
var id = $(this).data('job-id');
var body = $(this).parent().find('.message_body').val();
messageValidation(e, body, id);
});
To solve this problem I needed to select the child of the form and find the message_body through that.
messages = function() {
$('.new_message').submit(function(e) {
//var id = $(this).data('job-id');
var $this = $(this);
var body = $this.children('#message_body').val();
var id = $this.children('#message_job_id').val();
messageValidation(e, body, id);
});
function messageValidation(e, body, id) {
var div = '#message' + id + '-validation-errors';
if(body == "") {
$(div).html('');
e.preventDefault();
$(div).html('<small style="color:red"> Message body empty </small>');
}
};
};

clear input after search

I have a search box on my site. The search works well. I'd like the search field to clear after you submit a search. I have it working to clear onclick but the onsubmit doesn't work. It is definitely submitting a search because I can see the results.
js
<script type="text/javascript">
function clearDefault(el) {
if (el.defaultValue==el.value) el.value = ""
}
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
</script>
view
<%= form_tag guidelines_path, :class => 'navbar-search pull-right', :onSubmit=>"clearText(this)",:method => :get do %>
<%= text_field_tag :search, params[:search], :class => 'search-query', :placeholder=>"Search", :ONFOCUS=>"clearDefault(this)" %> <% end %
>
Th onsubmit isn't an event of a text field but rather the form it belongs to. If you move your onsubmit attribute to the form, it should clear it.
Rather than pass the field as a parameter, why not just fetch the field by it's class? So using jquery:
function clearText(){
search = $('.search-query');
if (search.defaultValue==search.value)
search.value = ""
}
If you can't use jQuery for some reason you could try and assign the form field an ID and use document.getElementById() instead?

How do I disable a submit button by default until it's text area has 1 character or more typed into it?

Currently when text area is focused on it expands it's height and the post and cancel button appear. Now I'd like to disable the submit button by default and only make it active once the text area has been typed into.
Later on I'll add opacity to the inactive submit button then take it away when the button is active just for a nice effect. But anyway I've tried applying disabled many ways and it doesn't work. I've tried various other things such as define a click function as well as submit then apply disabled using attr() to the disabled attribute of my form and it seems to have no effect.
HTML
<div class="comment_container">
<%= link_to image_tag(default_photo_for_commenter(comment), :class => "commenter_photo"), commenter(comment.user_id).username %>
<div class="commenter_content"> <div class="userNameFontStyle"><%= link_to commenter(comment.user_id).username.capitalize, commenter(comment.user_id).username %> - <%= simple_format h(comment.content) %> </div>
</div><div class="comment_post_time"> <%= time_ago_in_words(comment.created_at) %> ago. </div>
</div>
<% end %>
<% end %>
<% if logged_in? %>
<%= form_for #comment, :remote => true do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :micropost_id, :value => m.id %>
<%= f.text_area :content, :placeholder => 'Post a comment...', :class => "comment_box", :rows => 0, :columns => 0 %>
<div class="commentButtons">
<%= f.submit 'Post it', :class => "commentButton" %>
<div class="cancelButton"> Cancel </div>
</div>
<% end %>
<% end %>
JQuery:
$(".microposts").on("focus", ".comment_box", function() {
this.rows = 7;
var $commentBox = $(this),
$form = $(this).parent(),
$cancelButton = $form.children(".commentButtons").children(".cancelButton");
// $commentButton = $form.children(".commentButtons").children(".commentButton");
$(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();
$form.children(".commentButtons").addClass("displayButtons");
$cancelButton.click(function() {
$commentBox.removeClass("comment_box_focused").addClass("comment_box");
$form.children(".commentButtons").removeClass("displayButtons");
$commentBox.val("");
});
});
kind regards
Setting the disabled attribute doesn't work because if the disabled attribute is present, the field is disabled, regardless of the value of the attribute. You could use .removeAttr("disabled"), but it really makes the most sense to manipulate the disabled property which is more intuitive - it's just a boolean.
$commentButton.prop({ disabled: !$commentBox.val());
To be safe, bind to onkeyup, oninput, and onchange:
$commentBox.on("keyup input change", function () {
$commentButton.prop({ disabled: !$commentBox.val() });
});
If you need to manually enable or disable the button, such as after clearing the form, you can pass true or false directly to a call to .prop().
$commentButton.prop({ disabled: true });
Edit: Detailed breakdown
The .prop() method
The .prop() method gets and sets property values on elements, similar to how .attr() gets and sets attribute values on elements.
Considering this jQuery:
var myBtn = $("#myBtn");
myBtn.prop("disabled", true);
We can re-write that in plain JavaScript like this:
var myBtn = document.getElementById("myBtn");
myBtn.disabled = true;
Why we don't need an if statement
The reason we don't need an if statement is that the disabled property takes a boolean value. We could put a boolean expression in an if statement, and then depending on the result, assign a different boolean expression as the value of the property:
if (someValue == true) {
myObj.someProperty = false;
}
else {
myObj.someProperty = true;
}
The first problem is the redundancy in the if statement: if (someValue == true) can be shortened to if (someValue). Second, the whole block can be shortened to a single statement by using the logical not operator (!):
myObj.someProperty = !someValue;
The logical not operator (!) returns the negated result of an expression - ie true for "falsey" values, and false for "truthy" values. If you aren't familier with "truthy" and "falsey" values, here's a quick primer. Any time you use a non-boolean value where a boolean is expected, the value is coerced to boolean. Values that evaluate to true are said to be "truthy" and values that evaluate to false are said to be "falsey".
Type Falsey values Truthy values
———————— —————————————————— ——————————————————————
Number 0, NaN Any other number
String "" Any non-empty string
Object null, undefined Any non-null object
Since an empty string evaluates to false, we can get a boolean indicating whether there is any text in the textarea by applying ! to the value:
var isEmpty = !$commentBox.val();
Or, use !! to do a double negation and effectively coerce a string value to boolean:
var hasValue = !!$commentBox.val();
We could rewrite the jQuery from above to a more verbose form in plain JavaScript:
var myBtn = document.getElementById("myBtn");
var myTextBox = document.getElementById("myTextBox");
var text = myTextBox.value;
var isEmpty = !text;
if (isEmpty) {
myBtn.disabled = true;
}
else {
myBtn.disabled = false;
}
Or, a little shorter, and more similar to the original:
var myBtn = document.getElementById("myBtn");
var myTextBox = document.getElementById("myTextBox");
myBtn.disabled = !myTextBox.value;
You can try this:
var submit = $("input[type=submit]");
submit.attr("disabled","disabled");
$('textarea.comment_box').keyup(function() {
if ( !$(this).val() ) {
submit.attr("disabled","disabled");
} else {
submit.removeAttr("disabled");
}
});
Here's a JS Fiddle so that you can try this out: http://jsfiddle.net/leniel/a2BND/
You can first disable your submit button, and if textarea has a value enable it:
<form id="yourForm">
<textarea id="ta"></textarea>
<input id="submit" type="submit" disabled="disabled">
<form>
$("#yourForm").change(function() {
if ( $("#ta").val().length >= 1) {
$("#submit").removeAttr("disabled");
}
else {
$("input").attr("disabled", "disabled");
}
});
http://jsfiddle.net/dY8Bg/2/
You can achive this task using keyup event on text area. sample concept code below.
$("#textareaid").on('keyup', function (e) {
Count_Chars(this);
});
function Count_Chars(obj) {
var len = obj.value.length;
if (len >= 1) {
// do task
// enable post button
}
}
​
Added this to existing code to accomplish what I wanted. Marked answer that help me the most as winning answer and marked up others that helped.
commentButton = form.children(".commentButtons").children(".commentButton");
commentButton.attr("disabled","disabled");
commentBox.keyup(function() {
if ( !$(this).val() ) {
commentButton.attr("disabled","disabled");
} else {
commentButton.removeAttr("disabled");
}
});

How to validate an Ajax Form Submit (remote_form_tag)?

I have an ajax mail form like
- form_remote_tag :url=>mails_path,:condition=>"validate_mail()", :html => {:id=>"mailform",:method => :post, :class => 'ajax',:style=>"padding:15px;" } do |form|
.gimmespace
Naam
%br
= text_field_tag :name,params[:name],:class=>"title required"
.gimmespace
Telefoonnummber
%br
= text_field_tag :phone,params[:phone],:size=>25,:class=>"title"
.gimmespace
Mailadres
%br
= text_field_tag :email,params[:email],:size=>30,:class=>"title required"
.gimmespace
Onderwerp
%br
= text_field_tag :subject,params[:subject],:class=>"title required"
.gimmespace
Boodschap
%br
= text_area_tag :message,params[:message],:rows=>10,:cols=>45,:class=>"title required"
.gimmespace
= submit_tag "Verstuur",:id=>"mailsubmit",:class=>"sendBtn"
%button{:onclick=>"$.fn.colorbox.close();"} Annuleer
The above code is in HAML. It makes an ajax form submit to a controller. I have to validate the fields before it makes a submit. So, I tried several stuff. I read this article http://hillemania.wordpress.com/2006/09/18/rails-ajax-pre-submit-form-validation/ and made a before callback to a test javascript function to validate. Here is the javascript validating function.
function validate_mail() {
alert("Your Name, Email, Subject and Body Content are Required !");
return false;
}
As per the above function, it returns false any way and the form should not get submitted but, it submits well ajaxically. Is there any other way, please help.
I think you want to use the :condition option instead of the :before option. Something like this:
- form_remote_tag :url=> mails_path, :condition => "validate_mail()", ...
Then, if your condition function returns false, the form shouldn't be submitted.
Of course, you'll need to modify your validate_mail() function actually test that each form field isn't blank:
if ($('name').value == '' || $('phone').value == '' || ... ) {
alert('Something was blank...');
return false;
} else {
return true;
}
My Prototype syntax is rusty - that should get you on the right track though.

Categories

Resources