3

I have a dynamically created select element. How would I be able to get the attr of the specific option chosen. Right now it just gives me the att of the first element.

Here is my code

    $('button').click(function(){
        var arena = $(this).attr('id');
        var id = arena + '.jpg';
        $('#header').css('background-image', 'url('+id+')');
        $('#chooseArena').html("" + "<h1>Pick your ninja</h1>\
            <select name='first'>\
                <option id = 'black' value='black.png'>Black</option>\
                <option id = 'green' value='green.png'>Green</option>\
            <select>\
            <select name='second'>\
                <option value='black.png'>Black</option>\
                <option value='green.png'>Green</option>\
            <select>");

    });
    $(document).on('change', 'select', function(e){
        var ninja1 = $(e.target).children().attr('id'); //this always returns the first attr.  What should I do to get this to return the child element selected.
        alert(ninja1);
    });
Aaron
  • 4,380
  • 19
  • 85
  • 141
  • I don't think option can have id attributes. Could you use var ninja1 = $(e.target).children().val(); instead? – Vincent Jan 20 '17 at 18:54

1 Answers1

2

Get the selected option within the context using :selected pseudo-class selector.

$(document).on('change', 'select', function(e){
    var ninja1 = $('option:selected', this).attr('id'); //this always returns the first attr.  What should I do to get this to return the child element selected.
    alert(ninja1);
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188