- <fieldset id="sample">
- <select name="test" id="test" size="4"> <option> Foo </option> <option> Bar </option> <option> Blee </option> <option> Other </option> </select>
- <span class="other"></span>
- </fieldset>
That's the roughness. I'm trying to make a general solution, so I have a
span
after every select
. And here's where the problem comes.I want to watch every
select
click. That's easy in jQuery. I want to then check to see if the value is now 'other'. That also is easy.- $( 'select' ).click( function() {
- var strVal = $( this ).attr('value') ;
- if ( strVal == 'Other' ) {
- ...
- }
- else {
- ...
- }
- }) ;
What I want to do now is create an
input
box to put the "other" text in. And if I could do it in an object-y kind of way, I can.- $( 'select' ).click( function() {
- var strVal = $( this ).attr('value') ;
- var strOther = $( this ).parent().attr('id') + '_other' ;
- var strHTML = '<input type="text" name="' + strOther + '">'
- if ( strVal == 'Other' ) {
- $( this ).parent().children('.other').html( strHTML ) ;
- }
- else {
- $( this ).parent().children('.other').html('') ;
- }
- }) ;
But wouldn't it be better to do things with a more object-like interface? I fill one of those
select
s dynamically, with code that works like this:- clearSelectBox( document.getElementById('test') ) ;
- function fillSelectBox_SOLiD ( obj_sel ) {
- var valueArray = new Array( '1 cell' , '4 cell' , '8 cell' , 'Other' ) ;
- for ( var i = 0 ; i < valueArray.length ; i++ ) {
- var obj_option = document.createElement('option') ;
- obj_option.text = valueArray[i] ;
- try {
- obj_sel.add( obj_option , null ) ;
- // standards compliant; doesn't work in IE
- }
- catch(ex) {
- obj_sel.add( obj_option ) ;
- // IE only
- }
- }
- }
I would much rather create the
input
by saying something like var newInput = document.createElement('input')
than just writing the HTML, but until I can do something like that in JS, I will keep as is. Any pointers?