user1038814
user1038814

Reputation: 9657

calling a javascript function within markup created by javascript using Jquery

I have form fields which are displayed using Jquery on click of a button.

[select dropdown: conOperator]   [textfield: conValue ]  [select dropdown: conValuedd]

conValuedd is hidden by default.

I'm trying to figure out a way so that when I select either Apple or Banana in the first select drop down [conOperator], it hides the textfield conValue and displays drop down conValuedd instead. However, if I were to select Watermelon, it would display conValue and hide conValuedd again. Any ideas would be much appreciated.

$('<select id="conOperator' + num + '" name="conOperator' + num + '" class="standard_select" style="width:147px;">
    <option>Watermelon</option>
    <option>Apple</option>
    <option>Banana</option>
   </select>&nbsp;
   <input type="text" id="conValue' + num + '" name="conValue' + num + '" class="short_input" value="" style="width:147px;">&nbsp;&nbsp;
   <select style="display:none" id="conValuedd' + num +'" multiple="multiple" size="5">
    <option value="option1">Blah</option>
    <option value="option2">Blah</option>
   </select>').appendTo('#addCondition');

Upvotes: 0

Views: 195

Answers (2)

Engineer
Engineer

Reputation: 48793

Try something like a:

$('#addCondition').on('change','#conOperator' + num, function(e){        
    switch( $('option:checked',this).text() ){
        case 'Apple':
        case 'Banana':
            $(this).nextAll(':text:first').hide();
            $(this).nextAll('select:first').show();
            break;
        case 'Watermelon':
            $(this).nextAll(':text:first').show();
            $(this).nextAll('select:first').hide();
            break;
    }
});
$('#conOperator' + num).trigger('change');

DEMO

Upvotes: 1

Florent
Florent

Reputation: 12420

When you call appendTo(), the generated <select/> is added to the DOM so you can retrieve it with jQuery and add a listener on it.

$("#conOperator" + num).change(function() {
    // Your logic here
}

Upvotes: 0

Related Questions