Reputation: 1599
I am trying to put validation on a page that have two divs
<form>
<div id="first>
<input type="text" name="name"/>
<button id="next">Next</button>
</div>
<div id="second" style="display:none">
<input type="text" name="phone">
<button id="finish">Finish</button>
<button id="back">Back</button>
</div>
</form>
so when I click #next
it shows the second div, but I want to check validation for that div only.
Thanks
Upvotes: 0
Views: 618
Reputation: 9157
Since you've included jQuery in the tags, you should definitely stick with jQuery plugins. This save you a lot of unnecessary work.
Some of the form wizard plugins:
If you really need for custom form wizard, you could start with something like this (according to your HTML sample) :
<form method="post">
<div id="first">
<input id="name" type="text" name="name"/>
<button id="next">Next</button>
</div>
<div id="second" style="display:none;">
<input id="phone" type="text" name="phone">
<button id="finish">Finish</button>
<button id="back">Back</button>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function () {
$('#next').click(function (e) {
e.preventDefault();
if($('#name').val() == ''){
return alert('Type name!');
}
$('#second').show();
$('#first').hide();
});
$('#finish').click(function (e) {
e.preventDefault();
alert('hello ' + $('#name').val() + '! \nYour phone nr. is: ' + $('#phone').val());
});
$('#back').click(function (e) {
e.preventDefault();
$('#first').show();
$('#second').hide();
});
});
</script>
Upvotes: 2
Reputation: 1939
The problem is you are using #next
for all three of your buttons. If you would like to check validation for one div only, you should make all of your IDs different
<button id="next">Next</button>
<button id="finish">Finish</button>
<button id="back">Back</button>
Let's say you only want to check validation for the #next
div.
You can then use the JQuery selector $(#next)
It is still possible, even if all of your buttons have the same ID
You can use $(#next:first)
to select the first button with id #next
However please keep in mind one thing
Classes
can be used multiple times on a page
IDs
should generally only be used once per page
Upvotes: 0