2

I am creating contact form on my website, but i got stuck. I don't know how to put content from variable after each inputs on my website. I can show them into console.log and works perfect but i don't know how to put it on website.

Here's the code:

(function($) {
  $(document).ready(function() {
    var form = $(".contact_form"),
      fields = $("[data-error]");

    fields.on("click", function() {
      $(this).removeAttr('placeholder');
    });

    fields.on("blur", function() {
      var field = $(this);
      field.toggleClass("form_error", $.trim(field.val()) === "");
    });

    form.on("submit", function(e) {
      var hasErrors = false;
      
      fields.each(function(i, elem) {
        var field = $(elem),
          empty = $.trim(field.val()) === "",
          errors = field.data("error");

        console.log(errors);

        // HERE IS ERROR VAR 
        // sth here to put it into html
        
        field.toggleClass("form_error", empty);

        if (empty) {
          hasErrors = true;
        }
      });

      if (!hasErrors) {
        form.submit();
      } else {
        e.preventDefault();
      }
    });
  });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
  <input type="text" placeholder="Imię" data-error="Podaj imię">
  <input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
  <input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
  <input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
  <textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
  <button type="submit" class="przycisk">Wyślij</button>
</form>

4 Answers 4

1

Firstly note that presumably you're trying to check that the fields all have a value. If so, you should put the error message generation logic in the if (empty) code block.

To actually create the HTML for the messages you can use the after() method to insert the error messages after the related input element. If you also wrap the errors in an element, such as a span, which has a class you can easily use that to remove() the elements when the form is submit to be re-evaluated. Try this:

(function($) {
  $(document).ready(function() {
    var form = $(".contact_form"),
      fields = $("[data-error]");

    fields.on("click", function() {
      $(this).removeAttr('placeholder');
    });

    fields.on("blur", function() {
      var field = $(this);
      var valid = $.trim(field.val()) !== "";
      field.toggleClass("form_error", !valid).next('span.form_error').remove();
      if (!valid)
        field.after('<span class="form_error">' + $(this).data('error') + '</span>'); // add new error messages
    });

    form.on("submit", function(e) {
      var hasErrors = false;
      $('span.form_error').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('<span class="form_error">' + errors + '</span>'); // add new error messages
          field.toggleClass("form_error", empty);
        }
      });

      if (!hasErrors) {
        form.submit();
      } else {
        e.preventDefault();
      }
    });
  });
})(jQuery);
span.form_error {
  color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
  <input type="text" placeholder="Imię" data-error="Podaj imię">
  <input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
  <input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
  <input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
  <textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
  <button type="submit" class="przycisk">Wyślij</button>
</form>

Sign up to request clarification or add additional context in comments.

11 Comments

It works yeah, but don't work actually how i need it. This code works for me like this. I am clicking on input and later on background and shows the error that's good. Later I was writing some information to input, click somewhere else and errors class dissappear but span message didn't hide. I must write text into span and click button to hide error, but i want it to be dynamic like toggleClass before.
The spans will only hide when you click the submit button again. If you want them to be re-evaluated on blur() then you would need to write an event handler for that.
Actually thats what i am looking for but don't know how to write it :/ When i write name and click somewhere else span must hide before click button
I edited the answer for you. I changed the logic to show/hide the error in the blur event handler
Ah yeah, my bad, I flipped the logic on the validation check. Try field.toggleClass("form_error", !valid);. I updated the answer
|
0

Use text() for adding string to element or html() for adding html code.

Example:

var text = 'hello world';
$('div#textHere').text(text);

var htmlCode = "<strong>Hello</strong> World";
$('div#htmlHere').html(htmlCode);

Documentation for text() and for html().

2 Comments

But OPs issue seems to be how to create the #textHere element dynamically.
@RoryMcCrossan Oh! But I don't know how to put content from variable after each inputs on my website could mean 2 things: Add content to existing element (my solution) or create a new element in DOM (yours), no? I maybe just missunderstood.
0

When you want to get form field values you use $('#id').val(); the val will get value from form fields. And then you can use $('#id').html('Enter val here') that's it.

Comments

0

use can use text() or html()

Different:

1)If you retrieve text only, u can use text()

2)If you retrieve html element with text, then u can use html();

Eg 1 : -

var text1="hello world";

$(".text").text(text1) ==> hello world

$(".text").html(text1) ==> hello world

Eg 2 : -

var text2="<h1>hello world</h1>";

$(".text").text(text2) ==> '< h1>hello world< /h1>'

$(".text").html(text2) ==>

hello world

`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.