jQuery if/else statement to change css on click - javascript

$('#submitbtn').on("click", function() {
$('.message-box').val();
var message = $(".message-box").val();
$('#visible-comment').html(message);
$('.message-box').hide();
return false;
});
I want the above code in an if/else condition that if the value of .message-box is an empty string to change the border color of .message-box to red.
Could someone please guide me in the right direction?
I've tried the following, which changes the border red, but doesn't fire the rest of the code.
$('#submitbtn').on("click", function() {
if ($(".message-box").val("")) {
$(".message-box").css("border","2px solid red");
} else {
$('.message-box').val();
var message = $(".message-box").val();
$('#visible-comment').html(message);
$('.message-box').hide();
return false;
}
});
sample here : https://jsfiddle.net/wf69c7uu/2/

The idea would be to check for your conditions, and then simply add or remove the class based on the evaluation of the expression.
Here is a working demo
The code would look like the following:
$('#submitbtn').on("click", function() {
$('.message-box').val();
var message = $(".message-box").val();
if (message === '') {
$('.message-box').addClass("invalid");
}
else {
$('.message-box').removeClass("invalid");
$('#visible-comment').html(message);
$('.message-box').hide();
}
return false;
});
Or, optionally, you can check the input in "real-time" as the user types like so:
$('#submitbtn').on("click", function() {
$('.message-box').val();
var message = $(".message-box").val();
if (!$(".message-box").hasClass("invalid")) {
$('#visible-comment').html(message);
$('.message-box').hide();
}
return false;
});
$(".message-box").on("input propertychange", function () {
var $this = $(this);
if (!$this.hasClass("invalid") && $this.val() === '') {
$this.addClass("invalid");
}
else if ($this.hasClass("invalid") && $this.val() !== '') {
$this.removeClass("invalid");
}
});

Slightly changed the code which you posted on jsfiddle:
Added an if else block.
Added $('.message-box').css("border", "4px solid red"); to set the border color of the textarea when it's empty.
$(function () {
$('#submitbtn').on("click", function () {
var message = $(".message-box").val();
if (message == "") {
$('.message-box').css("border", "4px solid red");
}
else {
$('#visible-comment').html(message);
$('.message-box').hide();
return false;
}
});
});

Add e.preventDefault function so that your POST action will not be triggered.
Add if/else statement to check if your message box was empty.
$('#submitbtn').on("click", function(e) {
e.preventDefault();
$('.message-box').val();
var message = $(".message-box").val();
if(message == ""){
$(".message-box").css("border","2px solid red");
}else{
$('#visible-comment').html(message);
$('.message-box').hide();
}
});

Related

DOM not being manipulated from inside a function that is being triggered properly

I have written this function to validate that all form fields and check boxes in a form are filled out. The script automatically disables the submit button and then watches for the moment at which it can be re-enabled. My debugger statements are landing me in all of the proper places, but for some reason, the DOM element is not being updated. I'm sure I am just making a stupid mistake, but can't seem to find a solution. Thank you in advance for any help!
Specifically looking at this section:
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
Here is the whole script below.
$(document).ready(function() {
validateInput();
$('.validate').keyup(function(event){
validateInput();
});
$('[type=checkbox]').click(function(event){
validateInput();
});
function validateInput() {
var valid = 0;
var checkBox = $('[type=checkbox]');
var inputFields = $('input.validate');
var inputLength = inputFields.length + checkBox.length;
inputFields.each(function() {
if($(this).val() !== '') {
valid++ ;
}
});
checkBox.each(function() {
if($(this).prop('checked')) {
valid++ ;
}
});
if(valid === inputLength) {
updateBtnStatus('enable')
} else {
updateBtnStatus('disable')
}
}
function updateBtnStatus(status) {
var btn = $('input[type="submit"]');
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
}
});

How can I combine two functions properly on submit

