2

I'm really really new to coding so here's my question. How do I redirect to another page using JSP and Javascript? or Servlet? I don't understand a thing in Servlet that's why I use Javascript. When I choose any of the options and click submit, nothing happens.

Here's my code:

JSP:

<form>
    <select id="module_id" name="module_id" />
        <option value="0" selected /></option>
        <option value="1" /> CD101 </option>
        <option value="2" /> CD102 </option>
        <option value="3" /> CD103 </option>
        <option value="4" /> CD104 </option>
        <option value="5" /> CD105 </option>
        <input type="button" value="Submit" onclick ="myChoice();" />
    </select>
</form>

Javascript: (google-d)

<script type="text/javascript">
function myChoice(){
  var s = document.getElementById("module_id");
  var module_id = s.selectedIndex.value;

  if (module_id === 1)
      window.location = "response.jsp";
  if (module_id === 2)
      window.location = "http://www.google.com";
}
</script>
Anand Singh
  • 2,343
  • 1
  • 22
  • 34

1 Answers1

1

function myChoice(){
  var s = document.getElementById("module_id");
  var module_id = s.value;
  console.log(module_id );
  if (module_id === "1")
      alert("ok");
  if (module_id === 1)
      alert("not ok");
}
<form>
    <select id="module_id" name="module_id" />
        <option value="0" selected /></option>
        <option value="1" /> CD101 </option>
        <option value="2" /> CD102 </option>
        <option value="3" /> CD103 </option>
        <option value="4" /> CD104 </option>
        <option value="5" /> CD105 </option>
        <input type="button" value="Submit" onclick ="myChoice();" />
    </select>
</form>

Replace this from your code:

function myChoice(){
      var s = document.getElementById("module_id");
      var module_id = s.value;//changed
    
      if (module_id === "1")//changed
          window.location.href = "response.jsp";
      if (module_id === "2")//changed
          window.location.href = "http://www.google.com";
    }

Explanation:

You are getting string type value and you were comparing with int, The === operator compare the value as well as type so that's why redirection was not happening.

For more you should read this awesome answer https://stackoverflow.com/a/359509/3143384.

And selectedIndex of javascript returns the index of selected option not its object reference. so you have to user option or value. For more you can read this and try this example

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Anand Singh
  • 2,343
  • 1
  • 22
  • 34