Question

I'm creating a form to my site, and I want to make something like custom attribute "required". I have a few inputs with Id "required". Something like:

<input type="text" id="required">
<input type="text" id="required">
<input type="text" id="required">

I have a script who gives some attributes and initializes popover. But here's a problem. I want to create a script who will search for inputs without text, and will act on first in array. It was worked but only in first input. If I will write something there, script doesn't work and nothing happens.

Here's the code (I know it doesn't work on first input too, but I hope this will help you to understand what I want to achieve).

$('#check').click(function() {
var x = $("input").filter(function(){
   return $("#required").val().trim() == '';
});
x[0].val('');
x[0].addClass("input-error");
x[0].attr({
  "data-toggle": "popover",
  "data-container": "body",
  "data-content": "Wypełnij to pole",
  "data-trigger": "manual"
});
x[0].popover('show');
$('html, body').animate({
    scrollTop: $("#required").offset().top-100
}, 200);

});
x[0].keypress(function() {
x[0].removeClass("input-error");
  x[0].popover('destroy'); 
});
Was it helpful?

Solution

Javascript:

$('#check').click(function() {
    var x = $("input[id=required]").filter(function() {
        return $(this).val().trim() == '';
    });

    $(x).each(function (index) {
        $(this).val('');
        $(this).addClass("input-error");
        $(this).attr({
          "data-toggle": "popover",
          "data-container": "body",
          "data-content": "Wypełnij to pole",
          "data-trigger": "manual"
        });
        $(this).popover('show');  
        $(this).keypress(function() {
            $(this).removeClass("input-error");
            $(this).popover('destroy'); 
        });
    });

    if(x.length > 0) {
        $('html, body').animate({
            scrollTop: $(x[0]).offset().top-100
        }, 200);
    }

});

JSFiddle http://jsfiddle.net/GnRdH/4/

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