Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery set value only if empty

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);
like image 885
ahsteele Avatar asked Mar 21 '26 07:03

ahsteele


2 Answers

$(".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.

like image 133
prodigitalson Avatar answered Mar 22 '26 19:03

prodigitalson


$("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.

like image 21
Manjula Avatar answered Mar 22 '26 20:03

Manjula



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!