I am trying to create a form which contains a question field and an answer field.
The question field remains constant and on button click the answer field gets incremented to the max count set to it.
When a user enters data into these fields simultaneously I want to show them the preview of the text they entered.
I am able to do it for a single field but the answer field is an incrementing field and I am unable to figure out how to show a preview for the incremented fields.
HTML:
<fieldset id="5" style="padding-top:30px;">
<div>
<b>Question</b>
<input type="text" name="word" class="word2"
placeholder="Question" style="margin-left:32px;
width:150px;"/>
</div>
</fieldset>
<fieldset id="6">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<div class="controls">
<form role="form" autocomplete="off">
<b>Choice(s)</b><br /><br />
<div class="entry input-group col-xs-3">
<input class="word" name="fields[]" type="text" placeholder="Choice" />
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
<br>
</div>
</div>
</div>
</div>
</fieldset>
<fieldset id="2">
<div style="padding: 20px;">
<b><span class="word2_preview"></span></b>
</div>
</fieldset>
<fieldset id="3">
<div style="padding:20px;">
<b><span class="word_preview"></span></b>
</div>
</fieldset>
JavaScript:
$(function () {
$(document).on('click', '.btn-add', function (e) {
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function (e) {
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
</ script >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script> <
script type = "text/javascript" >
$(function () {
$(".word").keyup(function () {
var word = $(this).val();
$(".word_preview").html(word);
return false;
});
});
</script>
Change keyup event as bellow
$(".word").bind('keyup',function () {
addText();
return false;
});
Add addText function as bellow
function addText(){
var text = "";
$('input.word').each(function(i, obj){
text+=obj.value + "<br>";
console.log(text);
});
$(".word_preview").html(text);
}
Also add the bellow block in to .btn-add setion
$(".word").unbind('keyup').bind('keyup',function () {
addText();
return false;
});
That's all
Use jQuery `text()` method
$(function () {
$(document).on('click', '.btn-add', function (e) {
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
})
.on('click', '.btn-remove', function (e) {
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
$(function () {
$(document).on("keyup",".word",function () {
var word = $(this).val();
var parent_index = $(this).parent(".entry").index();
var id = "#word_prev_" + parent_index;
var elem = document.getElementById(id);
//if element was created just show the word preview
if(elem){
console.log("exists");
$(elem).text(word);
}
//if not create it and show the preview
else
{
console. log("creating");
$("#word_preview_wrapper > div").append("<b><span id=" + id +">" + word + "</span></b><br/>");
}
//return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<fieldset id="5" style="padding-top:30px;">
<div>
<b>Question</b>
<input type="text" name="word" class="word2"
placeholder="Question" style="margin-left:32px;
width:150px;"/>
</div>
</fieldset>
<fieldset id="6">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<div class="controls">
<form role="form" autocomplete="off">
<b>Choice(s)</b><br /><br />
<div class="entry input-group col-xs-3">
<input class="word" name="fields[]" type="text" placeholder="Choice" />
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
<br>
</div>
</div>
</div>
</div>
</fieldset>
<fieldset id="word_preview_wrapper">
<div style="padding:20px;">
</div>
</fieldset>
Like this I guess
Related
I have created Dynamic Add / Remove fields. Everything is working perfectly. I want sum of values from Amount field to be displayed on real time basis using JavaScript. I have tried but am unable to do. I am not much familiar with JavaScript.
Following is code:
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
You can use add keyup event listener and calculate sum as:
function calculateSum() { //Add a calculateSum function
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum(); //Call calculateSum to update the sum valaue
return false;
});
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum); //update when keyup
Demo:
var i = 0;
jQuery(document).ready(function($) {
function calculateSum() {
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
I think you can do it with this code:
function calcAmount(){
var amount = 0;
$('input[name="allocate_amount[]"]').each(function(){
amount = amount + $(this).val();
});
return amount;
}
jQuery(document).ready(function($) {
$("input[name="allocate_amount[]]").blur(function(){
$("#sum").html(calcAmount());
});
});
Okay, I try to update your code: and it works fine:
main changes:
- assign ids to input fields
- make changes in function
have a look to jsfiddle
https://jsfiddle.net/dupinderdhiman/ygvphmxq/31/
Main changes:
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" id='value1' name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id='value2' name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount. <span id="sum"></span></i></small>
</div>
</div>
<script type="text/javascript">
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
debugger;
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
return false;
});
});
</script>
</body>
</html>
I'm trying to make a MODAL step by step validating each step, but I can only validate the input with error, but I can not validate the select.
wanted that when the value of the select is equal to ZERO (0) the validation occurs as well.
Could someone help me with this JS? I would be extremely grateful.
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
<div class="container">
<div class="row">
<h2>Multistep form wizard on modal</h2>
<div class="center"><button data-toggle="modal" data-target="#requestform" class="btn btn-primary center-block">Click Me</button></div>
</div>
</div>
<div class="modal fade" id="requestform" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Proposta</h3>
</div>
<div class="modal-body">
<!-- Steps starts here -->
<div class="requestwizard">
<div class="requestwizard-row setup-panel">
<div class="requestwizard-step">
1
<p>Selecione um contato</p>
</div>
<div class="requestwizard-step">
2
<p>Selecione um curso</p>
</div>
<div class="requestwizard-step">
3
<p>Forma de pagamento</p>
</div>
</div>
</div>
<br>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<div class="form-group">
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Contato" />
</div>
<hr>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercountry">
<option value="0" class="selectcountry">Country</option>
<option value="201" class="selectcountry">Australia</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercity">
<option value="0" class="selectcity">City</option>
<option value="101" class="selectcity">California</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filterregion">
<option value="0" class="selectregion">Region</option>
<option value="3" class="selectregion">Brazil</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Curso" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinstallment"/></label>
<input type="text" class="form-control" placeholder="First installment" id="finstallment" name="finstallment" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.numberparcels"/></label>
<select class="form-control custom-select" name="parcels" required>
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinvoice"/></label>
<input type="date" class="form-control" placeholder="Invoice maturity" name="expiration_date" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"><spring:message code="label.selectpaymentplan"/></label>
<select class="form-control custom-select" name="payment_plan" required>
<option value="1">Bank slip</option>
</select>
</div>
</div>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Enviar</button>
</div>
</div>
</div>
</form>
<!-- Form ends here -->
</div>
</div>
</div>
</div>
you need to check for the control type in the for loop inside allNextBtn.click event like this:
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0)
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
and change this line:
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
to this:
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
here is the full js code:
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
isValid = true;
$(".form-group").removeClass("has-error");
//BEGIN EDIT
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0))
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
//END EDIT
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
I have a page that displays list of boxes, when i search once it gives me the result perfectly, when i search again, nothing is shown at all
SEARCH BOX:
<form class="search-form">
<input type="text" id="searchfield" class="input-medium search-query" placeholder="Search">
<button type="submit" class="btn">Search</button>
</form>
HTML:
<div class="col-md-4 col-sm-6">
<div class="mybox">
<div data-title="Titleshoudbehere" class="myitem">
<a target="_blank">
<div class="mytitle">
<p>Title is here</p>
</div>
<div class="footer">
<p>#hashtag </p>
</div>
</a>
</div>
</div>
</div>
JS:
$('.search-form').on('submit', function() {
return false;
});
$('.search-form .btn').on('click', function(e) {
var query = $.trim($(this).prevAll('.search-query').val()).toLowerCase();
$('div.mybox .mytitle').each(function() {
var $this = $(this);
if ($this.text().toLowerCase().indexOf(query) === -1)
$this.closest('div.col-md-4.col-sm-6').fadeOut();
else $this.closest('div.col-md-4.col-sm-6').fadeIn();
});
});
I've just copy-pasted your code into a snippet and it seems to work fine.
Try typing "Title" and then typing "Foo", and then "Title" again for instance:
$('.search-form').on('submit', function() {
return false;
});
$('.search-form .btn').on('click', function(e) {
var query = $.trim($(this).prevAll('.search-query').val()).toLowerCase();
$('div.mybox .mytitle').each(function() {
var $this = $(this);
if ($this.text().toLowerCase().indexOf(query) === -1)
$this.closest('div.mybox').fadeOut();
else $this.closest('div.mybox').fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="search-form">
<input type="text" id="searchfield" class="input-medium search-query" placeholder="Search">
<button type="submit" class="btn">Search</button>
</form>
<div class="col-md-4 col-sm-6">
<div class="mybox">
<div data-title="Titleshoudbehere" class="myitem">
<a target="_blank">
<div class="mytitle">
<p>Title is here</p>
</div>
<div class="footer">
<p>#hashtag </p>
</div>
</a>
</div>
</div>
</div>
In my form, I have made a dynamic text input field using jQuery and made it sortable using jQuery-UI. But the problem it, when I submit the form, only the last value of the form is sent to the action page.
How can I send all the values to the form action page and echo an Ordered List with the values?
Thanks in advance for your suggestions. Here is the snippet of the dynamic form:
$(document).ready(function() {
var fixHelperModified = function(e, div) {
var $originals = div.children();
var $helper = div.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function() {
$('div.index').each(function(i) {
$(this).html(i + 1);
});
};
$("#add").sortable({
helper: fixHelperModified,
stop: updateIndex
}).disableSelection();
$("#addNew").click(function() {
$('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><input type='text' class='form-control' name='members'></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
updateIndex();
});
$("body").on('click', '#add .delete', function() {
$(this).closest(".rem").remove();
updateIndex();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post" id="members" class="form-horizontal" action="pritnPreview.php">
<fieldset>
<div class="form-group">
<div class="col-sm-2">
<label class="form-name">Members</label>
</div>
<div class="col-sm-8">
<div class="row">
<div id='add'>
<div class='row rem' id='move'>
<div class='col-md-1 index'>1. </div>
<div class='col-md-9'>
<input type='text' class='form-control' name='members'>
</div>
<div class='col-md-1'>
<button class='delete btn btn-warning btn-xs'>Delete</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-2">
<button id='addNew' type="button" href="#">Add another</button>
</div>
</div>
</div>
</div>
</div>
</fieldset>
<input type="submit" name="submitSave" value="Submit">
</form>
The printPreview.php page:
<?php
if (!empty($_POST['cc'])) echo 'CC: ' . $cc;
?>
Change the name of the input to cc[] to save a array of values
name='cc[]'
I am adding to my spring project a form wizard based on bootstrap, where the view is this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Instalação da aplicação</title>
</head>
<body>
<div id="pad-wrapper">
<div class="row">
<div class="col-md-12 col-xs-12">
<div id="fuelux-wizard" class="wizard row">
<ul class="wizard-steps">
<li data-target="#step1" class="active">
<span class="step">1</span>
<span class="title">Banco de dados</span>
</li>
<li data-target="#step2">
<span class="step">2</span>
<span class="title">Dados do administrador</span>
</li>
<li data-target="#step3">
<span class="step">3</span>
<span class="title">Conclusão</span>
</li>
</ul>
</div>
<div class="step-content">
<div class="step-pane active" id="step1">
<div class="row form-wrapper">
<div class="col-md-8">
<form method="post" action="">
<div class="field-box">
<label>Máquina (IP):</label>
<input class="form-control" type="text" />
</div>
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" />
</div>
<div class="field-box">
<label>Senha:</label>
<input class="form-control" type="text" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane" id="step2">
<div class="row form-wrapper">
<div class="col-md-8">
<form>
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" />
</div>
<div class="field-box">
<label>Digite uma senha:</label>
<input class="form-control" type="password" />
</div>
<div class="field-box">
<label>Repita a senha:</label>
<input class="form-control" type="password" />
</div>
<div class="field-box">
<label>E-mail:</label>
<input class="form-control" type="text" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane" id="step3">
<div class="row form-wrapper">
<div class="col-md-8">
O sistema foi configurado com sucesso! Agora você pode efetuar seu login e começar a usa-lo.
</div>
</div>
</div>
</div>
<div class="wizard-actions">
<button type="button" disabled class="btn-glow primary btn-prev">
<i class="icon-chevron-left"></i> Prõximo
</button>
<button type="button" class="btn-glow primary btn-next" data-last="Finish">
Seguinte <i class="icon-chevron-right"></i>
</button>
<button type="button" class="btn-glow success btn-finish">
Faça login no sistema!
</button>
</div>
</div>
</div>
</div>
</body>
</html>
I want that after each step, run one jquery function which will perform soe update in the server (first step should create a database, second step should create a user), but I have no idea how to do this. Anyone can point me a direction accomplish the result I expected?
UPDATE
Ok, then I made some changes in the html code, and include some jquery code, which I guess I think should do the job, but isn't working. Anyone can see what I am doing wrong?
<body>
<!-- main container -->
<div class="content">
<div id="pad-wrapper">
<div class="row">
<div class="col-md-12 col-xs-12">
<div id="fuelux-wizard" class="wizard row">
<ul class="wizard-steps">
<li data-target="#step1" class="active">
<span class="step">1</span>
<span class="title">Banco de dados</span>
</li>
<li data-target="#step2">
<span class="step">2</span>
<span class="title">Dados do administrador</span>
</li>
<li data-target="#step3">
<span class="step">3</span>
<span class="title">Conclusão</span>
</li>
</ul>
</div>
<div class="step-content">
<div class="step-pane active" id="step1">
<div class="row form-wrapper">
<div class="col-md-8">
<form name="target" method="post" action="<c:out value="${pageContext.request.contextPath}/instala/createdb"/>">
<div class="field-box">
<label>Máquina (IP):</label>
<input class="form-control" type="text" name="maquina" />
</div>
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" name="usuario_db" />
</div>
<div class="field-box">
<label>Senha:</label>
<input class="form-control" type="text" name="senha_db" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane" id="step2">
<div class="row form-wrapper">
<div class="col-md-8">
<form name="target" method="post" action="<c:out value="${pageContext.request.contextPath}/instala/createuser"/>">
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" name="usuario" />
</div>
<div class="field-box">
<label>Digite uma senha:</label>
<input class="form-control" type="password" name="senha1" />
</div>
<div class="field-box">
<label>Repita a senha:</label>
<input class="form-control" type="password" name="senha2" />
</div>
<div class="field-box">
<label>E-mail:</label>
<input class="form-control" type="text" name="email" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane" id="step3">
<div class="row form-wrapper payment-info">
<div class="col-md-8">
O sistema foi configurado com sucesso! Agora você pode efetuar seu login e começar a usa-lo.
</div>
</div>
</div>
</div>
<div class="wizard-actions">
<button type="button" disabled class="btn-glow primary btn-prev">
<i class="icon-chevron-left"></i> Anterior
</button>
<button type="submit" class="btn-glow primary btn-next" data-last="Finish">
Prõximo <i class="icon-chevron-right"></i>
</button>
<button type="button" onclick="<c:out value="${pageContext.request.contextPath}/acesso/login"/>" class="btn-glow success btn-finish">
Faça login no sistema!
</button>
</div>
<div class="alert alert-danger" id="result">
<i class="icon-remove-sign"></i>
</div>
</div>
</div>
</div>
</div>
<!-- end main container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="<c:out value="${pageContext.request.contextPath}/jquery/js/jquery-2.1.0.min.js"/>"></script>
<script src="<c:out value="${pageContext.request.contextPath}/jquery/js/jquery-ui-1.10.4.custom.min.js"/>"></script>
<script src="<c:out value="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"/>"></script>
<script src="<c:out value="${pageContext.request.contextPath}/extras/js/jquery-ui-timepicker-addon.js"/>"></script>
<script src="<c:out value="${pageContext.request.contextPath}/extras/js/jquery-ui-sliderAccess.js"/>"></script>
<script src="<c:out value="${pageContext.request.contextPath}/extras/js/fuelux.wizard.js"/>"></script>
<script type="text/javascript">
$(function () {
$( "#result" ).hide();
var $wizard = $('#fuelux-wizard'),
$btnPrev = $('.wizard-actions .btn-prev'),
$btnNext = $('.wizard-actions .btn-next'),
$btnFinish = $(".wizard-actions .btn-finish");
$wizard.wizard().on('finished', function(e) {
// wizard complete code
}).on("changed", function(e) {
var step = $wizard.wizard("selectedItem");
// reset states
$btnNext.removeAttr("disabled");
$btnPrev.removeAttr("disabled");
$btnNext.show();
$btnFinish.hide();
if (step.step === 1) {
$btnPrev.attr("disabled", "disabled");
//
} else if(step.step === 2) {
//
} else if (step.step === 3) {
$btnNext.hide();
$btnFinish.show();
};
});
$btnPrev.on('click', function() {
$wizard.wizard('previous');
});
$btnNext.on('click', function() {
$wizard.wizard('next');
});
$( "#target" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, $(this).serialize() );
// Put the results in a div
posting.done(function( data ) {
if(data == "not") {
$( "#result" ).show();
$( "#result" ).empty().append( "Erro ao executar os procedimentos dessa etapa" ).fadeOut();
}
$("#target").each (function(){
this.reset();
});
});
});
});
</script>
</body>
UPDATE 2
My current jquery code is this:
$(function () {
$( "#result" ).hide();
var $wizard = $('#fuelux-wizard'),
$btnPrev = $('.wizard-actions .btn-prev'),
$btnNext = $('.wizard-actions .btn-next'),
$btnFinish = $(".wizard-actions .btn-finish");
$wizard.wizard().on("finished", function(e) {
alert("finished");
var fnprocessform = function (targetform) {
if (targetform.attr('id') === 'target') {
alert('validating form 1');
var maquina = $("input[maquina]").val();
var usuario = $("input[usuario_db]").val();
var senha = $("input[senha_db]").val();
var request = $.ajax({
url: "<c:out value="${pageContext.request.contextPath}/instala/createdb"/>",
type: "POST",
data: { maquina : maquina, usuario_db: usuario, senha_db: senha }
});
return request;
}
if (targetform.attr('id') === 'target2') {
alert('validating form 2');
var usuario = $("input[usuario]").val();
var senha = $("input[senha1]").val();
var pnome = $("input[primeiroNome]").val();
var unome = $("input[ultimoNome]").val();
var request = $.ajax({
url: "<c:out value="${pageContext.request.contextPath}/instala/createuser"/>",
type: "POST",
data: { usuario : usuario, senha1: senha, primeiroNome: pnome, ultimoNome: unome }
});
return request;
};
};
if(fnprocessform == "yes") {
alert('form validated');
var nextstep = $('.wizard-steps').find('.active').next();
nextstep.find('a').tab('show');
}
}).on("changed", function(e) {
alert("changed");
var step = $wizard.wizard("selectedItem");
$btnNext.removeAttr("disabled");
$btnPrev.removeAttr("disabled");
$btnNext.show();
$btnFinish.hide();
if (step.step === 1) {
$btnPrev.attr("disabled", "disabled");
} else if (step.step === 3) {
$btnNext.hide();
$btnFinish.show();
};
});
$btnPrev.on('click', function() {
$wizard.wizard('previous');
});
$btnNext.on('click', function() {
$wizard.wizard('next');
});
});
My problem now is that, otherwise from event "clicked", the event "finished" is never triggered when I access the page (it supposed to be triggered when I click in the button "next").
Anyone can tell me what's wrong with my current approach?
UPDATE 3
Ok, after a contact with the creator of bootstrap theme I using, I learn the event "finished" is only triggered in the end of the wizard. What I want is run some jquery code after first step (to create an database in server) and after second step (to create an user in the database). After the third step, I just go to login page.
My current HTML code is this:
<!-- main container -->
<div class="content">
<div id="pad-wrapper">
<div class="row">
<div class="col-md-12 col-xs-12">
<div id="fuelux-wizard" class="wizard row">
<ul class="wizard-steps">
<li data-target="#step1" class="active">
<span class="step">1</span>
<span class="title">Banco de dados</span>
</li>
<li data-target="#step2">
<span class="step">2</span>
<span class="title">Dados do administrador</span>
</li>
<li data-target="#step3">
<span class="step">3</span>
<span class="title">Conclusão</span>
</li>
</ul>
</div>
<div class="step-content">
<div class="step-pane active" id="step1">
<div class="row form-wrapper">
<div class="col-md-8">
<form id="target">
<div class="field-box">
<label>Máquina (IP):</label>
<input class="form-control" type="text" name="maquina" />
</div>
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" name="usuario_db" />
</div>
<div class="field-box">
<label>Senha:</label>
<input class="form-control" type="text" name="senha_db" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane" id="step2">
<div class="row form-wrapper">
<div class="col-md-8">
<form id="target2">
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" name="usuario" />
</div>
<div class="field-box">
<label>Digite uma senha:</label>
<input class="form-control" type="password" name="senha1" />
</div>
<div class="field-box">
<label>Repita a senha:</label>
<input class="form-control" type="password" name="senha2" />
</div>
<div class="field-box">
<label>Primeiro nome:</label>
<input class="form-control" type="text" name="primeiroNome" />
</div>
<div class="field-box">
<label>Ultimo nome:</label>
<input class="form-control" type="text" name="ultimoNome" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane" id="step3">
<div class="row form-wrapper payment-info">
<div class="col-md-8">
O sistema foi configurado com sucesso! Agora você pode efetuar seu login e começar a usa-lo.
</div>
</div>
</div>
</div>
<div class="wizard-actions">
<button type="button" disabled class="btn-glow primary btn-prev">
<i class="icon-chevron-left"></i> Anterior
</button>
<button type="button" class="btn-glow primary btn-next" data-last="Finish">
Prõximo <i class="icon-chevron-right"></i>
</button>
<button type="button" class="btn-glow success btn-finish">
Faça login no sistema!
</button>
</div>
<div class="alert alert-danger" id="result">
<i class="icon-remove-sign"></i>
</div>
</div>
</div>
</div>
</div>
<!-- end main container -->
My current jquery code is this:
$(function () {
$( "#result" ).hide();
var $wizard = $('#fuelux-wizard'),
$btnPrev = $('.wizard-actions .btn-prev'),
$btnNext = $('.wizard-actions .btn-next'),
$btnFinish = $(".wizard-actions .btn-finish");
$wizard.wizard().on("finished", function(e) {
//
}).on("changed", function(e) {
var step = $wizard.wizard("selectedItem");
$btnNext.removeAttr("disabled");
$btnPrev.removeAttr("disabled");
$btnNext.show();
$btnFinish.hide();
if (step.step === 1) {
$btnPrev.attr("disabled", "disabled");
} else if (step.step === 3) {
$btnNext.hide();
$btnFinish.show();
};
});
$btnPrev.on('click', function() {
$wizard.wizard('previous');
});
$btnNext.on('click', function() {
$wizard.wizard('next');
});
});
My idea is add a new block
.on("--event--", function(e) {
but I don't know which event is triggered between each step (if any). Anyone have sugestions?
Since you're using Bootstrap, just take advantage of the standard tab behavior to make your wizard. Update your html like this:
<div id="pad-wrapper">
<div class="row">
<div class="col-md-12 col-xs-12">
<div id="fuelux-wizard" class="wizard row">
<ul class="nav nav-pills wizard-steps">
<li class="active">
<a href="#step1" data-toggle="tab" >
<span class="step">1</span>
<span class="title">Banco de dados</span>
</a>
</li>
<li>
<a href="#step2" data-toggle="tab" >
<span class="step">2</span>
<span class="title">Dados do administrador</span>
</a>
</li>
<li>
<a href="#step3" data-toggle="tab">
<span class="step">3</span>
<span class="title">Conclusão</span>
</a>
</li>
</ul>
</div>
<div class="step-content tab-content">
<div class="step-pane tab-pane active" id="step1">
<div class="row form-wrapper">
<div class="col-md-8">
<form id="target" method="post" action="">
<div class="field-box">
<label>Máquina (IP):</label>
<input class="form-control" type="text" name="maquina" />
</div>
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" name="usuario_db" />
</div>
<div class="field-box">
<label>Senha:</label>
<input class="form-control" type="text" name="senha_db" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane tab-pane" id="step2">
<div class="row form-wrapper">
<div class="col-md-8">
<form id="target2" method="post" action="">
<div class="field-box">
<label>Usuário:</label>
<input class="form-control" type="text" name="usuario" />
</div>
<div class="field-box">
<label>Digite uma senha:</label>
<input class="form-control" type="password" name="senha1" />
</div>
<div class="field-box">
<label>Repita a senha:</label>
<input class="form-control" type="password" name="senha2" />
</div>
<div class="field-box">
<label>E-mail:</label>
<input class="form-control" type="text" name="email" />
</div>
</form>
</div>
</div>
</div>
<div class="step-pane tab-pane" id="step3">
<div class="row form-wrapper payment-info">
<div class="col-md-8">
O sistema foi configurado com sucesso! Agora você pode efetuar seu login e começar a usa-lo.
</div>
</div>
</div>
</div>
<div class="wizard-actions">
<button type="button" disabled class="btn-glow primary btn-prev">
<i class="icon-chevron-left"></i> Anterior
</button>
<button class="btn-glow primary btn-next" data-last="Finish">
Prõximo <i class="icon-chevron-right"></i>
</button>
<button type="button" onclick="" class="btn-glow success btn-finish">
Faça login no sistema!
</button>
</div>
<div class="alert alert-danger" id="result">
<i class="icon-remove-sign"></i>
</div>
</div>
</div>
</div>
Now add some javascript to handle the navigation:
$( document ).ready(function() {
var fnprocessform = function (targetform) {
if (targetform.attr('id') === 'target') {
//do your validation before you move to the next so you can show errors if needed
alert('validating form 1');
//if the form is validated move to the next step
var nextstep = $('.wizard-steps').find('.active').next();
nextstep.find('a').tab('show');
//then submit the form via ajax
//to make sure that the behavior you expect happens
//when you process the form, you probably want to send back an id of the newly created record
//so that if someone clicks back and then next again you don't create two records
//instead you read the id and update the record
}
if (targetform.attr('id') === 'target2') {
//same comments as above
alert('validating form 2');
var nextstep = $('.wizard-steps').find('.active').next();
nextstep.find('a').tab('show');
}
}
$('.wizard-actions .btn-next').on('click', function() {
var formtosubmit = $('.tab-pane.active').find('form');
fnprocessform(formtosubmit);
});
$('.wizard-actions .btn-prev').on('click', function() {
var prevstep = $('.wizard-steps').find('.active').prev();
prevstep.find('a').tab('show');
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
if ($('.wizard-steps').find('.active').is(':first-child')) {
$('.wizard-actions .btn-prev').prop('disabled', true);
} else {
$('.wizard-actions .btn-prev').prop('disabled', false);
}
if ($('.wizard-steps').find('.active').is(':last-child')) {
$('.wizard-actions .btn-next').prop('disabled', true);
} else {
$('.wizard-actions .btn-next').prop('disabled', false);
}
})
});
To finish this up, you'll need to add some nice styling, write a click event handler for the nav-pills to prevent them from causing the tabs to show and you need to handle all of your validation and form processing, but this should really get you going. You can make it even cooler by adding a progress bar using the built in progress bars in Bootstrap.
Ok, then I finally solved this question after more tryouts. That's the final code:
$(function () {
$( "#result" ).hide();
var $wizard = $('#fuelux-wizard'),
$btnPrev = $('.wizard-actions .btn-prev'),
$btnNext = $('.wizard-actions .btn-next'),
$btnFinish = $(".wizard-actions .btn-finish");
$wizard.wizard().on("finished", function(e) {
//
}).on("changed", function(e) {
var step = $wizard.wizard("selectedItem");
$btnNext.removeAttr("disabled");
$btnPrev.removeAttr("disabled");
$btnNext.show();
$btnFinish.hide();
if (step.step === 1) {
$btnPrev.attr("disabled", "disabled");
} else if (step.step === 3) {
$btnNext.hide();
$btnFinish.show();
};
});
$btnPrev.on('click', function() {
$wizard.wizard('previous');
});
$btnNext.on('click', function() {
var step = $wizard.wizard("selectedItem");
if(step.step === 1) {
var maquina = $("input[name=maquina]").val();
var usuario = $("input[name=usuario_db]").val();
var senha = $("input[name=senha_db]").val();
$.ajax({
url: "<c:out value="${pageContext.request.contextPath}/instala/createdb"/>",
type: "POST",
data: { maquina : maquina, usuario_db: usuario, senha_db: senha }
}).done(function(data){
if(data === "yes")
$wizard.wizard('next');
});
}
else {
var usuario = $("input[name=usuario]").val();
var senha = $("input[name=senha1]").val();
var pnome = $("input[name=primeiroNome]").val();
var unome = $("input[name=ultimoNome]").val();
$.ajax({
url: "<c:out value="${pageContext.request.contextPath}/instala/createuser"/>",
type: "POST",
data: { usuario : usuario, senha1: senha, primeiroNome: pnome, ultimoNome: unome }
}).done(function(data) {
if(data === "yes")
$wizard.wizard('next');
});
}
});
$btnFinish.on("click", function() {
location.href="<c:out value="${pageContext.request.contextPath}/acesso/login"/>";
});
});