how do i create a auto adaptive form [closed]

2019-09-21 18:48发布

问题:

I want to create a dynamic form on my website.

On my site a have several forms that are subject specific but i also have a contact us form with a subject dropdown from which they can choose any of the subjects that the subject specific forms cover.

now if they select website design enquiry i need to ask them for their website address whereas website address isn't relevant to all of the other enquiry subjects, if they ask about website hosting i again need their website address but also need their preference of hosting package.

if they ask about mobile app development i don't need the website or hosting package fields but need 4 checkboxes to appear to allow them to tick the ones relating to the platforms for which the mobile app is to be developed for.

so it needs to be auto adaptive to the type of enquiry selected.

how can i acheive this?

回答1:

you can use jQuery, to achieve that.

you need to add jQuery change listener on the dropdown select. then you add form elements to a container accroding to selected value.

here is a small example

$( ".select" ).change(function() {
    var value = this.val();
    if(value == "webDesign")
    {
        $("#fieldsContainer").append('<input name="webUrl" class="inputField"/>');
    }
});

you can also change action url accroding to select Value so it will be more easy to handle different forms

if(value == "webDesign")
{
     $("form#myForm").attr('action','process.php?type=webdesign');
}


回答2:

Your question is quite vague, but the answer to it is that there are many ways to achieve it. One of the most commonly used ways is to use javascript (or some library like jQuery using js).

I have put together a basic function for you that will showcase how it's done in pure js:

HTML:

Services: <select id="service">
    <option value="stuff">stuff</option>
    <option value="webdesign">webdesign</option>
</select><br />
<span id="webname">Website: <input type="text" /></span>

JS:

document.getElementById("service").onchange = function () {
    if (document.getElementById("service").options[document.getElementById("service").selectedIndex].value == "webdesign")
        document.getElementById("webname").style.display = "none";
    else
        document.getElementById("webname").style.display = "block";
}

Here is the demo page of the above code: http://jsfiddle.net/w3pGr/