How to select empty inputs (value="") using jQuery - javascript

How can I check for empty values of (required) input fields within a section, and then add a class to them on an event, using jQuery? So far, I have tried:
jQuery("#sender_container input.required").val("").addClass("error");
But that seems to SET the value, rather than checking it. Any ideas?

jQuery("#sender_container input.required").filter(function() {
return !this.value;
}).addClass("error");​
Why you have to use filter and not [value=""] you can see in this DEMO
The reason is: attribute selectors check the initial state of the element, not the current state. (note that you can change the "initial" state with the attr function, but it's bad practice, you should always use prop)
So if you change the input value, the current value won't effect the attribute selector. not wise... :)
Notes:
.val() returns the value of the form element, and breaks the jQuery chain,
$('selector').val().addClass('foo') Error, the return value is a string\ number
.val(valueToSet) sets the value of the form element and doesn't break the jQuery chain.
$('selector').val("some value").addClass('foo') - Valid, the returned value is a jQuery

$('input:text[value=]','#sender_container').addClass('error');
DEMO

$('#sender_container input.required[value=""]').addClass('error')

jQuery('#sender_container input.required[value=""]').addClass("error");
You can try this:
$('input:not([value!=""])').addClass('error');
DEMO
Note: This answer should not be used, and the only reason it wasn't deleted is so it can be learned from.

$field = $("#sender_container input.required");
if( ! $field.val())
{
$field.addClass("error");
}
this simple way may work.

If you only need to select based on the initial attribute value of the input then the following will do:
var elements = $('#sender_container input.required[value=""]')
But be aware that this won't work if the value attribute isn't present. It also won't work for the current input value if it has been changed by user or script.
If you'd like to get the current input value you can use jquery's filter function:
var elements = $('#sender_container input.required').filter(function() {
return this.value === '';
// alternatively for "no value":
// return !this.value;
})
After you've selected the jquery elements you can add your class:
elements.addClass('error');

to get all fields inspected this might help.
$('#sender_container [required]').each(function(index)
{
if (!($(this).val())) $(this).addClass('error');
}
});

Related

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

jQuery not function dependency on the value of another control

I have the following code:
$(serialNumbersDDL).children("option:gt(0)").remove();
It will delete all the options except the first one. Now I need to delete all the options except the first one and also not delete the option whose value is equal to the label text. How can I say that with writing limited amount of code?
try
$("option:not(':first')",serialNumbersDDL).filter(function(){
return $(this).val()!=$(this).text();
}).remove();
I'd try
$(serialNumbersDDL).children("option:gt(0)").not(function(){
return $(this.labels).text() == this.value;
}).remove();

Selecting from a list of previously selected elements via jQuery

I'm having a bit of a brain fart here, and hoping someone can help me find a 1-line solution to this problem, without having to call .each().
So I get a list of all checkboxes within a container like this:
var checkboxes = $(':checkbox', '#surveyModal');
At some point later, I need to find out if any (or none) of the checkboxes are checked within that list.
I expected something like these to work:
$(':checked', checkboxes)
// or
checkboxes.attr(':checked')
// or
$(checkboxes).attr(':checked')
But it doesn't. The only thing I've had success with is calling each() and then checking each individually. But that means I'll have to keep a separate variable (.e.g. someAreChecked at a higher-level scope, which I don't feel is optimal.
checkboxes.each(function () {
if ($(this).attr('checked')) {
someAreChecked = true;
}
});
I was hoping that I can easily in a single line do such a check:
if (checkboxes.('get checked count') == 0)
{
}
Thanks in advance.
The filter function is what you're looking for :)
checkboxes.filter(':checked').length;
.attr returns the value of an attribute, and you have to pass the attribute's name to it, not a selector.
Just use .is instead.
Description: Check the current matched set of elements against a
selector, element, or jQuery object and return true if at least one of
these elements matches the given arguments.
$(checkboxes).is(':checked')
This should do it:
$("input[type=checkbox][checked]").length

JS: check whether default value have been altered

is it possible to check whether default value (set using value="abcdef") of a field with id="someidset" have changed without having info about this default value? Hope it's kind of clear...
When you update the content of an element, the value property changes. However, the value attribute does not. This means that, presuming the value was defined in the value attribute in the original HTML, you can compare the two to see if the one has changed:
var el = document.getElementById('someidset');
if (el.value != el.getAttribute('value')) {
// value has changed
}
Note that this will only reliably work with type="text" inputs.
Well there are attributes and properties.
var someInput = document.getElementById('someInput');
someInput.value; // inputs value right now
someInput.getAttribute('value'); // inputs value set at start
Try this demo: http://jsfiddle.net/maniator/wVazC/
change the value right after the alert and wait 10 seconds
Sure, you can use the defaultValue property. It should work for most types of <input /> elements. Just check it against the value property.
Here's an example.

jquery dynamic id

i use such code to access item
function f(id){
$("#"+id).val(); // with analogy $("#id item")
}
is it correct? is any other methods?
If you want to return the value of an element with specified id, then yes as that is what seems to be logical purpose of your function:
function f(id){
return $("#" + id).val();
}
The functions should assume that an element with specified id exists and then it returns you the value of that element. This should work for input fields as well as textarea. If however, it is any other element, you might want to use html() or text() instead of val() eg:
function f(id){
return $("#" + id).html();
// return $("#" + id).text();
}
You could use PureDom
function f(id){
return document.getElementById(id).value;
}
Take that, jQuery!
Yes this is perfectly valid way to access the element having its id.
From the jQuery API website:
.val() Returns: String, Array
Description: Get the current value of
the first element in the set of
matched elements.
What It's not clear to me when you say
// with analogy $("#id item")
is if you want to have ONLY one child item of the one that is identifiedby #id or if you need the item that is identified by item#id.
Your code is perfect if you are passing a string like "hello" inside your code and you want to get the DOM element with ID of #hello.

Categories

Resources