I have combed through multiple StackOverflow posts and haven't found the right syntax for what I'm looking for. I think I'm close, but need some help. Here's the situation:
I have a form with regular text and select fields that are styled differently based on whether the field has been filled out or not.
I've purposely not added something like Chosen or jQuery UI to rip apart the select field and rebuild with normal elements. Trying to keep things clean and small. All styling is done with CSS.
Currently I am adding a class to my select fields on load and then removing that class when someone interacts with the select field:
$(".infield select").addClass('default-value');
$("select").bind("focus", function () {
$(this).removeClass('default-value');
});
This works great, but my issue is that we are using cookies to prepopulate some of the form fields if they've filled out a form on the site previously. The above code only kicks in if they interact with the field.
I need something to remove my "default-value" class if the page loads and the select field has something selected. Here's my latest try, but it's not working.
$("select option:selected").on(function() {
$(this).parent().removeClass("default-value");
});
Also for reference here's the basic select field code:
$(".infield select").addClass('default-value');
$(".infield select option:selected").on(function() {
$(this).parent().removeClass("default-value");
});
$(".infield select").bind("focus", function () {
$(this).children('option[value="defaultValue"]').remove();
$(this).removeClass('default-value');
});
form {
background-color: #EFF2F4;
padding: 5%;
}
.infield select {
font: bold 1.1em "source-sans-pro", Helvetica, Helvetica;
border: none;
border-left: 4px solid #BCC2C8;
padding: .5em;
width: 100%;
color: #808080;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border-radius: 0px;
border-radius: 0px !important;
background: url(/images/uploads/design-assets/select-arrow.png) right center no-repeat;
background-size: 21px;
-webkit-border-radius: 0px;
-webkit-appearance: none;
background-color: #fff;
-webkit-border-radius: 0px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border-right: 10px solid #fff;
}
.infield select.default-value {
color: #99acb9;
font-weight: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="infield">
<select id="billing_state" name="billing_state">
<option value="">State</option>
<option selected="selected" value="AL">AL</option>
<option value="AK">AK</option>
</select>
</form>
What am I missing?