value-attribute seems not to show input-field-content - javascript

I'm trying to use jquery to check if every input-field has already been filled out. And if yes, I'd like to make a green border around the form.
This was my approach:
if($('input:text[value=""], textarea[value=""]').length == 0){
alert("DONE");
}
Hovever the value="" -Selector doesn't work.
It seems that the value-attribute only contains the input-field's default-value, but not the actual content inserted by the user - according to firebug.
This command alerts me the actual contents:
$('input:text[value!=""]').each(function(){
alert($(this).val());
});
My Question: Where are the actual input-field contents stored? And how can I use jQuery to check efficiently, if there are empty fields?

You are right, the attribute selectors only work with the value the attribute really has. Later on, changing the value of the input will only change the DOM element's internal state.
Where are the actual input-field contents stored?
You can access the value via the value property of the DOM element elementNode.value.
And how can I use jQuery to check efficiently, if there are empty fields?
You can use .filter:
$('input').filter(function() {
return !this.value;
});

A neat way of validating inputs is to attach a validation rule to the element for your script to find and validate against.
To make a field required:
<input type="text" data-validate="required" />
Your script:
$('[data-validate]').each(function() {
var rule = $(this).attr('data-validate'), value = $(this).val();
switch (rule) {
case 'required':
if (!value) {
alert('Field invalid!');
}
break;
}
});
It works pretty well for me.
You can make it more efficient by selecting only specific element types or children of a specific element (such as a form).

You could try using .filter() like this:
var empty = $('input:text').filter(function(){ return $(this).val() == "" }).length;
if(empty > 0){
alert("There are "+empty+" fields which have not been filled out");
}

my approach if you are not willing to use Jquery validate.
give a class to each of your input fields and then use Jquery class selector to test if those all have filled or not. You can use this even for dropdown too.

You should use this construction:
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
if (incomplete) {
alert('Please fill all fields!');
}
:input selector selects all input, textarea, select and button elements.
Read this: http://api.jquery.com/input-selector/

Related

Resetting specific form input with jQuery

I currently have a radio that displays an additional input field if clicked and hides that input field if another radio is selected. What I am looking to accomplish is that when another radio input is clicked i'd like to clear that text input of any value that was put in it.
I am also utilizing MUI CSS for floating labels on form inputs which appends the .mui--is-empty class to fields that are empty and .mui--is-not-empty class to fields that contain values.
I've tried the following:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'tip-custom') {
$('#show-me').fadeIn();
} else {
$('#show-me').fadeOut();
$('input[name=tip-custom-value').val('');
}
});
});
But this just sets the value to "" where I need to completely reset this specific field for the .mui--is-empty to append back to it.
Here's is a gyazo of what I am experiencing which you can see the starting state of the floating label and how it reacts when cleared.
https://gyazo.com/b848a5855d27b2d6ebd9202bda7fabe9
Is there a way to completely reset the text input as if there is actually no value?
UPDATE
I was able to accomplish what I was trying to do with the following script:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if(this.id == 'tip-custom') {
$('#show-me').fadeIn();
}
else {
$('#show-me').fadeOut();
$('input[name=tip-custom-value').val(null).removeClass('mui--is-not-empty').addClass('mui--is-empty');
}
});
});
But i'm concerned that even if the value is set to '' will it return anything on form submit? I would prefer that if there is no actual value that it did not.
I'm not sure my answer is right or wrong because I cant check part of the code. I think you have a typo in your code. So, I think I could fix it. Please, check this code if it works:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if(this.id == 'tip-custom') {
$('#show-me').fadeIn();
}
else {
$('#show-me').fadeOut();
$('input[name="tip-custom-value"]').val(null).removeClass('mui--is-not-empty').addClass('mui--is-empty');
}
});
});
The typo was inside else statement. I think you forgot to close square brackets for your code.
I hope it works.

Empty all fields except one

I am trying to clear all text except one field using js
Used below code :
$('input[type=text]').each(function(){
if ($(this).hasClass('.isMobile').length < 0) {
$(this).val('');
}
});
$(this).hasClass('.isMobile').length used this to check particular field has some class.
But $(this).hasClass('.isMobile').length showing undefined every time.
You don't need a loop for that, you only need to narrow down your jQuery selector :
$('input[type=text].isMobile').val('');
If you want to exclude the input with the class isMobile instead :
$('input[type=text]:not(.isMobile)').val('');

jQuery Form Validator - How to change the data-validation-optional property using javascript?

