简体   繁体   中英

jQuery - placeholder values after submiting form contact

I want to improve my form contact using jQuery. I want to clear input fields after clicking and show placeholders values on submit button. I have placeholders in my input fields and want to load them into variable and show them after ajax post method.

<input type="text" name="name" placeholder="Name" data-error="Please write name">

and jQuery code:

form.on("submit", function(e) {
        e.preventDefault();

        var hasErrors = false;

        $('div.error_message').remove(); // Remove any old errors when submitting the form

        fields.each(function(i, elem) {
            var field = $(elem),
                empty = $.trim(field.val()) === "",
                errors = field.data("error");

            if (empty) {
                hasErrors = true;
                field.after('<div class="error_message">' + errors + '</div>'); // add new error messages
                field.toggleClass("form_error", empty);
            }
        });

        if (!hasErrors) {
             var formData = $(this).serializeArray();
             $.post(form.attr("action"), formData, function(data) {
                 console.log(data, true);

            $(".przycisk").on("click", function() {
                var placeholder = $("input[placeholder]");
                console.log(placeholder);
                $("input, textarea").val(placeholder);

            });

        } else {

        }

        return false;
    });

you have to say wich attribute from input do you want to use. in jquery is so: .attr('attributeName') now you can select your any attribute (like placeholder)

change your code like this:

 $("input, textarea").val(placeholder.attr('placeholder'));

see my code here : https://codepen.io/miladfm/pen/ZyOEWX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM