Programing

jQuery-선택한 옵션에서 사용자 정의 속성 가져 오기

lottogame 2020. 4. 27. 07:56
반응형

jQuery-선택한 옵션에서 사용자 정의 속성 가져 오기


다음을 감안할 때 :

<select id="location">
    <option value="a" myTag="123">My option</option>
    <option value="b" myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
            var element = $(this);
            var myTag = element.attr("myTag");

            $('#setMyTag').val(myTag);
        });
    });
</script>

작동하지 않습니다 ...
선택이 변경 될 때 숨겨진 필드의 값을 myTag의 값으로 업데이트하려면 어떻게해야합니까? 현재 선택된 값을 얻는 것에 대해 뭔가를해야한다고 가정하고 있습니다 ...?


<select>요소에 이벤트 핸들러를 추가하고 있습니다.
따라서 $(this)선택한이 아닌 드롭 다운 자체가됩니다 <option>.

다음 <option>과 같이 선택된을 찾아야합니다 .

var option = $('option:selected', this).attr('mytag');

이 시도:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 

요소가 사용자 정의 태그가있는 "옵션"이 아니라 "선택"이기 때문입니다.

이것을 시도하십시오 : $("#location option:selected").attr("myTag").

도움이 되었기를 바랍니다.


이 시도:

$("#location").change(function(){
            var element = $("option:selected", this);
            var myTag = element.attr("myTag");

            $('#setMyTag').val(myTag);
        });

에 대한 콜백 함수에서 change(), this선택을하지 선택한 옵션을 의미합니다.


Suppose you have many selects. This can do it:

$('.selectClass').change(function(){
    var optionSelected = $(this).find('option:selected').attr('optionAtribute');
    alert(optionSelected);//this will show the value of the atribute of that option.
});

You're pretty close:

var myTag = $(':selected', element).attr("myTag");

Simpler syntax if one form.

var option = $('option:selected').attr('mytag')

... if more than one form.

var option = $('select#myform option:selected').attr('mytag')


Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger

Chrome Debug

I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.

<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>

<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');

//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){

//clear the current content of the select
$select.html('');

//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},

error:function(){

//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});

$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>

Here is the JSON File to create...

{  
"List":[  
{  
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{  
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{  
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{  
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}

Hope this helps, thank you all above for getting me this far.


Try This Example:

$("#location").change(function(){

    var tag = $("option[value="+$(this).val()+"]", this).attr('mytag');

    $('#setMyTag').val(tag); 

});

$("body").on('change', '#location', function(e) {

 var option = $('option:selected', this).attr('myTag');

});

참고URL : https://stackoverflow.com/questions/2230704/jquery-getting-custom-attribute-from-selected-option

반응형