Removing a class from all input elements - javascript

I want to remove a class from my input elements.I'm using Data Annotations in MVC and unobtrusive javascript for validation,anyway, when user clicks submit button I want to remove valid class from all input elements, because it change all unnecessary input's (non-required) valid (green border color) and it's not looking good.Anyway, I try this:
$("#submitBtn").click(function () {
if ($(".input-validation-error").length == 0) { // if there is no error
$(this).button('loading');
} else {
$("input").each(function () {
$(this).removeClass("valid");
});
}
And it didn't work, also tried:
$("input").removeClass("valid");
It didn't work either.And I thought maybe it's working before the validation and valid class adding after the click event automatically.So I try this:
setInterval(function() {
$("input").each(function() {
$(this).removeClass("valid");
});
}, 1000);
But still no success. I don't know jQuery very well, probably I'm missing something simple.What is the problem?

if the class is attached to the input element then it should be as simple as
$("input.valid").removeClass('valid')
As it turned out OP didn't want the valid highlight to be applied so setting the validClass to '' fixed it
For the page the default validClass was set using
jQuery.validator.setDefaults({ validClass: '' });

Try to wrap your code inside DOM ready:
$(document).ready(function() {
$("#submitBtn").click(function () {
if ($(".input-validation-error").length == 0) { // if there is no error
$(this).button('loading');
} else {
$("input").each(function () {
$(this).removeClass("valid");
});
}
})

Check out this fiddle:
http://jsfiddle.net/dwQb4/1/
$("input").removeClass("valid");
There are 3 inputs with class="valid" that turns them green and some jquery to remove the class
this may help you

Related

How change the css with the checkbox with different names?

Currently, I have multiple checkbox inputs with different names(checkit, checktype, checklog) assigned to the inputs.
What I want to do is to have each checkbox to change the color of the background when checked.
However, I dont know how I can assign each one of the checkbox to do some tasks without duplicating the following code ?If possible some examples or tips will be great! I would love to hear from you .
Should I remove name="checkit" if I want to make all the inputs do the same thing? What if I want them to do some slightly different things?
$('input[name="checkit"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Add the following by , or give some class name to it
$('input[name="checkit"], input[name="checktype"], input[name="checklog"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Don't use the name atrribute in jQuery and add a common class to each checkbox for a common functionality and access it with class selector in jQuery as shown below.
If you want to do something different with different checkboxes apart from this, then you can add more jQuery code for that specific input tag. It will not affect this code.
$('input.someClass').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
You can remove the name part from the selector and add selector for input[type='radio']. And if you want to add a bit different logic (I think you mean different classes), you can get the name of the current checked checkbox and use it to make your logic. Something like this
$('input[type="radio"]').change(function () {
var checkboxName = $(this).prop('name');
// if(checkboxName === .....)
});
Updated according to the comment
$('input[name="checkit"], input[name="checktype"], input[name="checklog"]').change(function () {
var checkboxName = $(this).prop('name');
// .............
});
$('input[type="checkbox"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Use
$('input[type="checkbox"]')
instead of
$('input[name="checkit"]')

JavaScript - If checkbox is disabled, add class using jQuery

I'm having a problem with the syntax (or maybe with the selectors) on my code. See the demo.
I tried the following code but the results does nothing.
#1. hasAttribute():
if ($('input[type=checkbox]').hasAttribute("disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#2. is():
if ($('input[type=checkbox]').is("[disabled]")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
// ------------------------------------------------
if ($('input[type=checkbox]').is(":disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#3. prop():
if ($('input[type=checkbox]').prop("disabled", true)) {
$(this).closest('.chkbox').addClass("is-disabled");
}
So then I think the problem is on the line:
$(this).closest('.chkbox').addClass("is-disabled");
Any idea?
Thanks.
You can use :disabled selector
see here
You're using $(this) without declaring anything. Thats the reason it's not working. It works in the second example because of the .change() function gives the context of the 'thing' (this) that is changing.
This code should work as you desire.
$(function() {
// Grab all inputs with the type checkbox.
var input = $('input[type=checkbox]')
// Check for each of the input fields (i, el stands for index, element)
input.each(function(i, el) {
// Does it have the attribute disabled?
if(el.hasAttribute('disabled')) {
// Add the class 'is-disabled'
$(el).closest('.chkbox').addClass('is-disabled')
}
})
$('input[type=checkbox]').change(function(){
if ($(this).is(":checked")) {
$(this).closest('.chkbox').addClass("is-checked");
} else {
$(this).closest('.chkbox').removeClass("is-checked");
}
});
});

Using jQuery $(this) to select anything in this form

have multiple forms on one page but all with the same class name.
I want to make it so that if there is no content in the text area, the submit button is disabled.
This works as you can see here i have done that:
http://jsfiddle.net/WJnqw/
However, this obviously will affect all of the forms with the same submit button classname.
I have tried changing the code to include e.g:
$(this).find(".addcommentbutton").prop("disabled", true);
As i thought that would select the form, and find the add comment button.
But it doesnt work.
Any help?
Thanks!
The problem is that this was the window. You need to pass the context somehow.
Here's a working version that shows two ways of either specifying what this in the function refers to or letting jquery do it:
http://jsfiddle.net/LVf5w/
$(document).ready(function () {
$('.addpostcomment').each(function() {
disableComments.call(this); // specify what "this" will be in the function
});
$(".addpostcomment").keyup(disableComments); //let jquery specify that "this" will be the element
});
function disableComments() {
$(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);
};
You could also just do this instead of iterating and calling the function:
http://jsfiddle.net/LX2Dj/
$(document).ready(function () {
$(".addpostcomment").keyup(disableComments).trigger('keyup');
});
Or (my preference) do away with the anonymous function altogether:
http://jsfiddle.net/sfuHU/
$(document).ready(function () {
$(".addpostcomment").keyup(function() {
$(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);
}).trigger('keyup');
});
Note that you have duplicate ids on your elements. The id must be unique.
JSFIDDLE DEMO
You need to use .next() not find & also use this directly in the keyup event
$(this).next('.addcommentbutton').prop('disabled', !($(this).val().length > 0));
// comment form not allow submit when empty
$(document).ready(function () {
disableComments();
$( ".addpostcomment" ).keyup(function() {
$(this).next('.addcommentbutton').prop('disabled', !($(this).val().length > 0));
});
});
function disableComments() {
var commentLength = $('.addpostcomment').val().length;
if (commentLength < 1) {
$(".addcommentbutton").prop("disabled", true);
} else {
$(".addcommentbutton").prop("disabled", false);
}
};

Global click event blocks element's click event

This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.

how to apply function to each checkbox on page?

I am trying to apply a function to every checkbox on a page that shows/hides <div class="selectlist"> depending on if the checkbox is checked, this function makes all the <div class="selectlist"> on the page toggle
$("input[type=checkbox]").live('change', function() {
if ($(this).is(':checked') == false) {
$('#selectlist').hide();
} else {
$('#selectlist').show();
}
});
I tried the jquery each function like this but that doesnt seem to work
$.each($("input[type=checkbox]").live('change', function() {
if ($(this).is(':checked') == false) {
$('#selectlist').hide();
} else {
$('#selectlist').show();
}
}));
I know its possible to this by using a class instead of input[type=checkbox] but I want to avoid doing that
How can I make jquery change the behavior of the checkbox the user clicks?
If you're trying to bind an event handler to all elements verifying input[type=checkbox], simply do
$(document).on('change', "input[type=checkbox]", function() {
if (!this.checked) {
$('#selectlist').hide();
} else {
$('#selectlist').show();
}
});
No need to use each there : most jQuery functions work if the jQuery set contains more than one element.
Note that I use on there instead of live : after having been deprecated for a long time, live has been removed from recent versions of jQuery.
EDIT : discussion in comments below lead to this code :
$(document).on('change', "input[type=checkbox]", function() {
$(this).next().toggle(this.checked);
});
$(document).on('change', 'input[type=checkbox]', function() {
$('#selectlist').toggle(this.checked);
});
ID's are uniqe, and there is no "all the <div id="selectlist"> on the page toggle", there can be only one? Use a class instead, and show us what the markup looks like !

Categories

Resources