Reputation: 3393
if I have the html
<select id="autoplay">
<option data-autoplay="">no</option>
<option data-autoplay="1">yes</option>
</select>
how using jQuery can I return the data-autoplay
value in respect to which option is selected and set it as a variable var autoplay = *selected value*
so if I select no
it returns nothing and if I select yes
it returns 1 so var autoplay = "1";
Upvotes: 0
Views: 278
Reputation: 253308
You can use the attr()
method to get the value of an attribute:
var autopplay = $('#autoplay option:selected').attr('data-autoplay');
if (!autoplay || autoplay == '') {
// an empty string was returned
}
else if (autoplay == 1) {
/* remember not to trust your users, so validate in/on the server
if you're storing the variable/result...
// 1 was returned
}
It's possible to also use data('autoplay')
, which will look at data-
prefixed attributes with a string matching the selector (autoplay) following the data-
, so in this case it would look for: data-autoplay
(somewhat obviously, I suppose).
References:
Upvotes: 1
Reputation: 24302
try following code,
$("#autoplay option:selected").attr("data-autoplay");
or
$("#autoplay option:selected").data("autoplay");
Upvotes: 1