HaneenSu
HaneenSu

Reputation: 150

Hitting enter doesn't call the function; resets instead.

I have a very simple form that has a drop-down list with 3 options and a text box. I need to check the values of both inputs in order to direct the user to the appropriate page. It works fine when I click by mouse on the "Go" button. However hitting enter reload the page! The code was working before adding the drop-down list.. it is causing the problem to occur somehow!


 <select form="semester">
    <option value="Fall">Fall</option>
        <option value="Spring">Spring</option>
     <option value="Summer">Summer</option>

   </select>
 <input type="text" name="year" maxlength="4" size="30" onsubmit= " if(event.keyCode == 13) document.getElementById('btnSearch').click()" />

<input type="button" id="btnSearch" onclick="check(this.form)" value="Go!"/>

 <script language="javascript">
    var e = document.getElementById("semester");
    var ee = e.options[e.selectedIndex].value;
    function check(form)
    {
       if(ee == "Fall" || "fall"&& form.year.value == "2013")
        {               window.location="semester/fall13/categories.html"; 
                    }

                    else
                    {
                        alert("Not Available!")/*displays error message*/
                    }

                }
            </script>

Upvotes: 1

Views: 1462

Answers (2)

Anshu Dwibhashi
Anshu Dwibhashi

Reputation: 4675

Exactly do what AvinashW says:

<select id="semester" name="semester">

to prevent the form from submitting, do this:

onsubmit="return false;"

Here's another mistake you are making:

if(ee == "Fall" || "fall"&& form.year.value == "2013")

should be

if(ee == "Fall" || ee ==  "fall" && form.year.value == "2013")

And if you dont mind, i made a page with the functionality you need but with my code:

<html>
<body>
<div>
    <select id="semester">
        <option value="Fall">Fall</option>
        <option value="Spring">Spring</option>
        <option value="Summer">Summer</option>
    </select>
    <br/>
    <input type="text" id="year" maxlength="4" size="30" onkeypress= " if(event.keyCode == 13) document.getElementById('btnSearch').click()" />

    <button id="btnSearch" onClick="Go()">Go</button>
</div>

<script>
function GetSelectedItem()
{
    var e = document.getElementById("semester");
    strSel=e.options[e.selectedIndex].value;
    return strSel;
}

function Go(){
    selected = GetSelectedItem();
    if( (selected=="Fall"||selected=="fall") && document.getElementById('year').value=='2013'){
        window.location="semester/fall13/categories.html"; 
    }else{
        alert("Not available!");
    }
}
</script>
</body>
</html>

JSFIDDLE

Upvotes: 3

Avinash Ware
Avinash Ware

Reputation: 158

Here is correction,

<select id="semester" name="semester">

onsubmit should apply to form ,not to input

Upvotes: 2

Related Questions