Form validation within tabs assistance required - javascript

Please see a working demo of my form so far: Demo Fiddle
I have it working so that if you do not fill in the fields it will not allow you to move onto the next tabs. However, if you fail to validate and then fill in the details the boxes stay red. I need some assistance with clearing the queried boxes once you fill them in.
jQuery(document).ready(function($) {
var currentTab;
$(".tabs-menu a, .tab-content .next").click(function(event) {
event.preventDefault();
var $this = $(this),
requiredAreFilled = true,
tab = $this.attr("href") || $this.data('next'),
currentTab = $('.tabs-menu .current').children('a').attr('href');
$(currentTab).find('.required').each(function(index, elt) {
if ($(elt).val() === '') {
requiredAreFilled = false;
$(elt).css('border', '2px solid #FB8183'); // This is bad, should be a class
}
});
var tabLink = $this.is('a') ? $this.parent() : $('.' + tab.substring(1)),
$tabLink = $(tabLink);
console.log($tabLink);
if (requiredAreFilled) {
$tabLink.addClass("current")
.siblings().removeClass("current");
$(".tab-content").not(tab).hide();
$(tab).fadeIn();
}
});
});

Your JSFiddle repaired
.required-error { /* new class */
border: 2px solid #FB8183;
}
jQuery(document).ready(function ($) {
var currentTab;
$(".tabs-menu a, .tab-content .next").click(function (event) {
event.preventDefault();
var $this = $(this),
requiredAreFilled = true,
tab = $this.attr("href") || $this.data('next'),
currentTab = $('.tabs-menu .current').children('a').attr('href');
$(currentTab).find('.required').each(function (index, elt) {
if ($(elt).val() === '') {
requiredAreFilled = false;
$(elt).addClass('required-error'); // This is bad, should be a class
} else {
/* this will fix the "corrected" inputs */
$(elt).removeClass('required-error');
}
});
var tabLink = $this.is('a') ? $this.parent() : $('.' + tab.substring(1)),
$tabLink = $(tabLink);
console.log($tabLink);
if (requiredAreFilled) {
$tabLink.addClass("current")
.siblings().removeClass("current");
$(".tab-content").not(tab).hide();
$(tab).fadeIn();
}
});
});

Just trigger the keyUp event on the input fields to remove the border :)
$('input[type="text"]').keyup(function() {
//remove the border
});
Y don't use a validation plugin, if you already use jQuery?
There are a lot of good Plugins out there:
http://formvalidator.net/
If you use Bootstrap i recommend: http://bootstrapvalidator.com/

Try this : DEMO focusout, DEMO keyup
Basically this js is added :
$(".tab-content").on("focusout",".invalidInput",function() {
if($.trim($(this).val()).length>0)
$(this).removeClass("invalidInput");
});
and used a css class :
.invalidInput{
border : 2px solid #FB8183;
}
This removes the border when the textbox focus is taken away, if you need it to happen as soon as user enters data, use keyup instead of focusout

Related

How to reset or unselect multi select box using jQuery?

