Search code examples
phpjqueryhtmlselectbuddypress

How can I change the option of a select with jQuery?


I am using the BuddyPress plugin to create a multi-select option in user the profile. Unfortunately, before people click this select, the display text is '----'. I want to use jquery to change the display text from '----' to something like 'Please select'. How can I do that in jQuery?

<select id="field_221" name="field_221" aria-required="true">
    <option value="">----</option>
    <option value="13">13</option>
    <option> value="14">14</option>
    <option> value="15">15</option>
</select>


Solution

  • You can do this by iterating through the select options and replacing any that are equal to '----'.

    JavaScript:

    $(function () { // Executes on DOM ready
        $("#field_221 > option").each(function () {
            if (this.text === '----') {
                this.text = 'Please select';
            }
        });
    });
    

    Demo: http://jsfiddle.net/BenjaminRay/8r3d9r9c/

    Also, you have an extra > in the last two options. Change <option> value... to <option value....