1

I'm trying to redirect my users on different URLs based on the text they enter in input and I've seen this question Need to redirect form to multiple URLs based on input

And I've tried the same thing but I don't know why this is not working for me please find my code below, whenever I click on the 'GO' button nothing happens.

<script type="text/javascript">
var urlMapping = {
    "STRING1" : "https://google.com/",
    "STRING2" : "https://stackoverflow.com/",
    "STRING3" : "https://twitter.com/home"
}

$("#submit-form").click(function(){
    var input = $("input").val().trim().toUpperCase();
    if (urlMapping.hasOwnProperty(input)){
        window.location = urlMapping[input];
    }
    else {
        //if url not found, redirect to default url
        window.location = "./default.html";
    }
});

</script>

<form class="form-inline">
    <div class="form-group">
         <input type="text">
         <button id="submit-form" type="button">Go</button>
    </div>
</form>
Paradoxi
  • 25
  • 7
  • Looks like a document ready issue – Taplar Dec 18 '20 at 23:31
  • 2
    Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Taplar Dec 18 '20 at 23:31
  • 1
    Your script is above the html. At the point in time the script runs, the form does not exist yet – Taplar Dec 18 '20 at 23:32
  • @Taplar Hi, can you show me how can I implement this on my code, I'm really sorry but I'm kinda new to this and clearly I'm doing something wrong, and it's still not working, yes I'm using .html – Paradoxi Dec 18 '20 at 23:40
  • Please read the duplicate. The gist is browsers parse html documents from the top down. So if you have a ` – Taplar Dec 18 '20 at 23:42
  • @Taplar I've tried before putting my script after the elements too and it still didn't work. – Paradoxi Dec 18 '20 at 23:46
  • https://jsfiddle.net/6h7ucv40/ works fine – Taplar Dec 18 '20 at 23:48
  • @Taplar ok so apparently I had to put it after the jquery.min.js too and it worked, before I was just putting it after the element. Thank you so much it's solved – Paradoxi Dec 18 '20 at 23:50

0 Answers0