I am new to jQuery and I have the following lines of jQuery. My intention is 'on submit' to check if the input text values are filled and check to see if the radio buttons are checked or selected and make the text red if they aren't but i am not sure on how to combine the two.
Right now it is kind of buggy because it submits IF the text is filled and it ignores the radio buttons BUT it makes the text red before it submits. so it is working just not how I would like it to.
jQuery
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
}
});
Call e.preventDefault() to prevent the normal form submission.
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
e.preventDefault();
}
});
I like to separate my validations into single units and combine them at the end. It makes it easier to read, maintain and test.
$('#form3096').submit(function (e) {
var isFieldPopulated, isRadioChecked;
isFieldPopulated = $('#check-sm input:text').filter(function () {
return $.trim(this.value) !== "";
}).length > 0;
if (!isFieldPopulated) {
$('.social-heading').css('color','red');
}
isRadioChecked = $('input:radio', this).is(':checked');
if (!isRadioChecked) {
$('.radio-options').css('color','red');
}
return isFieldPopulated && isRadioChecked;
});
you can try this
$('#form3096').submit(function (e) {
var len = $('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length;
if (!len) {
$('.social-heading').css('color','red');
e.preventDefault();
}
if(!$('input:radio', this).is(':checked')){
$('.radio-options').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function (e) {
if (!$.trim($('#check-sm input:text').val()) {
$('.social-heading').css('color','red');
return false;
}
if ($('input:radio', this).is(':checked')) {
// everything's fine...
return true;
} else {
$('.radio-options').css('color','red');
return false;
}
});

Jquery if any element in a class meets the condition

I want to check if any element in a class meets certain conditions.
Example.
$(document).on('click','.modalInner_form_nav', function(){
var input = $(this).parents('.modalInner_form').find('.validate_g');
//$(input).each(function(index, element) {
if ($(input).val() == ''){
$(input).css('border', '#BB0000 1px solid');
return false;
}
else {
/////////go to next///////////
if ($(this).parents('.modalInner_form').is(':last-child')){
}
else {
$(this).parents('.modalInner_form').slideUp();
$(this).parents('.modalInner_form').next('.modalInner_form').slideDown();
}
////////////
}
});
This returns false if all input fields are empty, but if one in this class is not empty, it returns true.
The problem is you have a inner function so
$(document).on('click', '.modalInner_form_nav', function () {
var $form = $(this).parents('.modalInner_form');
var $input = $form.find('.validate_g');
var valid = true;
$input.each(function (index, element) {
var $this = $(this)
if ($this.val() == '') {
valid = false;
$this.css('border', '#BB0000 1px solid');
}
});
if (valid) {
if ($form.is(':last-child')) {
//do something else
} else {
$form.slideUp();
$form.next('.modalInner_form').slideDown();
}
}
});
Not really sure what your question is, but here is a way to improve your code.
Save $(this).parents('.modalInner_form') in a variable instead of constantly repeating this same line of code. Then you can replace all those method calls with the variable and just call whatever functions you want on the variable.
var varName = $(this).parents('.modalInner_form');
varName.find('.validate_g');
...
if(varName.is(':last-child')){
...

JavaScript workaround for not supported HTML5 elements and attributes

I am using Modernizr to detect unsupported HTML5 elements and attributes within browsers. If a element/attribute is not supported I like to write a quick workaround with jQuery.
At the moment I am stumbling around the "required" attribute with input element. My thought was to "detect" the associated form element and hook the jQuery .submit() event of the form. But how to do it?
To gain insight yourself here is a sample code how I fixed the "placeholder" attribute with input element:
if(Modernizr.input.placeholder == false) {
alert('input placeholder not exists, perform a workaround...');
$('[placeholder]').each(function() {
var input = $(this);
var placeholder = input.attr('placeholder');
input.bind('focus', function() {
if(this.value == placeholder) {
this.value = '';
$(this).removeClass('mzr-no-placeholder');
}
}).bind('blur', function() {
if(this.value == '') {
this.value = placeholder;
$(this).addClass('mzr-no-placeholder');
}
});
if(!this.value.length) {
this.value = placeholder;
$(this).addClass('mzr-no-placeholder');
}
});
}
else {
alert('input placeholder exists.');
}
Here is the solution
Thanks to greut.
if(Modernizr.input.required == false) {
alert('Tag input required not exists, perform a workaround...');
$('form').submit(function() {
var requirementsOK = true;
$('[required]', this).each(function() {
if(!this.value.length) {
$(this).addClass('mzr-no-required');
requirementsOK = false;
}
else {
$(this).removeClass('mzr-no-required');
}
});
return requirementsOK;
});
}
else {
alert('Tag input required exists.');
}
Here an hint on how to start that:
if (Modernizer.input.required === false) {
$('form').submit(function() {
$('[required]', this).each(function() {
if (!$(this).val()) {
alert('derp!');
return false;
}
}
}
}

Why can't javascript/jquery-feature be applied to multiple nodes?

I have a small javascript that changes the title of a input-field to it's value and some other stuff:
function autoFill(id){
if(jQuery(id).val()==""){
jQuery(id).val(jQuery(id).attr("title"))
.addClass("help");
};
jQuery(id).focus(function(){
if(jQuery(this).val()==jQuery(this).attr("title")){
jQuery(this).val("").removeClass("help");
}
})
.blur(function(){
if(jQuery(this).val()==""){
jQuery(this).val(jQuery(this).attr("title"))
.addClass("help");
}
});
jQuery(".trip").submit(function(){
if(jQuery(id).val() == jQuery(id).attr("title")){
jQuery(id).val('');
}
});
}
When I try to use this script on a class that is on several nodes on one page it only works on the first. For example:
autoFill(".field");
Now I have to make it like this instead:
autoFill("#driver_from");
autoFill("#driver_to");
autoFill("#driver_when");
autoFill("#passenger_from");
autoFill("#passenger_to");
autoFill("#passenger_when");
how do I make it so that it works on every field instead?
Something like this would work:
function autoFill(selector){
jQuery(selector).each(function() {
if(jQuery(this).val() == "") {
jQuery(this).val(jQuery(this).attr("title"))
.addClass("help");
};
jQuery(".trip").submit(function(){
if(jQuery(this).val() == jQuery(this).attr("title")) {
jQuery(this).val('');
}
});
}).focus(function(){
if(jQuery(this).val() == jQuery(this).attr("title")) {
jQuery(this).val("").removeClass("help");
}
}).blur(function(){
if(jQuery(this).val() == "") {
jQuery(this).val(jQuery(this).attr("title"))
.addClass("help");
}
});
}
The important part is the .val() check at the beginning, it's getting the .val() of the first match, you need to handle each separately.
Or, rewrite it as a plugin like this:
(function($) {
$.fn.autoFill = function() {
return this.each(function() {
$(".trip").submit(function(){
if($(this).val() == $(this).attr("title")) {
$(this).val('');
}
});
}).focus(function(){
if($(this).val() == $(this).attr("title")) {
$(this).val("").removeClass("help");
}
}).blur(function(){
if($(this).val() == "") {
$(this).val($(this).attr("title")).addClass("help");
}
}).blur();
};
})(jQuery);
Then you can call it like this:
$(".field").autoFill();

Categories