Questions Populate input text dynamically by click of button jQuery / Javascript

4768 asked on

I have a form on a php page that is being used on mobile devices. There are a number of input boxes in the form that are not relevant depending on the type of job the user is performing and filling in the job details for.

To save them time writing in N/A on those that are not relevant to the job they are entering details for I want to permit them to click on a small button which is on the side of the text input box.

Then when they are filling in the form they can simply press the N/A button to populate the box with "N/A" thus saving them time and effort.

Can this be done on several fields?

Regards

Alan

    1 Answer
    1 answered on

    Sure why not, you did not mention how input fields to be populated. Should one button populate "N/A" in all the fields or something like this? Form :

    <form id="job-form">
    <ul class="form-style">
        <li>
            <label>Name <span class="required">*</span></label>
            <input type="text" name="field1" class="field-long" /><button data-field="field1" class="na_btn"> N/A </button>
        </li>
        <li>
            <label>Field One <span class="required">*</span></label>
            <input type="text" name="field2" class="field-long" /><button data-field="field2" class="na_btn"> N/A </button>
        </li>
    
        <li>
            <label>Field One <span class="required">*</span></label>
            <input type="text" name="field3" class="field-long" /><button data-field="field3" class="na_btn"> N/A </button>
        </li>
        <li>
            <label>Field One <span class="required">*</span></label>
            <input type="text" name="field4" class="field-long" /><button data-field="field4" class="na_btn"> N/A </button>
        </li>
        <li>
            <input type="submit" value="Submit" />
        </li>
    </ul>

    If you are using jQuery library, you can do this :

    $(".na_btn").click(function(e) {
        e.preventDefault();
        var input_name = $(this).data("field");
        $("input[name="+input_name+"]").val("N/A");
    });

    Or pure Javascript :

    //Javascript
    var na_buttons = document.getElementsByClassName("na_btn");
    for (var i = 0; i < na_buttons.length; i++) {
        na_buttons[i].addEventListener('click', function(e){
            var input_name = this.dataset.field;
            document.getElementsByName(input_name)[0].value = "N/A";
            e.preventDefault();
        });
    }

    jQuery Demo :