javascriptjqueryjquery-data

if/else jQuery using custom attribute


I am trying to do an if/else in jquery using an custom attribute. i named the attribute "data-id" because i was hoping i can use the .data() thing of jquery but somehow it did not work.

Here is what i tried last:

 if($("#marke").val() == '0'){
    $("#modellselect").attr("data-id").not('0').hide();
 } else{
    $("#modellselect").attr("data-id").show();
 } 

So, if the marke-value is 0 i want to show only the moddellselect with data-id 0, and if the marke-value is not 0, i want to show all of the modellselect's.


Solution

  • You need to use .filter for this instead

    if($("#marke").val() == '0'){
        $("#modellselect").filter(function(){
            return $(this).data('id') != '0'
        }).hide()
     } else{
        $("#modellselect[data-id]").show();
     } 
    

    (Remember, Id's should be unique - looks like yours are not)