Janan
Janan

Reputation: 45

JS - get #id instead of.val()

is there any way to get id instead of value where

$('#' + $(this).val()).show();

$(function() {
  $('#inputtype').change(function(){
    $('.fastallow').hide();
    $('#' + $(this).val()).show();
  });
});

HTML

<select id="inputtype" class="form-control" name="typeof"> 
     <option value="FALSE" selected>Methods</option> 
    <?php foreach ($mb as $namee): ?> <option id="<?= $namee->u_ft; ?>" value="<?= $namee->username; ?>"><?= $namee->vn; ?></option> 
    <?php endforeach ;?> 
</select> 

and

<div class="form-row fastallow" id="1" style="display:none;">
.
.
.
</div>

I want to display div only where option id = 1

Upvotes: 4

Views: 282

Answers (1)

charlietfl
charlietfl

Reputation: 171700

You can't repeat ID's in a page, they are unique by definition

Use a data-attribute on the <option> instead and use :selected selector to target selected <option> in order to access that attribute

$(function() {
  $('#inputtype').change(function(){
    // "this" is the <select>
    $('.fastallow').hide();
    $('#' + $(this).find(':selected').data('id')).show();
  });
});
.fastallow{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="inputtype" class="form-control" name="typeof">
   <option></option>
   <option data-id="1" value="someVal">One</option>
   <option data-id="2"  value="anotherVal">Two</option>
</select>
<div id="1" class="fastallow">Content One</div>
<div id="2" class="fastallow">Content Two</div>

Upvotes: 1

Related Questions