Navigating to a Website Based on the Selected Option in a Drop-Down Menu

I am currently working on a form that includes options for selecting a city and social networking site. The goal is to collect information about both the selected city and social network so that it can be stored for future reference. Upon submitting the form, I want the user to be redirected to the homepage of the chosen social networking site (e.g. Facebook). However, I'm encountering an issue with the redirection not occurring correctly. Here is the code snippet:

<script type="text/javascript">
function actionDef() {
var option_selected = $('purposeId').value();
console.log = option_selected;
    if( option_selected=="gl" ) {
        document.getElementById("search-form").action = "https://www.google.co.in/";
    }
    else if( option_selected=="y" ) {
        document.getElementById("search-form").action = "https://in.yahoo.com/?p=us";
    }
    else if( option_selected=="fb" ) {
        document.getElementById("search-form").action = "http://www.facebook.com/";
    }
}      
</script>
        <form action="/" name="search-form" id="search-form" method="get" accept-charset="UTF-8" class="form-vertical">
<div class="city">
                <label for="cityId" class="required">Select Your City</label>
                <select id="cityId" name="cityId" data-prefill="location.cityId" class="form-control" placeholder="Select a city">
                  <option value="9">Bangalore</option>
                  <option value="20">Chennai</option>
                  <option value="27">Faridabad</option>
                   ...
              <div class="show-ofr">
                 <input type="submit" name="button" class="btn btn-primary btn-block">
              </div>
</form>

Answer №1

Check out the code snippet below for a solution to the issue you are facing with processing values from a select field.

JavaScript

<script src="http://code.jquery.com/jquery-3.0.0.min.js"></script>
    <script>
      jQuery(function($) {
        // Binding change event to select
        $('#purposeId').on('change', function() {
          var url = $(this).val(); // Fetch selected value
          alert(url);
          if (url == "1") {
            document.getElementById("search-form").action = "https://www.google.co.in/";
          } else if (url == "2") {
            document.getElementById("search-form").action = "https://in.yahoo.com/?p=us";
          } else if (url == "3") {
            document.getElementById("search-form").action = "http://www.facebook.com/";
          }
        });
      });
    </script>

HTML

<form action="" name="search-form" id="search-form" method="get" accept-charset="UTF-8" class="form-vertical">
      <div class="city">
        <label for="cityId" class="required">Enter your city</label>
        <select id="cityId" name="cityId" data-prefill="location.cityId" class="form-control" placeholder="Enter a city">
          <option value="88">Vizag</option>
          <option value="128">Warangal</option>
          <option value="271">Wardha</option>
          <option value="252">Yamunanagar</option>
          <option value="270">Yavatmal</option>
          <option value="303">Yelanka</option>
          <option value="207">Zirakpur</option>
        </select>
        <span id="city-not-selected-error" class="help-inline"></span> 
        <i class="fa fa-angle-down" aria-hidden="true"></i>
      </div>
      <div class="purpose">
        <label for="purposeId" class="required">Enter Type</label>
        <select id="purposeId" name="purposeId" class="form-control" placeholder="Select Type">
          <option value="select_purpose" selected="selected">Select Type</option>
          <option value="1" id="gl">Google</option>
          <option value="2" id="y">Yahoo</option>
          <option value="3" id="fb">Facebook</option>
        </select>
        <span id="city-not-selected-error" class="help-inline"> </span> <i class="fa fa-angle-down" aria-hidden="true"></i> <span id="purpose-not-selected-error" class="help-inline"> </span>
      </div>
      <div class="show-ofr">
        <input type="submit" name="button" class="btn btn-primary btn-block">
      </div>
    </form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

PHP pattern matching equivalent to selecting elements based on their position in CSS

Struggling with the logic to identify objects in an array by their position. Seeking a PHP equivalent of nth-child(5n + 1) condition, which targets positions like 0, 5, 10, and so on within a loop. One approach could be to divide by 5 and check for whole ...

