0

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";

2 Answers 2

1

try following code,

$("#autoplay option:selected").attr("data-autoplay");

or

$("#autoplay option:selected").data("autoplay");
Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.