I have one bootstrap tab and i create multi select box using jQuery and the all functions are working properly but the RESET button only not working.
i try my all ways but its waste, anyone can you help me..
Please check my full code on fiddle,
MY FULL CODE IS HERE
Just want how to reset the field using jQuery
(function($) {
function refresh_select($select) {
// Clear columns
$select.wrapper.selected.html('');
$select.wrapper.non_selected.html('');
// Get search value
if ($select.wrapper.search) {
var query = $select.wrapper.search.val();
}
var options = [];
// Find all select options
$select.find('option').each(function() {
var $option = $(this);
var value = $option.prop('value');
var label = $option.text();
var selected = $option.is(':selected');
options.push({
value: value,
label: label,
selected: selected,
element: $option,
});
});
// Loop over select options and add to the non-selected and selected columns
options.forEach(function(option) {
var $row = $('<a tabindex="0" role="button" class="item"></a>').text(option.label).data('value', option.value);
// Create clone of row and add to the selected column
if (option.selected) {
$row.addClass('selected');
var $clone = $row.clone();
// Add click handler to mark row as non-selected
$clone.click(function() {
option.element.prop('selected', false);
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$clone.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', false);
$select.change();
}
});
$select.wrapper.selected.append($clone);
}
// Add click handler to mark row as selected
$row.click(function() {
option.element.prop('selected', 'selected');
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$row.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', 'selected');
$select.change();
}
});
// Apply search filtering
if (query && query != '' && option.label.toLowerCase().indexOf(query.toLowerCase()) === -1) {
return;
}
$select.wrapper.non_selected.append($row);
});
}
$.fn.multi = function(options) {
var settings = $.extend({
'enable_search': true,
'search_placeholder': 'Search...',
}, options);
return this.each(function() {
var $select = $(this);
// Check if already initalized
if ($select.data('multijs')) {
return;
}
// Make sure multiple is enabled
if (!$select.prop('multiple')) {
return;
}
// Hide select
$select.css('display', 'none');
$select.data('multijs', true);
// Start constructing selector
var $wrapper = $('<div class="multi-wrapper">');
// Add search bar
if (settings.enable_search) {
var $search = $('<input class="search-input" type="text" />').prop('placeholder', settings.search_placeholder);
$search.on('input change keyup', function() {
refresh_select($select);
})
$wrapper.append($search);
$wrapper.search = $search;
}
// Add columns for selected and non-selected
var $non_selected = $('<div class="non-selected-wrapper">');
var $selected = $('<div class="selected-wrapper">');
$wrapper.append($non_selected);
$wrapper.append($selected);
$wrapper.non_selected = $non_selected;
$wrapper.selected = $selected;
$select.wrapper = $wrapper;
// Add multi.js wrapper after select element
$select.after($wrapper);
// Initialize selector with values from select element
refresh_select($select);
// Refresh selector when select values change
$select.change(function() {
refresh_select($select);
});
});
}
})(jQuery);
$(document).ready(function() {
$('select').multi({
search_placeholder: 'Search',
});
});
/* Reset button */
function DeselectListBox() {
var ListBoxObject = document.getElementById("firstData")
for (var i = 0; i < ListBoxObject.length; i++) {
if (ListBoxObject.options[i].selected) {
ListBoxObject.options[i].selected = false
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can trigger the click of your reset button and clear the whole div in your document ready function. After this you can remove the class "selected" so its completely reset.
Like this
$(document).ready(function() {
$('select').multi({
search_placeholder: 'Search',
});
$('#tabReset').click(function() {
$('.selected-wrapper').empty();
$('a').removeClass('selected');
});
});
attach an event to reset button. empty the selected-wrapper and remove the selected class from non-selected-wrapper
$("button.alltabreset").click(function(){
$(".selected-wrapper").empty();
$(".item").removeClass("selected");
});
solution: https://jsfiddle.net/zuov3wmb/

Get Bouncy Content Filter to run automatically

I'm using this awesome bouncy filter from Codyhouse but i can't for the life of me figure out how to make it run automatically i.e flip on its own and still accept user click events. The jsfiddle...Thanks.
jQuery(document).ready(function($) {
//wrap each one of your filter in a .cd-gallery-container
bouncy_filter($('.cd-gallery-container'));
function bouncy_filter($container) {
$container.each(function() {
var $this = $(this);
var filter_list_container = $this.children('.cd-filter'),
filter_values = filter_list_container.find('li:not(.placeholder) a'),
filter_list_placeholder = filter_list_container.find('.placeholder a'),
filter_list_placeholder_text = filter_list_placeholder.text(),
filter_list_placeholder_default_value = 'Select',
gallery_item_wrapper = $this.children('.cd-gallery').find('.cd-item-wrapper');
//store gallery items
var gallery_elements = {};
filter_values.each(function() {
var filter_type = $(this).data('type');
gallery_elements[filter_type] = gallery_item_wrapper.find('li[data-type="' + filter_type + '"]');
});
//detect click event
filter_list_container.on('click', function(event) {
event.preventDefault();
//detect which filter item was selected
var selected_filter = $(event.target).data('type');
//check if user has clicked the placeholder item (for mobile version)
if ($(event.target).is(filter_list_placeholder) || $(event.target).is(filter_list_container)) {
(filter_list_placeholder_default_value == filter_list_placeholder.text()) ? filter_list_placeholder.text(filter_list_placeholder_text): filter_list_placeholder.text(filter_list_placeholder_default_value);
filter_list_container.toggleClass('is-open');
//check if user has clicked a filter already selected
} else if (filter_list_placeholder.data('type') == selected_filter) {
filter_list_placeholder.text($(event.target).text());
filter_list_container.removeClass('is-open');
} else {
//close the dropdown (mobile version) and change placeholder text/data-type value
filter_list_container.removeClass('is-open');
filter_list_placeholder.text($(event.target).text()).data('type', selected_filter);
filter_list_placeholder_text = $(event.target).text();
//add class selected to the selected filter item
filter_values.removeClass('selected');
$(event.target).addClass('selected');
//give higher z-index to the gallery items selected by the filter
show_selected_items(gallery_elements[selected_filter]);
//rotate each item-wrapper of the gallery
//at the end of the animation hide the not-selected items in the gallery amd rotate back the item-wrappers
// fallback added for IE9
var is_explorer_9 = navigator.userAgent.indexOf('MSIE 9') > -1;
if (is_explorer_9) {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
} else {
gallery_item_wrapper.addClass('is-switched').eq(0).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
});
}
}
});
});
}
});
function show_selected_items(selected_elements) {
selected_elements.addClass('is-selected');
}
function hide_not_selected_items(gallery_containers, filter) {
$.each(gallery_containers, function(key, value) {
if (key != filter) {
$(this).removeClass('is-visible is-selected').addClass('is-hidden');
} else {
$(this).addClass('is-visible').removeClass('is-hidden is-selected');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm assuming by "make it run automatically" you're talking about triggering the content-selection animation programatically, rather than requiring a user click. One possible solution is to assign an id to the selection elements, and then register the click handler directly to those elements, rather than the parent filter_list_container. Then, you can use jQuery's trigger() method to simulate a click on the appropriate element.
Assign an id in the html like this:
<a id="green" href="#0">Green</a>
Then register the click handler like this:
$("#red, #green, #blue").on('click', function(event){ ... }
...and trigger like this:
$("#green").trigger("click");
Here's a JSfiddle with an example.

jQuery: check if element has specific style (not inline)

Is it possible to check via jQuery or vanilla JS if an element has a specific style?
In my case I want to check if any input-fields on the page have a red border — applied via an external CSS-File. No inline-css and no style-attr is available, styling is completely external.
For my initial testing I got the following code from this StackOverflow-Answer: https://stackoverflow.com/a/29659187
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).css('border-color') === 'rgb(255,0,0)'
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
… but .css seams to only test inlineStyles.
Update
I can't change HTML, the markup has to stay «as is». The red border is coming through css only. Like this: https://jsfiddle.net/z3t6k04s/
Try it like this:
$('.formValidation input[type=submit]').on('click',function(e){
// Prevent Default Form Submit
e.preventDefault();
// Define Global if Invalid Fields Exist
var hasInvalidInputs = false;
// Run Through all to check Input Fields
$('input').filter(function(index){
// Check if Invalid Inputs already got detected. If not - check if this field is red
if( !hasInvalidInputs )
hasInvalidInputs = $(this).css('border-color') == 'rgb(161, 0, 0)'; // If field is red -> update global var to true
});
// Check if Invalid Fields are set to true
if (hasInvalidInputs) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
You could use
Window.getComputedStyle()
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
Example:
var inp = document.getElementsByTagName('input')[0];
var style = window.getComputedStyle(inp, null);
console.log(style.getPropertyValue("border-color"))
input[type='text'] {
border: 1px solid rgb(255, 0, 0);
}
<input type="text" value="Foo" />
Create a one class which has a red color
like
.red-color{
border-color:red;
}
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).hasClass('red-color');
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
I hope this will helpful to you.
You can use below code
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var isValid;
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
element.css('border-color','red');
}else{
isValid = true;
element.css('border-color','');
}
});
if (isValid==false) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});

jQuery mouseenter functions - changing colour if colour isn't already

So, I am not that fluent with jQuery and I have written a bit of code in it that doesn't look as if it works. Here is my code;
$(document).ready(function() {
$("#loginSelector").mouseenter(function() {
if $("#loginSelector").style.backgroundColor != "#3064CA" {
$("#loginSelector").style.backgroundColor = "#3064CA";
};
});
$("#loginSelector").mouseleave(function() {
if $("#loginSelector").style.backgroundColor != "#5990DE" {
$("#loginSelector").style.backgroundColor = "#5990DE";
};
});
$("#signupSelector").mouseenter(function() {
if $("#signupSelector").style.backgroundColor != "#3064CA" {
$("#signupSelector").style.backgroundColor = "#3064CA";
};
});
$("#signupSelector").mouseleave(function() {
if $("#signupSelector").style.backgroundColor != "#5990DE" {
$("#signupSelector").style.backgroundColor = "#5990DE";
};
});
});
All I want the code to do is check to see if the button is not a certain colour, and if it isn't that colour and it is hovered on, it changes to another colour.
Try this and follow the same for the rest of the blocks.
$("#loginSelector").mouseenter(function() { //when hovered on
var desiredColor = "#3064CA"; //define the desired color
if ( $(this).css('color') === desiredColor) return; //if the element's color = the desired color, don't do anything. stop the execution
$(this).css('color', desiredColor); //else set the desired color
});
Assuming the elements initially have the color #5990DE, I'd simply add the following css:
#loginSelector, #signupSelector{
background: #5990DE;
}
#loginSelector:hover, #signupSelector:hover{
background: #3064CA;
}
Or if otherwise,
css:
.onHover{
background: #3064CA;
}
.onLeave{
background: #5990DE;
}
script:
$(document).on('mouseenter', 'loginSelector , #signupSelector', function(){
$(this).addClass('onHover').removeClass('onLeave');
});
$(document).on('mouseleave', '#loginSelector , #signupSelector', function(){
$(this).addClass('onLeave').removeClass('onHover');
});

