views:

295

answers:

2

I have a php page with 4 text boxes, each need a "drop down" when the text boxes have the focus. Clicking the options would populate the (editable) text box(es) and close the drop down. The text boxes are of course part of html forms. How can I do this inline with javascript or ajax using minimal code?

+1  A: 

Unless you are calling a webserver ajax is useless here.

You will need to have or create a div, since it is below your input box, and absolute positioning will be useful to ensure it is appropriately placed relative to the input box.

You should only have one function, so it should be adaptable to the input fields, hence the reason for absolute positioning.

You will want to track the keypress and mouseclick events in this div, and ensure that only one is open at a time, so have an onblur so that if the user clicks anywhere else the div closes.

James Black
+1  A: 

if you use jquery you can do this extremely easily.

you could tweak this to your liking:

<html>
<script language='javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'&gt;&lt;/script&gt;

<script language='javascript'>
$(document).ready(function(){
    $("input[type='text']").focus(function(){
        $(this).parent().find('select').show();
    });

    $('select').change(function(){
        $(this).parent().find('input[type="text"]').val($(this).val());
        $(this).hide();
    }).blur(function(){
        $(this).hide();
    });
});
</script>

<form>

<fieldset>
<input type='text' /><br/>
<select style='display:none;'>
    <option value=''>----</option>
    <option value='1'>opt1</option>
    <option value='2'>opt2</option>
    <option value='3'>opt3</option>
</select><br/>
</fieldset>

<fieldset>
<input type='text' /><br/>
<select style='display:none;'>
    <option value=''>----</option>
    <option value='1'>opt1</option>
    <option value='2'>opt2</option>
    <option value='3'>opt3</option>
</select><br/>
</fieldset>

<fieldset>
<input type='text' /><br/>
<select style='display:none;'>
    <option value=''>----</option>
    <option value='1'>opt1</option>
    <option value='2'>opt2</option>
    <option value='3'>opt3</option>
</select><br/>
</fieldset>

<fieldset>
<input type='text' /><br/>
<select style='display:none;'>
    <option value=''>----</option>
    <option value='1'>opt1</option>
    <option value='2'>opt2</option>
    <option value='3'>opt3</option>
</select><br/>
</fieldset>
</form>

</html>

if your select options need to be dynamic, ajax is very simple with jquery. if you already know what's going to be in there, have the php populate the hidden select boxes, and the focus event will show them.

Brandon H