views:

249

answers:

3

I am utilizing a modal for setting a default value for a series of text box fields. However, I only want to set the field to the default value if no value already exists. Is there a way to do that with a jQuery selector?

Current Code

var fooVal = $('#cboxLoadedContent').find('#SetFoo').val();
var barVal = $('#cboxLoadedContent').find('#SetBar').val();
$('.foo').val(fooVal);
$('.bar').val(barVal);
A: 

You could use :text[value=''] to find all empty textfields.

Jonathan Sampson
good point... thats not really robust enough to handle all kinds of form controls.
prodigitalson
+3  A: 
$(".foo[value='']").val(fooVal);

EDIT: As mentioned by Jonathan if youre using more than text inputs for this youre going to need to be a little more advanced... particularly with select tags, but also checkboxes, radios and textareas.

prodigitalson
`$('.foo[value=""]').val(fooVal);` works in IE but not in Firefox while `$(".foo[value='']").val(fooVal);` works in both. Why is that?
ahsteele
I have no idea... i always do it the latter way so ive never noticed that before.
prodigitalson
+1  A: 
$("input.foo[type=text][value='']").val(fooVal);
$("input.bar[type=text][value='']").val(barVal);

If your class has used for other type of inputs, then code should look like above code for ensuring only empty text boxes which has given class are affected by the code.

Manjula
actually you can just use $(".foo:text[value='']").val(fooVal);There are specific pseudo-class selectors for various form controls and selected/checked.
prodigitalson