show/hide div when user inputs text into text area?

I am trying to toggle a div so it shows and hides when a user enters text into textarea.
i am using the below code and its not working for me, can anyone please show me why? thanks
html:
<head>
<script>
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').toggle("slow");
}
});
});
</script>
</head>
<form>
<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>
css:
#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;
}
so apparently my above code doesnt work in IE 9, but i should be able to achieve what i am trying to do by using this code, but can someone please show me where i place my div ID/how i adapt it to work for me?
var activeElement = null;
var activeElementValue = null;
// On focus, start watching the element
document.addEventListener("focusin", function(e) {
var target = e.srcElement;
if (target.nodeName !== "INPUT") return;
// Store a reference to the focused element and its current value
activeElement = target;
activeElementValue = target.value;
// Listen to the propertychange event
activeElement.attachEvent("onpropertychange", handlePropertyChange);
// Override .value to track changes from JavaScript
var valueProp = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value');
Object.defineProperty(activeElement, {
get: function() { return valueProp.get.call(this); },
set: function(val) {
activeElementValue = val;
valueProp.set.call(this, val);
}
});
});
// And on blur, stop watching
document.addEventListener("focusout", function(e) {
if (!activeElement) return;
// Stop listening to propertychange and restore the original .value prop
activeElement.detachEvent("onpropertychange", handlePropertyChange);
delete activeElement.value;
activeElement = null;
activeElementValue = null;
});
function handlePropertyChange(e) {
if (e.propertyName === "value" &&
activeElementValue !== activeElement.value) {
activeElementValue = activeElement.value;
// Fire textchange event on activeElement
}
};
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').show();
} else {
$('#cname2').hide();
}
});
});
One possible approach (demo):
$(document).ready(function() {
$("#cname").on('input', function() {
$('#cname2')[this.value.length > 8 ? 'hide' : 'show']('slow');
});
});
Here I assumed that in cname2 container there's some warning message, that has to be shown if length of text input is 8 or less characters. Note also that I've used oninput handler, not keyup: as it allows me to process mouse-driven cut-and-paste as well as direct input. The only drawback is that IE8 doesn't support this event (and IE9 support for it is rather buggy, as handler is not fired when character is removed from text input).
Use this Javascript function
var z = document.getElementById('cname');
z.onkeyup = function(){
document.getElementById('cname2').innerHTML = z.value;
}
Your HTML:
<input type='text' name='cname' class='field' id='cname'>
<div class='cname2' id='cname2'></div>
Checkout here: http://jsfiddle.net/iamsajeev/Q9LPv/
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').fadeIn("slow");
}
else
{
$('#cname2').fadeOut("slow");
}
});
});
http://jsfiddle.net/5EjP7/2/
I hope that helps
Try the following script:
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').toggle("slow");
}
});
});

Categories