How do I get the selected value from a select box,

2019-06-26 16:20发布

问题:

I have this select box in HTML, and the page it's on is being loaded into another page (both on my website) through an iframe. I want to be able to get the selected value from the select box (inside the iframe), and display it on the outside. Here's some code I've pieced together, but I don't know if i'm doing it right:

<script>
$('#iframe').contents().find('#cds').change(function() {
    var selectVal = $(this).val();
    url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on'; 
    $("twitter").attr("id", url);
});
</script>

Any advice?

To Clarify

  • My <select> element is in the iframe
  • I want to display the selected value outside the iframe
  • The source of the iframe is on the same domain as the page into which it is loaded

回答1:

I'm not sure what your HTML looks like, but

$("twitter").attr("id", url);

should probably be:

$(".twitter").attr("id", url);

Update: Try this code... you need to detect if the iframe has loaded as well (demo)

$(function () {
    // define this here because we're changing the ID
    var $twitter = $('#twitter');
    // bind to select inside iframe
    $('#iframe').on('load', function () {
        $(this).contents().find('#cds').change(function () {
            var selectVal = $(this).val();
            url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
            $twitter.attr("id", url).text(url);
        }).change(); // trigger change to get initial value
    });
});

Also, since we're changing the ID of twitter, we need to save that jQuery object.