-1

I am trying to add a hyperlink to a dropdron menu. The menu was created dynamically but the last option value and text are always going to be 'add new job'. I want the page to be redirected when the use clicks that option. I have Google it but haven't found a good solution yet.

<select name='job'>
<option value='value1'>value1</option>
<option value='value2'>value2</option>
<option value='value3'>value3</option>
//the above data are generated by server-side code. 
<option value='www.sample.com'>add new job</option> 
//I want the page to be redirected to the sample.com when user click the option. 
</select>
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
FlyingCat
  • 14,036
  • 36
  • 119
  • 198

4 Answers4

2

Maybe something like:

jQuery.change('select[name=job]', function() {
  if ($(this).val() == "www.sample.com"){
      window.location.href = "www.sample.com";
    }
}
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Alexander Corwin
  • 1,097
  • 6
  • 11
1

You'll have to use JavaScript for this. More likely you'll want to catch the change event of your dropdown, then check if the value is a link and redirect your user to that address. At least that's one way of doing it.

Leo
  • 5,069
  • 2
  • 20
  • 27
1
<select name='job' id='job'>
  <option value='value1'>value1</option>
  <option value='value2'>value2</option>
  <option value='value3'>value3</option>
  //the above data are generated by server-side code. 
  <option value='goto-new'>add new job</option> 
  //I want the page to be redirected to the sample.com when user click the option. 
</select>



$('#job').on('change', function(e) {
  if ($this.val() == 'goto-new') {
    // put your redirection here
    window.location.href = "http://stackoverflow.com";
  }
});
odupont
  • 1,946
  • 13
  • 16
  • While this code snippet may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Box Box Box Box Jun 26 '16 at 08:08
1

Implement a click handler and check for value of the selection option and redirect,

DEMO

Try,

$(document).ready(function() {

    $('select[name="job"]').change(function() {
        var selectedVal = $(this).val();
        if (isValidURL(selectedVal)) {
            window.location.href = selectedVal;
        }
    });


  //Below function is copied from http://stackoverflow.com/a/9350644/297641
  function isValidURL(value) {
    return /^(https?|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DF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
    }
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134