0

I'd like to know if it's possible for a select box to have two functions.

1.Redirects automatically when selecting an option using value.

2.Load content via ajax into the closest div using data-file.

<select class="loadurl">
 <option value="#">Select</option>
 <option value="contact.php">Contact</option>
 <option value="about.php">About</option>
 <option data-file="fans.php">Fans</option>
</select>
<div class="area"></div>

But when I tried the following script, the ajax option (Fans) didn't work but attempted to redirect instead. May I know how to have two functions in just one select box? Here's a demo.

$(".loadurl").bind('change', function () {

  var selected = $(this).find('option:selected');
  var loadfile =selected.data('file');
  var area = $(".area");

  $(this).next(".area").load(loadfile);
area.empty();

});


$('.loadurl').bind('change', function () {
    window.location.href = $(this).val();
});
RedGiant
  • 4,444
  • 11
  • 59
  • 146

1 Answers1

2

You need to use a conditional choice here - if the selected option has data-file then load the target in the area else reload the page.

var area = $(".area");
$(".loadurl").on('change', function () {
    var selected = $(this).find('option:selected');
    var loadfile = selected.data('file');
    if (loadfile) {
        area.empty();
        $(this).next('.area').load(loadfile);
    } else {
        window.location.href = $(this).val();
    }
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531