How to fix element position while validating input values?

Hi there

this is my jsfiddle.net
http://jsfiddle.net/vngx/t2f4m2ea/11/

based on this I have 2 questions
1)When I try to validate Mobile section then Add-Another Button is changing its position.All Validation text are coming in the right of input tag I want them to be below of input field that is set for.

2)In case of mobile_add_other when I add more than one mobile numbers then if forgot to add mobile numbers then it is only validating first added user_mobile_other block not all fields that I added(You can check by click on it ore than 3 times on “Add Another” button.I want each field to be validate in user_mobile_other

How to do this?

Thanks

:sleeping:

  1. Use: .error{display: block; }

how and where?
can you edit my code?

Aw come on.

1 Like

ok
at least where to put this line?

It’s CSS

1 Like

Ok Just one thing jQuery validates form’s input fields by theirs ids or names?

This is something you can easily experiment with and find out.

In your fiddle, this works:

FirstName<input type="text" name="user_first_name" id="user_first_name"/>

so try this:

FirstName<input type="text" id="user_first_name"/>

and then this:

FirstName<input type="text" name="user_first_name"/><br>

not working yet

What’s not working yet?

The jquery validation routine needs the name attributes to be unique otherwise it doesn’t work. This means that when you clone a field you will need to increment the name attribute so that it is unique and then add new message rules for it for the validation.

That would leave you with something like this:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.block_template {
	display: none;
}
</style>
</head>


<body>
<form method="post" id="register_form">
		FirstName
		<input type="text" name="user_first_name">
		<br>
		LastName
		<input type="text" name="user_last_name" >
		<br>
		Mobile
		<input type="text" style="margin-left: 84px;" maxlength="10" name="user_mobile" >
		<input type="button" id="mobile_Add" value="AddAnother">
		<br>
		<div class="mobile_block block_template">
				<input class="mobile_number" type="text" style="margin-left: 135px;" name="user_mobile_other"  maxlength="10" required>
				<input type="button" value="Delete" id="mob_del" >
		</div>
		<div id="mobile_numbers"></div>
		<input type="submit" value="Submit">
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>

<script>
$(document).ready(function() {

    function simpleformvalidation() {

        $("#register_form").validate({
            rules: {
                user_first_name: "required",
                user_last_name: "required",
                user_mobile: "required",
                user_mobile_other: "required"
            },
            messages: {
                user_first_name: {
                    required: "Please Enter First name"
                },
                user_last_name: {
                    required: "Please Enter Last name"
                },
                user_mobile: {
                    required: "Please Enter Mobile Number"
                },
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

    }
    simpleformvalidation();

    //this Function is called to addition of mobile numbers
    $("#mobile_Add").click(function() {
        var c = $(".block_template").clone();
			  c.removeClass("block_template");
        $("#mobile_numbers").append(c);
				 $("#mobile_numbers input[type=text]").each(function(index) {
             var theNameAttribute = "user_mobile_other";
						 $(this).attr('name', theNameAttribute + index);
        });
        $('[name*="user_mobile_other"]').each(function() {
            $(this).rules('add', {
                required: true,
                messages: {
                    required: "Please Enter Mobile Number Another"
                }
            });
        });

    });

    //This function is called when delete button is called in mobile
    $('#mobile_numbers').on('click', '#mob_del', function() {
        // remove parent container
        $(this).parent('.mobile_block').remove();
				
				
    });

});
</script>
</body>
</html>

The above is a working example but I didn’t tidy up your html.

Hopefully Pullo or Paul can check the logic of the script and tidy it up a bit.:slight_smile:

Yes the logic was a little flawed and the above does not work when inputs are deleted out of sequence because the jQuery validation also adds unique ids to the error messages and ties them into the input. This means you would also need to update those values also and it starts getting complicated.

It may be easier just to keep a counter incrementing.

e.g.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.block_template {
	display: none;
}
</style>
</head>

<body>
<body>
<form method="post" id="register_form">
		FirstName
		<input type="text" name="user_first_name">
		<br>
		LastName
		<input type="text" name="user_last_name" >
		<br>
		Mobile
		<input type="text" style="margin-left: 84px;" maxlength="10" name="user_mobile" >
		<input type="button" id="mobile_Add" value="AddAnother">
		<br>
		<div class="mobile_block block_template">
				<input class="mobile_number" type="text" style="margin-left: 135px;" name="user_mobile_other"  maxlength="10" required>
				<input type="button" value="Delete" id="mob_del" >
		</div>
		<div id="mobile_numbers"></div>
		<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>

<script>
$(document).ready(function() {

    function simpleformvalidation() {

        $("#register_form").validate({
            rules: {
                user_first_name: "required",
                user_last_name: "required",
                user_mobile: "required",
                user_mobile_other: "required"
            },
            messages: {
                user_first_name: {
                    required: "Please Enter First name"
                },
                user_last_name: {
                    required: "Please Enter Last name"
                },
                user_mobile: {
                    required: "Please Enter Mobile Number"
                },
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

    }
    simpleformvalidation();

    //this Function is called to addition of mobile numbers
    $("#mobile_Add").click(function() {
        var c = $(".block_template").clone();
			  c.removeClass("block_template");
        $("#mobile_numbers").append(c);
				updateNameAttribute();
    });
		
		var nameIncrement = 0;
		function updateNameAttribute(){
			$("#mobile_numbers input[type=text]").each(function(index) {
            var theNameAttribute = "user_mobile_other";
						$(this).attr('name', theNameAttribute + nameIncrement);
            nameIncrement ++;
						$(this).rules('add', {
                required: true,
                messages: {
                    required: "Please Enter Mobile Number Another"
                }
            });
        });
		}


    //This function is called when delete button is called in mobile
    $('#mobile_numbers').on('click', '#mob_del', function() {
        // remove parent container
        $(this).parent('.mobile_block').remove();
    });
});
</script>
</body>
</html>

Unless the others have got time to tidy it up :smile:

EDIT:

Here’s another attempt that tidies up the sequence a bit.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.block_template {
	display: none;
}
</style>
</head>

<body>
<body>
<form method="post" id="register_form">
		FirstName
		<input type="text" name="user_first_name">
		<br>
		LastName
		<input type="text" name="user_last_name" >
		<br>
		Mobile
		<input type="text" style="margin-left: 84px;" maxlength="10" name="user_mobile" >
		<input type="button" id="mobile_Add" value="AddAnother">
		<br>
		<div class="mobile_block block_template">
				<input class="mobile_number" type="text" style="margin-left: 135px;" name="user_mobile_other"  maxlength="10" required>
				<input type="button" value="Delete" class="mob_del" >
		</div>
		<div id="mobile_numbers"></div>
		<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>

<script>
$(document).ready(function() {

    function simpleformvalidation() {

        $("#register_form").validate({
            rules: {
                user_first_name: "required",
                user_last_name: "required",
                user_mobile: "required",
                user_mobile_other: "required"
            },
            messages: {
                user_first_name: {
                    required: "Please Enter First name"
                },
                user_last_name: {
                    required: "Please Enter Last name"
                },
                user_mobile: {
                    required: "Please Enter Mobile Number"
                },
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

    }
    simpleformvalidation();

    //this Function is called to addition of mobile numbers
    $("#mobile_Add").click(function() {
        var c = $(".block_template").clone();
			  c.removeClass("block_template");
        $("#mobile_numbers").append(c);
				updateNameAttribute();
    });
		
		
		function updateNameAttribute(){
			$("#mobile_numbers input[type=text]").each(function(index) {
            var theNameAttribute = "user_mobile_other";
						var theLabel = $(this).next('label');
						$(this).attr('name', theNameAttribute + index);
						theLabel.attr('for', theNameAttribute + index);
						theLabel.attr('id', theNameAttribute + index + '-error');
						$(this).rules('add', {
                required: true,
                messages: {
                    required: "Please Enter Mobile Number Another"
                }
            });
        });
		}


    //This function is called when delete button is called in mobile
    $('#mobile_numbers').on('click', '.mob_del', function() {
        // remove parent container
        $(this).parent('.mobile_block').remove();
				updateNameAttribute();
    });
});
</script>
</body>
</html>

EDIT 2:

Had a few minutes so tidied the html up and made it valid.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.mobile_block, #mobile_numbers {
	display:block;
	position:relative;
}
.mobile_block {width:270px}
.block_template {display: none;}
#register_form label {
	display:inline-block;
	vertical-align:middle;
	width:135px;
	margin:5px 0;
}
#register_form label.error {
	width:auto;
	display:block;
	color:red;
	margin:0 0 5px 140px;
	font-style:italic;
	font-size:smaller;
}
#register_form input[type=text] {
	margin-left:140px;
	margin:5px 0;
	width:180px;
	padding:3px 5px;
}
#mobile_numbers {margin-left:140px;}
#mobile_numbers label.error {margin:0 0 5px}
#mobile_numbers input[type=text] {margin-left:0}
#mobile_Add {
	display:block;
	margin:10px 0 20px 140px;
}
.mob_del {
	position:absolute;
	right:0;
	top:6px;
	width:60px;
	padding:2px 0;
	border-radius:4px;
	border:1px solid #ccc;
}
.mob_del:hover{background:#f9f9f9;}
</style>
</head>
<body>
<form method="post" id="register_form">
		<fieldset>
				<legend>Form clone and validation example</legend>
				<div class="input-row">
						<label for="user_first_name">First Name</label>
						<input type="text" name="user_first_name" id="user_first_name">
				</div>
				<div class="input-row">
						<label for="user_first_name">Last Name</label>
						<input type="text" name="user_last_name" id="user_last_name">
				</div>
				<div class="input-row">
						<label for="user_mobile">Mobile</label>
						<input type="text" maxlength="10" name="user_mobile" id="user_mobile">
				</div>
				<div class="mobile_block block_template">
						<input class="mobile_number" type="text"  name="user_mobile_other"  maxlength="10" required>
						<input type="button" value="Delete" class="mob_del" >
				</div>
				<div id="mobile_numbers"></div>
				<div class="input-row">
						<input type="button" id="mobile_Add" value="Add Another Mobile Number">
						<input type="submit" value="Submit">
				</div>
		</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script> 
<script>
$(document).ready(function() {

    function simpleformvalidation() {

        $("#register_form").validate({
            rules: {
                user_first_name: "required",
                user_last_name: "required",
                user_mobile: "required",
                user_mobile_other: "required"
            },
            messages: {
                user_first_name: {
                    required: "Please Enter First name"
                },
                user_last_name: {
                    required: "Please Enter Last name"
                },
                user_mobile: {
                    required: "Please Enter Mobile Number"
                },
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

    }
    simpleformvalidation();

    //this Function is called to addition of mobile numbers
    $("#mobile_Add").click(function() {
        var c = $(".block_template").clone();
			  c.removeClass("block_template");
        $("#mobile_numbers").append(c);
				updateNameAttribute();
    });
		
		
		function updateNameAttribute(){
			$("#mobile_numbers input[type=text]").each(function(index) {
            var theNameAttribute = "user_mobile_other";
						var theLabel = $(this).next('label');
						$(this).attr('name', theNameAttribute + index);
						theLabel.attr('for', theNameAttribute + index);
						theLabel.attr('id', theNameAttribute + index + '-error');
						$(this).rules('add', {
                required: true,
                messages: {
                    required: "Please Enter Another Mobile Number"
                }
            });
        });
		}


    //This function is called when delete button is called in mobile
    $('#mobile_numbers').on('click', '.mob_del', function() {
        // remove parent container
        $(this).parent('.mobile_block').remove();
				updateNameAttribute();
    });
});
</script>
</body>
</html>

Codepen example.

Thanks to both of you

Here is my jsfiddle.net
http://jsfiddle.net/vngx/n924yu3L/

Still not working

The first thing getting in your way is this:

Where did I find that? You can see it in the javascript console (ctrl+shift+J)

Use the “tide up” button at the top of the jsfiddle editor to fix indenting and layout problems. You’ll see that the end of your script seems to have a duplicated last line that needs to be removed.

After removing that, you’ll see that the layout is all good.

Next, you need to get the validation library working.

You have jQuery chosen in the frameworks area, but you also need to include an external resource for the validation.
You can use the one at http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js

@Paul_Wilkins:
Thanks its working now

But one more thing I want all validation messages below the input fields and position of 'add another" should not change.

I hope you got my point

For that you will be wanting to update the CSS instead.

You can position the errors below for example, by setting them to display as a block and push them across.

label.error {
    display: block;
    margin-left: 5em;
}

The good people in the CSS forum are likely to be able to help you much further with such layout issues.

Ok position related display message thing is fix somehow using your code

but what about fixing position of add another button?

That’s a good question.

The tricky part is that the error immediately follows the input, but you want the “add another” button to remain just after the input instead.

I can think of a few options in regard to this but they don’t seem to be an elegant enough of a solution. It would be great to gain some input from some CSS veterans here.