I'm currently using jQuery Form Validator (http://formvalidator.net/#home). I currently have three input boxes that take in a phone number (3 numbers, 3 number, 4 numbers). Since the phone number is optional, all three input boxes are optional (data-validation-optional = "true"). Validation (making sure only numbers are entered) works fine for all three boxes but my problem is that the validation plugin doesn't check to make sure all three boxes are filled in. This is a problem because a user can fill in one box but leave the other two empty.
The way I can solve this is to check if all three boxes have an empty string when the form is submitted. If so than do nothing, but if only one box is submitted than make all three boxes mandatory (data-validation-optional = "false").
I'm having trouble changing the inline data-validation-optional property of an input using JavaScript. When I use document.getElementById("phone1").data-validation-optional = "false" it gives me a javascript error.
Here is my current code:
input:
<input type="text" id="phone1" name="phone1" tabindex="21" maxlength="3" value="" data-validation="custom" data-validation-regexp="^([0-9]{3})$" data-validation-optional="true" style="position:relative; display:block; left:24px; top:31px; width: 76px; height: 44px; text-align: center; padding-left: 0px;" data-validation-error-msg="- Mobile # is incorrect.">
javascript:
$('#phone1')
.bind('validation', function() {
if(String(document.getElementById('phone1').value) == "" &&String(document.getElementById('phone2').value) == "" && String(document.getElementById('phone3').value) == ""){
//return true - all empty
document.getElementById("phone1").data-validation-optional = "true";
}
else{
if(String(document.getElementById('phone1').value) == "" || String(document.getElementById('phone2').value) == "" || String(document.getElementById('phone3').value) == ""){
document.getElementById("phone1").data-validation-optional = "false";
//return false - at least one is empty
}
else{
document.getElementById("phone1").data-validation-optional = "true";
//return true - all filled
}
}
})
Any help would be appreciated! Thanks!
Try
$("#phone1").data('validation-optional') = "true";
or
$("#phone1").data('validation-optional') = true;
Both will address the data item set with data-validation-optional="..." though I'm not sure whether validation will be affected. I can't find any evidence of a 'validation' event for individual form elements, nor can I find evidence that the validation plugin will respond to hot-swapping of data properties. You may also need to 'destroy' then re-invoke the plugin.
The problem you are having is you aren't accessing the data attributes the correct way. I notice you're using jQuery, so you might as well leverage it. In jQuery, you can use .attr() and .data() to access data attributes.
$('#phone1').attr('data-validation-optional', 'true');
Victorjonsson's validator accesses the data-validation-*="" attributes using .attr(), so don't use .data() to change them, because values set with data() cannot be accessed with .attr(). The reverse is also true.
Upside of this approach is you won't need to re-initialize the plugin every time you change something.
If you'd prefer to not use jQuery and opt for vanilla javascript, you use el.getAttribute('data-foo'); and el.setAttribute('data-foo', 'bar'); to access your data attributes. See this answer for more on that.
In your case, the code should be:
document.getElementById('phone1').setAttribute('data-validation-optional', 'true');

How to collapse all divs that don't have a form input value set in them

If I have several DIV's each with a form in them with standard form elements (selects, text boxes, radios, checkboxes etc), is there a way to collapse all the divs that don't have a (non-default) value set on at least one of the inputs?
Go through each form, and search for form elements, check the current value property against the defaultValue, which will hold the elements default value (what it was on pageload)
$('div').each(function() {
var self = this;
$('form', this).find(':input').each(function() {
if (this.value != this.defaultValue) {
$(self).hide();
return false;
}
});
});
Depends what your defaults are, but you could loop and check:
$("div form").each(function() {
$(this).find(......) //find your inputs
//check
//if not default
$(this).closest("div").hide();
});
if you want to address the critical elements directly with a jquery selector, you might consider this piece of code as a beginning:
var $default_input_divs = $('div input[value="defaultvalue"]').parent('div');
$default_input_divs.remove();
JSfiddle example: http://jsfiddle.net/vaQYS/

jQuery serialize remove empty Select

I have a big form, that will be serialized by a jQuery function.
The problem is that I need to remove from this form before being serialized all the empty values.
I found a way to successfully remove all the empty input text fields, but not the selections.
It does not work properly with select dropdowns.
Ceck below:
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#submForm').validate({
submitHandler: function(form) {
// Do cleanup first
$('input:text[value=\"\"]', '#submForm').remove();
$('select option:empty', '#submForm').remove();
var serialized = $('#submForm').serialize();
$.get('".$moduleURL."classes/DO_submission.php', serialized);
window.setTimeout('location.reload()', 8000);
return false;
form.submit();
}
})
});
It should completely remove the dropdown selections where the values are empty. Not only the options but the entire select box should not be included in the serialize function.
How do I achieve this?
$('select option:empty', '#submForm').remove();
This code is not working as it should..
First, a select can not have an empty value. It will default to the first option if the selected attribute is not set.
Second, $('select option:empty') selects the empty options. To do something, an option should have a value, so afaik the selector will never work.
What you need to do is check all selects to see if they have a different value than their default, and if it is not the case, remove them.
If with 'empty select' you mean that the user has not chosen a 'valid' option (for example the fist option of a select is <option value=''>Select your value</option> )why don't you iterate on the select and check their value?
$('select').each(function(){
if ($(this).val() === ''){//this assumes that your empty value is ''
$(this).remove();
}
});
EDIT - sorry for the error, i missed the last parenthesis, i tried it and it works for me
I would just instead of serlizing the the whole form I would use jquery Form and then all you have to do is call
$('#submForm').ajaxSubmit({/.../});
Try
$('select option:selected:empty').parent().remove();
Edited after reading Nicola's comment.

Categories

Resources