2

jQuery is permitted, but an HTML-only solution is preferred.

I have a select box with a couple of options. When the user selects 'Name', I want the placeholder text 'Enter your name' to appear in the adjacent text-box.

Likewise for 'ID' -> 'Enter your ID'.

See http://jsfiddle.net/Uy9Y3/

<select>
    <option value="-1">Select One</option>
    <option value="0">Name</option>
    <option value="1">ID</option>
</select>
<input type="text">

This is a requirement by a client that I haven't been able to figure out.

If it helps, the website is using the Spring framework.

cfs
  • 10,610
  • 3
  • 30
  • 43
John Smith
  • 53
  • 1
  • 3

3 Answers3

2

Since you need to update the placeholder when the select updates, you'll need to use javascript to do it.

You could set the placeholder you would like to display as an attribute on each option element using the HTML5 data- style attributes. Then use jQuery to attach a change event listener which will update the placeholder attribute of the input box.

Note that the placeholder attribute doesn't have any effect in older versions of IE, so if you need to support old IE you'll need to polyfill that functionality with another library.

Working Demo

HTML

<select id="mySelect">
    <option data-placeholder="" value="-1">Select One</option>
    <option data-placeholder="Enter your name" value="0">Name</option>
    <option data-placeholder="Enter your ID"  value="1">ID</option>
</select>
<input id="myInput" type="text">

jQuery

$('#mySelect').on('change', function() {
    var placeholder = $(this).find(':selected').data('placeholder');
    $('#myInput').attr('placeholder', placeholder);
});
cfs
  • 10,610
  • 3
  • 30
  • 43
1

It requires JavaScript. You can do it inline -- if that's what you mean by HTML-only.

<select onchange="document.querySelector('input').setAttribute('placeholder', 'Enter your ' + this.options[this.selectedIndex].text);"></select>
reecer
  • 86
  • 2
0

See the following jsfiddle for an example of how to do this:

http://jsfiddle.net/sW6QP/

Note that this is using jQuery ONLY because jsfiddle seems to be unable to find the function placed into the onChange event.

If you want to do it without jQuery, change the select line to this:

<select id="selectionType" onChange="setPlaceholder();">

And instead of $("#selectionType").on("change",function() {, do this instead:

function setPlaceholder() {

(make sure to change the }); to } as well)