-1

Hello there dear community.

Here is my HTML code:

<select name="Pcolor" id="image" style="height:30px;">
    <option value="">Избран цвят: Blue/Lt Blue </option>
    <option value="45751303" color-number="0">Black</option>
    <option value="45751343" color-number="1">Black/Pink</option>
    <option value="45751359" color-number="2">Blue/Lt Blue</option>
    <option value="45751324" color-number="3">Dk Purple/Purpl</option>
    <option value="45751390" color-number="4">Ink/Cerise</option>
</select>

I want to ask how i can get the color-number attribute number where option text is Blue/Lt Blue for example ?

It is important to make it only with JavaScript/jQuery !

I hope you understand what i want to describe, thanks in advance!

Venelin
  • 2,905
  • 7
  • 53
  • 117
  • 2
    Iron man, What did you tried? I am sure you want to share code with us. – Satpal May 20 '15 at 09:20
  • 1
    possible duplicate of [jquery : How to select an option by its text?](http://stackoverflow.com/questions/3744289/jquery-how-to-select-an-option-by-its-text) – CodingIntrigue May 20 '15 at 09:21
  • See `.attr()` or `.prop()` jQuery functions. Also a suggestion, Use `data-colorNumber` instead of `color-number` – Shaunak D May 20 '15 at 09:23
  • [This tells you how to do this exactly](http://stackoverflow.com/a/3744305/542251) closing as duplicate. [Working fiddle](https://jsfiddle.net/oreyuvmx/) – Liam May 20 '15 at 10:40

3 Answers3

2

I would do this way:

$('#image option[value="Blue/Lt Blue"]').attr("color-number");

So essentially you search for the correct option and get it attribute.

pinturic
  • 2,253
  • 1
  • 17
  • 34
  • `$('#image option[value=45751359]').attr("color-number");` – Satpal May 20 '15 at 09:24
  • I think the option `value` is not `Blue/Lt Blue` like you point in your answer. It must find the option for the text in it `` – Venelin May 20 '15 at 10:11
2

Using :contains() won't be a proper solution as it will return partial matches, instead you can use .filter()

var text = 'Black/Pink';
var cn = $('select[name="Pcolor"] option').filter(function() {
  return $(this).text().trim() == text;
}).attr('color-number');

console.log(cn)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="Pcolor" id="image" style="height:30px;">
  <option value="">Избран цвят: Blue/Lt Blue</option>
  <option value="45751303" color-number="0">Black</option>
  <option value="45751343" color-number="1">Black/Pink</option>
  <option value="45751359" color-number="2">Blue/Lt Blue</option>
  <option value="45751324" color-number="3">Dk Purple/Purpl</option>
  <option value="45751390" color-number="4">Ink/Cerise</option>
</select>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
$('#image').on('change',function() {
  alert($(this).find('option:selected').attr('color-number'));
})

https://jsfiddle.net/cw6knsc5/2/

madalinivascu
  • 32,064
  • 4
  • 39
  • 55