Alan
Alan

Reputation: 2086

Javascript Selector for custom Tag

I need to be able to get the .val() of a custom parameter within an tag. The tag looks like this:

option style="font-weight: normal" answerid="32" >text here< /option

For the sake of the code / tag being self explanatory, I wanted to use "answerid" instead of "name" but I can't figure out how to get the value of that. My current script looks like this:

<script>
$('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val("answerid");
     $.get("ticket.php?do=quickanswer&selected=" +valueSelected+ "", 
     function( data ) {
                $( ".quickanswer" ).html( data );
                });

     console.log(valueSelected);
 });
</script>

Upvotes: 0

Views: 100

Answers (2)

zzzzBov
zzzzBov

Reputation: 179176

Using answerid as an attribute is invalid HTML. Instead of using invalid markup, use a custom [data-*] attribute:

<option data-answer-id="32">text here</option>

You can then take advantage of jQuery's .data() method to access the value:

answerId = optionSelected.data('answerId'); //32

.attr() works as well:

answerId = optionSelected.attr('data-answer-id'); //'32'

Please see my related answer for details as to why you'd use one over the other

Upvotes: 0

Felix
Felix

Reputation: 38112

You can use .attr():

var valueSelected  = optionSelected.attr("answerid");

Fiddle Demo

Upvotes: 1

Related Questions