Question

Good afternoon! I am building a contact form in Contact Form 7 in Wordpress. And I need a functionality where one of the form fields is a number selector (for example, 1-10) and I need the number that is selected to be calculated and drop down the number of fields to be inputted.

I'll try to explain the best I can. So if someone types in the 4...I need a drop down of four input fields.

I have looked for some jquery script for this functionality, but I'm basically at a deadend. If anyone has any suggestions, I would much appreciate it!

Was it helpful?

Solution

Here's an option using jQuery (jsFiddle)

HTML

Number of inputs:
<select class="numInputs" onChange="buildInputs(this);">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<div class="inputs"></div>

Javascript (jQuery)

$(document).ready(function () {
    // set onchange event for the select box.
    $('.numInputs').change(function () {
        // clear any inputs added to the div.
        $('.inputs').empty();
        // get number of inputs to add from select box.
        var num = $('.numInputs option:selected').text();
        // build the inputs.
        for (var i = 1; i <= num; i++) {
            $('<input type="text"/><br/>').appendTo('.inputs');
        }
    })
});

OTHER TIPS

You would use javascript, I wrote a simple sample for you. I haven't ever worked with wordpress, but this just works on it's own, and I would think you should be able to just put it in.

Javascript

<script type="text/javascript">
    function thing(){
        var num = document.getElementById("number").value; //Get the number out of the number field
        document.getElementById("select").innerHTML = ''; //Get rid of the placeholder, or the old ones
        for (var i = 0; i < num; i++){
            var newOpt = document.createElement('option');
            newOpt.innerHTML = i; //It'll just have a dropdown for 0 to the number
            newOpt.value = i;
            document.getElementById("select").appendChild(newOpt);
        }
    }
</script>

HTML

<form>
    Number: <input type="number" name="number" id="number" onblur="thing();">
    <select id="select">
        <option value="no">Enter a number first</option>
    </select>
    <input type="submit" value="Submit">
</form>

Also, instead of using onblur, you could use onkeyup or something. onblur is for when it loses focus.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top