choose among various options in Javascript

I'm currently using PHP and AJAX to create a basic CRUD system. I want to display a form with three buttons: Grabar, Modificar, and Eliminar. The issue I'm facing is determining the action to take based on which button is clicked. For instance, clicking the Grabar button should redirect to registro.php, clicking Modificar should redirect to modificar.php, and the same logic applies to the Eliminar button redirecting to eliminar.php.

How can I achieve this functionality in JavaScript? This is what I have so far:

function enviarDatosEmpleado(){

  //div where the results will be displayed
  divResultado = document.getElementById('resultado');
  //collecting input values
  nom=document.nuevo_empleado.nombre.value;
  ape=document.nuevo_empleado.apellido.value;
  web=document.nuevo_empleado.web.value;
  valor=document.nuevo_empleado.Submit.value;

  alert(valor);
}
  /* 
  ajax=objetoAjax();

  ajax.open("POST", "registro.php",true); */

And here is my form:

<form name="nuevo_empleado" action="" onsubmit="enviarDatosEmpleado(); return false">
            <h2>New employee</h2>
                <table>
                <tr>
                    <td>Names</td><td><label><input name="nombre" type="text" /></label></td>
                </tr>
                <tr>
                    <td>Last Name</td><td><label><input type="text" name="apellido"></label></td>
                </tr>
                <tr>
                    <td>Website</td><td><label><input name="web" type="text" /></label></td>
                </tr>
                <tr>
                    <td>&nbsp;</td><td><label><input type="submit" name="Submit" value="Grabar" /></label></td>
                    <td><label><input type="submit" name="submit" value="Modificar" /></label></td>
                    <td><label><input type="submit" name="submit" value="Eliminar" /></label>
                    </td>
                </tr>
                </table>
        </form>

Can you also assist me with writing the if statement for this functionality?

Answer №1

Give this a try!

  document.getElementsByName('new_employee')[0].onclick = function(e) {
    e.preventDefault();

    var redirectLinks = {
        save: 'save.php',
        edit: 'edit.php',
        delete: 'delete.php'
    };

    if (e.target.type === 'submit') {
        window.location.href = redirectLinks[e.target.value.toLowerCase()]; 
    }
  };

Check out the JSBin Demo here: http://jsbin.com/kefapofato/1/edit?html,js,output

Answer №2

Revise and update the action property within the form.

switch (valor) {
  case 'Save':
    document.new_employee.action = 'register.php';
    break;
  case 'Edit':
    document.new_employee.action = 'edit.php';
    break;
  case 'Delete':
    document.new_employee.action  = 'delete.php';
    break;
}

However, a more efficient approach would be to set up individual handlers for each button's click event, ensuring that unique actions are triggered for each one.

<form ...>
  ...
  <input type='submit' value='Save' onclick='this.form.action = "register.php";'>
  <input type='submit' value='Edit' onclick='this.form.action = "edit.php";'>
  ...
</form>

If you wish to implement the commented-out JavaScript provided at the end of the code, you must make a couple of adjustments. Firstly, modify your event handler to accept an event parameter, which is necessary to prevent the form from being submitted by the browser itself.

For different actions based on the selected button, a switch statement similar to the one in the initial example can be utilized.

function sendEmployeeData(event) {
  event.preventDefault(); // this prevents the browser from submitting the form
  ...
  var ajax = new XMLHttpRequest();
  switch (valor) {
    case 'Save':
      ajax.open('POST', 'register.php', true);
      break;
    case 'Edit':
      ajax.open('POST', 'edit.php', true);
      break;
    case 'Delete':
      ajax.open('POST', 'delete.php', true);
      break;
  }

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

Dealing with jQuery JSON AJAX Error Handling for Data Response

Looking to generate a dynamic select input (dropdown menu) from JSON data. I've experimented with two methods to obtain a JSON object for the dropdown menu Select input, labeled Attempt 1 and Attempt 2 in the commented out JS code. Although I am abl ...

Assistance requested with Javascript for an HTML dropdown menu

My question involves utilizing two HTML drop down menus. <select> <option value="">Please Select</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

Load the dropdown menu with JSON data but encounter an error: SyntaxError caused by an unexpected token `{` in

I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file. Here is an example of my JSON data: {"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlin ...

Interactive hover text appears when you mouse over the SVG path

Does anyone know the simplest way to display sample text when hovering over an svg path? Below is my CSS code: <style> path:hover{ fill:yellow;stroke:blue; } .available { fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;strok ...

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

Extracting data from several pages using the same URL, but with varying ajax responses

I've been attempting to scrape all the reviews for a specific book on Goodreads.com. url= https://www.goodreads.com/book/show/320.One_Hundred_Years_of_Solitude?ac=1&from_search=true The initial scrapping of the first page was successful using Py ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Display just the minutes using react-countdown-circle-timer in a React application

Looking to create a test page in React featuring a countdown timer set at 50 minutes, I integrated the react-countdown-circle-timer module. However, I encountered an issue where the minutes displayed do not change dynamically as they should. My goal is to ...

After successfully posting a tweet, I have not heard back from Twitter

My objective is to achieve the following on click: Share the URL and text on Twitter in a popup window Receive a response from Twitter indicating whether the tweet was successful or failed Close the popup window after the tweet is successfully pos ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

Resolving the issue of multiple instances of React within a single application

I'm currently working on a React module in my local environment. To link the module, I am using npm link. Although the module is being imported successfully, the hooks inside the module are failing with the following error message: Invalid hook call ...

Upon refreshing the page, nested React routes may fail to display

When I navigate to the main routes and their nested routes, everything works fine. However, I encounter an issue specifically with the nested routes like /register. When I try to refresh the page, it comes up blank with no errors in the console. The main r ...

Please refresh the page in order to utilize the newly updated cookies

I have a specific process that involves: A button triggers the function fcn1 and redirects to a page called p1 Function fcn1 retrieves 6 strings from a backend SQL database The 6 strings are then stored in cookies Page p1 reads the 6 cookies and displays ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Pressing the "Enter" key in a .Net WinForm Browser Control

How can I simulate the Enter key press event on a web page using the GeckoFX Web Control? I am unable to use SendKeys.Send({ENTER}) Is there a method to trigger the Enter key using JavaScript within a webpage? ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

Embeddable javascript code can be enhanced by incorporating references into the header

I have developed a basic calculator application using HTML, JavaScript, JQuery, and CSS. My intention is to allow others to embed this calculator app on their own web pages by utilizing a file named generate.js. Within this file, there are several documen ...