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!');
}
});
Related
I have a table and I iterate through each row.
If the row background color is green and its respective checkboxes with class as linebox are not checked I am supposed to display an error message on click of submit.
But the return false is not working and the form is getting submitted.Though the message is getting displayed.
How do I resolve this?
Below is the code.
jQuery(document).on('click', '#add-All-button', function () {
$(".rowb").each(function() {
if($(this).css("background-color") == "rgb(71, 163, 71)") {
var ischk = 0;
var row = $(this);
if (row.find('input[class="linebox"]').is(':checked') ) {
ischk++;
}
if(ischk==0) {
alert('Every green colored row should have one of the checkboxes checked.');
return false;
}
}
});
});
You're not returning false out of your event handler, just out of your $.each callback. If you want to also return false out of your handler, you'll need a return statement in the handler itself.
For instance, perhaps (see the *** lines):
jQuery(document).on('click', '#add-All-button', function() {
var rv; // *** By default it's `undefined`, which has no special meaning, so that's fine
$(".rowb").each(function() {
if ($(this).css("background-color") == "rgb(71, 163, 71)") {
var ischk = 0;
var row = $(this);
if (row.find('input[class="linebox"]').is(':checked')) {
ischk++;
}
if (ischk == 0) {
alert('Every green colored row should have one of the checkboxes checked.');
rv = false; // ***
return false;
}
}
});
return rv; // ***
});
Side note: This comparison is likely to fail in the wild:
$(this).css("background-color") == "rgb(71, 163, 71)"
Different browsers return color information in different formats, and don't return the value in the same format you set it in (necessarily). jQuery doesn't attempt to standardize this. So the value you get back might be "rgb(71, 163, 71)", but it might also be "rgb(71,163,71)" or "rgba(71, 163, 71, 0)" or "rgba(71,163,71,0)" or even "#47A347". Instead of relying on getting back a value in a specific format, you'd probably be better off using a data-* attribute or a value tracked via the jQuery data function instead.
Side note 2: I wouldn't use the click event of a button to hook into the form submission process; I'd use the submit event of the form instead.
You need to return false in the outer function, returning false in .each will only break the loop. The other you may need to use to stop a form submission is event.preventDefault which can be used to stop the browsers default behavior like going to a link or submitting a forming but you'll need to change the event type on your button to match this appropriately. That is to say that the event you should be listening for is submit. Have a look at the fixed up code below for more details.
jQuery(document).on('submit', '#add-All-button', function() {
var out = true;
$(".rowb").each(function() {
if ($(this).css("background-color") == "rgb(71, 163, 71)") {
var ischk = 0;
var row = $(this);
if (row.find('input[class="linebox"]').is(':checked')) {
ischk++;
}
if (ischk == 0) {
alert('Every green colored row should have one of the checkboxes checked.');
out = false;
}
}
});
if (!out) { event.preventDefault(); }
return out;
});
Currently my code checks for input in the textareas on the site. If I leave all of them blank, they all get highlighted red when I press the button, which is expected. But, when I enter text into 1 or more boxes, it just passes through.
It isn't checking all the boxes everytime I press the button, it validates the submit if 1 box has text in it. What is wrong with the js code?
$(window).load( function () {
$('#form1').on('submit', function(event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
});
function validate() {
var success = true;
// Verify that the user entered some special instructions (we only take special orders!)
var inputarea = $('.input');
for(var i = 0; i < inputarea.length; i++)
{
if(inputarea.val() === "")
{
console.log("Missing textarea input");
success = false;
//NEED TO CHANGE THE LINE BELOW SO IT WONT SHOW TEXT, JUST CHANGE BORDER COLOUR
$('.input').css("border","1px solid red");
}
}
return success;
}
});
http://jsfiddle.net/originalwill/5cw1a2c2/
The link won't show my error because it is based on a button request using a form, so it won't work in jsFiddle.
I believe the following would be a better solution:
function validate() {
var success = true;
// Verify that the user entered some special instructions (we only take special orders!)
$('.input').each(function(i, item) {
if ($(item).val() === "") {
console.log("Missing textarea input");
success = false;
//NEED TO CHANGE THE LINE BELOW SO IT WONT SHOW TEXT, JUST CHANGE BORDER COLOUR
$(item).css("border","1px solid red");
}
});
return success;
}
In your original code, you had the statement:
if (inputarea.val() === "")
Notice that this had no relationship to your indexing through the array. It might have worked with something like the following:
if ($(inputarea.get(i)).val === "")
which would have obtained the element for the i'th entry and then retrieved its value but I believe the jQuery.each() function is superior for your task.
A sample jsFiddle is provided.
in native javascript
var inputarea = documen.getElementsByClassName('input');
for(var i = 0; i < inputarea.length; i++)
{
if(inputarea[i].value === "")
{
console.log("Missing textarea input");
success = false;
inputarea[i].style.border='1px solid red';
// or inputarea[i].style = 'border:1px solid red;';
}
}
in Jquery i think this will work
$('.input').each(function(i, item) {
if ($(item).val() === "") {
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}else{
$(item).removeAttr('style')
// to remove border
}
});
I have a webform with a control panel (#pnlStepOne). The panel includes two textfields "txtFname" and "txtLname". I have a validator setup for each textfield. I have tested the form and all works as desired.
My questions is how do I add a jQuery effect to the panel onclick event only if one (or both) of the textfields ("txtFname" and "txtLname") don't validate. (this effect would "shake" the panel).
And I would like to add another jQuery effect to "flip" the control panel and switch the current one (#pnlStepOne) for another one (#pnlStepTwo) if both fields are validated by the asp:RequiredFieldValidators.
Just a sample code that I will tweak once I have the right If condition.
$(document).ready(function () {
$("#btnStepOne").click(function (event) {
if (**this is the condition that I am missing**)
{
$('#pnlStepOne').css({
background: 'red',
});
}
});
});
You can modify your code to be like this:
$(document).ready(function () {
$("#btnStepOne").click(function (event) {
var fvFname = document.getElementById('client-id-of-your-fvFname-validator');
var fvLname = document.getElementById('client-id-of-your-fvLname-validator');
ValidatorValidate(fvFname);
ValidatorValidate(fvLname);
if (!fvFname.isvalid || !fvLname.isvalid) {
$('#pnlStepOne').css({
background: 'red',
});
}
});
});
Have a rad of my answer to a similar question here:
Enable/Disable asp:validators using jquery
Which has the MSDN link here: http://msdn.microsoft.com/en-us/library/aa479045.aspx
In one of my projects I use a prettifyValidation function, so you could have something like:
$(document).ready(function () {
$("#btnStepOne").click(function (event) {
prettifyValidation();
});
});
function prettifyValidation() {
var allValid = true;
if (typeof Page_Validators != 'undefined') {
// Loop through from high to low to capture the base level of error
for (i = Page_Validators.length; i >= 0; i--) {
if (Page_Validators[i] != null) {
if (!Page_Validators[i].isvalid) { // The Control is NOT Valid
$("#" + Page_Validators[i].controltovalidate).removeClass("makeMeGreen").addClass("makeMeRed");
allValid = false;
} else { // Control is valid
$("#" + Page_Validators[i].controltovalidate).removeClass("makeMeRed").addClass("makeMeGreen");
};
};
};
};
}
This will loop through all controls on the page that have an ASP.NET validator attached, and then add or remove a class depending if they are valid or not.
Obviously from here you can limit the function to a specific control by matching the controlToValidate property, and you can restyle, add controls, change classes but this should hopefully provide you a decent base to work from.
$(document).ready(function () {
$("#bcscan").submit(function (e) {
e.preventDefault();
if($("select").val() === '#') {
$(this).addClass("warning");
}
else {
ajaxPost();
}
});
});
I'm using following function, how can I modify it to add class warning, if one of select element's value = "#"?
Currently it's adding warning class to all selects
I think this may be what you want:
$('select').filter(function() {
return ($(this).val() === '#');
}).addClass('warning');
That selects all select elements, filters it down to those elements whose current value is equal to #, then adds the warning class to that subset.
I'll leave my original answer here, though given the changes to the question it's likely no longer relevant. This is my last stab at guessing what it is you want - if this is useful to you, great; if not, oh well.
$(document).ready(function () {
$("#bcscan").submit(function (e) {
e.preventDefault();
var doAjaxPost = true;
$('select').each(function() {
if($(this).val() === '#') {
doAjaxPost = false;
$(this).addClass('warning');
}
});
if(doAjaxPost) {
ajaxPost();
}
});
});
That checks all select elements when the form is submitted - if any of them have a value of # it adds the warning class to that select element. If none of them have a value of # it goes ahead and calls the ajaxPost() function.
$('select').change(function (event) {
if ($(this).val() === '#') $(this).addClass('warning');
});
this is populated with the element that fired the event. In this case the select.
Demo: http://jsfiddle.net/TimWolla/tNhKe/
Edit to match the question:
$(document).ready(function () {
$("#bcscan").submit(function (e) {
e.preventDefault();
var invalidCount = $('select').filter(function() {
return ($(this).val() === '#');
}).addClass('warning').length;
if (invalidCount == 0) {
alert('valid');
}
});
});
Demo: http://jsfiddle.net/TimWolla/QxBH9/
if($("select:selected").val() == '#') {
$("select").addClass("warning");
}
http://api.jquery.com/selected-selector/
Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);