jaya
jaya

Reputation: 327

How do I append new anchor to options in drop down using jQuery

Is it possible to create a new anchor tag dynamically along with option in drop down list?

I want to open new page in new tab from drop down list box. Is there is any other way to do this?

So far, I have tried this:

function abc
{
    $("#reportimg").fadeOut("slow"); 
    <?php $link="<html><a Onclick='openreport($report2)'>Open</a></html>";?>
    var text="<?php echo $report2.$link;?>";  
    var val="<?php echo $report2;?>"; 
    alert(text);
    $('#report_list').append( new Option(text,val) );
}

Upvotes: 0

Views: 1178

Answers (2)

Ian
Ian

Reputation: 50905

Try using this structure (of course you can replace my stuff with your PHP generation, but there's no need to use <a> or whatever):

<select id="report_list">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

And this Javascript:

$(document).ready(function () {
    $("#report_list").on("change", function () {
        openreport($(this).val());
    });
});

DEMO: http://jsfiddle.net/AyvUZ/2/

This listens for the <select>'s value to change, meaning an option was chosen. You can grab its value with $(this).val() (which is all you seemed to need in your example code), and pass that to openreport. This is all done without modifying the original HTML.

Upvotes: 2

SergioMSCosta
SergioMSCosta

Reputation: 334

You can not actually force a browser to open a new tab, only a new window. Nowadays browsers do tend to open a new tab when you click on a "_blank" link or open a new window through JavaScript.

If you're OK with that (and I suspect, you're not since you asked specifically for a solution that opens a new tab), you can try this:

<!doctype html>
<html>
<body>
    <select id="myDropDown">
        <option>Select a website</option>
        <option value="http://www.google.com">Google</option>
        <option value="http://www.yahoo.com">Yahoo</option>
        <option value="http://www.msn.com">MSN</option>
    </select>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script>
        $(function() {
            $('#myDropDown').change(function(el) {
                window.open($('#myDropDown').val());
            });
        })
    </script>
</body>
</html>

Hope that helps!

Upvotes: 2

Related Questions