What is the best approach to retrieve a JSON object from a form exception that has a specific name?

I have a certain form with input fields. My goal is to generate a JSON object from the form, excluding any input whose name is "point". However, my code doesn't seem to be working properly when I use the "not()" function. What am I doing wrong and how ...

When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude f ...

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...

Generate HTML tags dynamically within a JSON document using PHP

Is there a way to incorporate HTML markups (generated dynamically by a CMS) into a JSON file? I am aware that in the html string, one must escape double quotes by adding "" as shown below. { "title": "Title", "da ...

The nested arrays in JavaScript produce different results when viewed in developer tools compared to when they are printed using toString()

There is a strange issue with the nested array in my current project that I need help with. When I log the nested array in console.log as individual values, it displays correctly. For example: console.log("Array: " + arr) //Array: 0,0,0,0,0,0,0,1 Howev ...

How can you animate the background of a website using AngularJS - CSS or JavaScript?

My aim is to create a dynamic animation for the background image when the view changes. The current background image is set through a function defined within MainController: // app/js/controllers.js $scope.getBg = function() { return $route.current.sco ...

Converting Repository Objects to Json in Symfony3

element, I am facing an issue while attempting to send a repository object as JSON. In my controller code, I have implemented a conditional check to ensure that the request is made via XmlHttpRequest. Upon receiving the data and fetching the corresponding ...

Object displaying no visible illumination

Recently, I've been experimenting with this project, and after some trial and error, I've managed to get things working to some extent. As a novice in JavaScript, I'm unsure if the issue I'm facing has a simple solution. The problem is ...

Exploring Selenium WebDriver: Manipulating Table Elements and Iterating Through Rows

Is there a more efficient way to iterate through tables row by row without using Absolute Xpath? In my test case, I need to search for specific data in each row. This was the previous logic of my code: private static int iRow; WebElement sWorkUnitRows = ...

Adding a pathway to a clip path: a step-by-step guide

While attempting to create a wave effect on an image, I hit a roadblock. There are two SVGs involved - one with the path I want to use and the other behaving as expected but with the wrong clip path/shape. However, when I try to insert the desired path, ...

A step-by-step guide on utilizing the reduce function to calculate the overall count of a user's GitHub repositories

I need help finding the total number of repositories for a specific user. Take a look at my code below: Javascript const url = "https://api.github.com/users/oyerohabib/repos?per_page=50"; const fetchRepos = async () => { response = await f ...

Navigate through a nested JSON structure and update the data points

In my possession is a JSON tree structured as follows: { "projects": { "Proj1": { "milestones": { "default": "20150101", "default2": "20140406", "default3": "20140101", ...

The connection between ng-model and ng-repeat, and the comprehension of $scope

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="customersCtrl"> <ul& ...

Is there a way to conceal the second td element?

This is the code I'm using: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> </head> <body style="width:100%;" > ...

Error: The post method in $setup is not defined in Vue Composition API

Dealing with a frustrating issue in my Vue application. One page is functioning perfectly fine, while the other is causing trouble by displaying this error: The first page loads a collection of wordpress posts (Blog.vue) without any issues, but the second ...

Add color to the cells within the table

I need help with dynamically adding colors to my table based on the results. If the result is 'UnSuccessfull', the color should be 'red'. If the result is 'Successful', the color should be 'green'. The challenge I a ...

What could be causing htmlparser2 in Node.js to add extra nodes during document parsing?

Seeking to extract the HTML content of a webpage using node so I can process its DOM to create something unrelated. It's crucial to accurately obtain the DOM representation from the HTML in order to properly process it. Utilizing htmlparser2 for this ...

Error encountered when sending information to web service repeatedly

After populating an array with data, the information is logged into a database using a web service when the array reaches a specific record count. However, upon calling the web service, I encountered an error related to a parameter being passed: Error Ty ...