Option in form

Im trying to get a form to work the way I want…
http://www.coronadoshores.ca/add_property.php
The area i have to work on is the rental price
(depending on the Type selected, you either have a monthly rental price or a sale price)
What im trying to do is take it one step further in that if they choose a Type of Rental, a combo box would show up allowing a weekly or monthly rate. then the rental price would change to either /week or /month

Thanks

Can you please move the appropriate code to a separate example, using for example [jsfiddle][1] or [codepen][2], so that everyone looking at your situation doesn’t need to sign up and register to your web page?

Having said that though, here is one way that it might be done:

1 Like

Here is a simple example of the parts of the form that you have mentioned.

<form id="property">
    <p>
        <label>Type:
            <input type="radio" name="type" value="rental"> Rental
            <input type="radio" name="type" value="sale"> Sale
        </label>
    </p>
    <p id="rentaltype">
        <label>Rental type:
            <input type="radio" name="rentaltype" value="monthly"> Monthly
            <input type="radio" name="rentaltype" value="weekly"> Weekly
        </label>
    </p>
</form>

Since radio buttons are used in this example, we can loop through the appropriate radio buttons of the form, attaching an event handler on to each of them.

var form = document.getElementById('property'),
    i;
for (i = 0; i < form.elements.type.length; i += 1) {
    attachTypeHandler(form.elements.type[i]);
}

The handler adds an onchange event to each radio button. If the radio button is rental and it is checked, the rentaltypes will be shown.

function attachTypeHandler(el) {
    el.onchange = function (evt) {
        var input = this;
        var rentaltype = document.getElementById('rentaltype');
        if (input.value === 'rental' && input.checked) {
            rentaltype.classList.remove('hidden');
        } else {
            rentaltype.classList.add('hidden');
        }
    };
}

A little bit of CSS is all we need to hide things:

.hidden {
    display: none;
}

The last little detail is to hide the rental types when the page first starts, which is as easy as triggering the onchange event on one of the radio buttons.

// trigger the onchange event, to hide the rentaltype section
form.elements.type[0].onchange();

This has all been using vanilla JavaScript. If you are using a library such as jQuery then much of this can be simplified quite further.

The example can be seen at http://jsfiddle.net/gjwfg35e/

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.