If got an selection with with and value, which is the same value as an class data attribute. I want to onchange show the current div with the same value as the option value. My code is this:
$('.test_c').hide();
$('#test').on("change", function() {
let me = $(this).val();
$('test_c' me.data('document-id')).show();
})
<select name="test" id="test" class="test">
<option value="default">Select</option>
<option value="1">Test</option>
</select>
<div class="test_C" data-document-id="1" style="display: none">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You're quite close. Couple of points:
me
is a string:
let me = $(this).val()`
will set me
to the value, not an element/node/jquery, this value will be a string, so you can only use string methods. me
would normally be just $(this)
and a better variable name might fit here, eg var documentId=...
- Use attribute selectors
[attribute-name]
to match an attribute. - Use
.class
for class selector (missing the.
on$('test_c'
) - Class selectors are case-sensitive, so
$(".test_c")
will not find<div
- can be easier just to always use lowercase.
Giving:
$('#test').on("change", function() {
let docId = $(this).val();
$('.test_c').hide();
$(`.test_c[data-document-id=${docId}]`).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="test" id="test" class="test">
<option value="default">Select</option>
<option value="1">Test</option>
</select>
<div class="test_c" data-document-id="default"><em>please select above</em></div>
<div class="test_c" data-document-id="1" style="display: none">ONE</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>