Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - How to grab specific data-type of option after that option is selected?

I'll jump straight with the markup, then explain what I'm trying to do.

Html select options

    <select id="1d" name="camp">
    <option data-url="week_1" value="Week 1">30th July</option>
    <option data-url="week_2" value="Week 2">6th August</option>
    </select>
    <input type="hidden" name="camp_url" id="1e">

Jquery script I'm struggling with. The script below shows the value of the selected option, of course, but I can't find a way to grab to the data-url info.

    $('#1d').change(function () {
        $('#1e').val($(this).val());
    });

Bottom line, I'm needing the value of input#1e to be the data-url of #1d upon selection.

Thanks for your help.

like image 740
Stephen Callender Avatar asked Jun 05 '12 20:06

Stephen Callender


People also ask

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do I get the text value of a selected option jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How can check select option value is selected or not in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });


1 Answers

How about that?

$("#1d").on("change", function () {
    var url = $(this).children(":selected").data("url");
    $("#1e").val(url);
});

DEMO: http://jsfiddle.net/aRzNn/


Also personally I enjoy this solution:

$("#1d").on("change", function () {
    $("#1e").val(function() {
        return $("#1d > :selected").data("url");
    });
});​
like image 135
VisioN Avatar answered Sep 22 '22 21:09

VisioN