2

I have the following code:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.pack.js"></script>
</head>
<body>
<select name="size">
    <option custAttr="0" value="0" disabled selected>Value ↓</option>
    <option custAttr="10" value="10">AAA (10)</option>
    <option custAttr="20" value="20">BBB (20)</option>
    <option custAttr="30" value="30">CCC (30)</option>
</select>

<label class="result"></label>

<script>
$(document).ready(function() {
    $('select').on('change', function() {
        $('.result').text(
            $('select[name=size]').val()
        );
    });
});
</script>
</body>
</html>

Actually the script takes the content from value="". Is there a way that the script takes the code from my custom attribute custAttr=""?

1
  • 1
    Take a look at .attr() Commented Oct 3, 2016 at 11:14

4 Answers 4

4

Firstly note that creating your own attributes will mean your HTML is invalid which can have unexpected effects. Use data-* attributes to store your own data. From there you can use option:selected to get the required data value. Try this:

$(document).ready(function() {
  $('select').on('change', function() {
    $('.result').text($('select[name=size] option:selected').data('cust-attr'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="size">
  <option data-cust-attr="0" value="0" disabled selected>Value ↓</option>
  <option data-cust-attr="10" value="10">AAA (10)</option>
  <option data-cust-attr="20" value="20">BBB (20)</option>
  <option data-cust-attr="30" value="30">CCC (30)</option>
</select>

<label class="result"></label>

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks. It's working. I have to wait 5 minutes to accept.
No problem, glad to help
Still a small question: Do you know how to replace dot by comma. E.g. 123,45 instead of 123.45.
Yep, .replace(/,/g, '.')
Sorry for have to ask again, but: where to add this? I tried some ways, but it didn't work.
|
0

As far as i know you can do it like this

$("#myselect option:selected").attr('custAttr');

Comments

0
$('select[name=size]').attr("custAttr");

.attr()

Comments

0

attr() should do the trick!

$('select[name=size]').attr('custAttr');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.