Home > front end >  Show a form based on data from another page on the website
Show a form based on data from another page on the website

Time:01-12

I have a client that wants a specific feature and I'm still new to javascript so I'm trying to figure a way to make it possible.

When a user first lands on the website, they'll be asked to specify their role. They will have the options of buyer, seller, or agent. On a separate contact page, we will have a form block. However, we want to have 3 different forms based on the specific role of the user.

For example, if they indicated they are a buyer, they will see a specific form for them. If they indicated that they are a seller, they will see the seller-specific form on the contact page.

Is this even possible and what would be the best method of doing it?

CodePudding user response:

You can create 3 hidden forms and change the visibility based on the role selection change with a function.

or better use AJAX to change the form tag innerHTML according to your requirements. create 3 separate html files(form1.html,form2.html,form3.html) and add your inputs for each forms. In the main file use the ajax to load the forms.

<select onchange="loadForm(this.value)">
    <option value="">select a role</option>
    <option value="form1">Salse</option>
    <option value="form2">Admin</option>
    <option value="form3">Customer</option>
</select>

<form action="" id="form">Select a role Please</form>

<script>
    
    function loadForm(formName) {
        if(role !=""){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("form").innerHTML =
                    this.responseText;
                }
            }
        xhttp.open("GET", formName '.html', true);
        xhttp.send();
    }else{
        document.getElementById("form").innerHTML = "Select a role Please"
    }
};
</script>

CodePudding user response:

  1. Set an input that users will choose so you know if they are a buyer, seller, or agent. This can be radio buttons or a select input. Call this "input1"
  2. Create your three forms and keep them hidden.
  3. Put an event listener on the "input1" so if the user clicks or selects, you display the respective form.

If you don't want any being able to manipulate your forms, you can have your form html added/appended or removed by javascript so that the forms are not easily available with few website manipulations.

  •  Tags:  
  • Related