I have 2 buttons in a div :
plus button
minus button
when I click plus button, I'm creating another same div by cloning it and it is working fine, but when I click on minus button, in the same way, I need to remove one whole div, here is my code :
$(document).ready(function() {
var addMoreConditions = function(evt) {
var $div = document.getElementById('query_area');
var queryDiv = document.getElementsByClassName('search_criteria1');
// $div.appendChild($div);
$(".search_criteria1:last").clone().insertAfter("div.search_criteria1:last");
};
});
var removeConditions = function(ev) {
$('#query_area').remove($(ev).parent()[0]);
}
.m-form__group {
padding-left: 30px;
padding-right: 30px;
}
.row {
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group m-form__group row">
<div class="search_criteria1 form-group m-form__group row">
<div class="col-4">
<select class="field_attr1 form-control m-input"></select>
</div>
<div class="col-3">
<select class="condition_div1 form-control m-input">
<option value="eq">=</option>
<option value="neq">!=</option>
</select>
</div>
<div class="col-3">
<input type="text" class="fieldValue1 form-control m-input" />
</div>
<div class="col-1" onclick="addMoreConditions()">
<input class="btn btn-primary" type="button" name="btn3" value="+">
</div>
<div class="col-1" style="padding-left:20px" onclick="removeConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="-">
</div>
</div>
</div>
First of all, you need to remove $(document).ready as you are using inline events. And inline handler expects function to be under global scope. In your example, then are under local scope of $(document).ready
While removing, you can use .closest() to select respective element to be removed.
var addMoreConditions = function(evt) {
var $div = document.getElementById('query_area');
var queryDiv = document.getElementsByClassName('search_criteria1');
// $div.appendChild($div);
$(".search_criteria1:last").clone().insertAfter("div.search_criteria1:last");
};
var removeConditions = function(ev) {
$(ev).closest('.search_criteria1').remove();
}
.m-form__group {
padding-left: 30px;
padding-right: 30px;
}
.row {
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group m-form__group row">
<div class="search_criteria1 form-group m-form__group row">
<div class="col-4">
<select class="field_attr1 form-control m-input"></select>
</div>
<div class="col-3">
<select class="condition_div1 form-control m-input">
<option value="eq">=</option>
<option value="neq">!=</option>
</select>
</div>
<div class="col-3">
<input type="text" class="fieldValue1 form-control m-input" />
</div>
<div class="col-1" onclick="addMoreConditions()">
<input class="btn btn-primary" type="button" name="btn3" value="+">
</div>
<div class="col-1" style="padding-left:20px" onclick="removeConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="-">
</div>
</div>
</div>
<div class="col-1 removeitem" style="padding-left:20px">
give some specific class or id id used one class
$(document).on("click", ".removeitem", function (e) {
//user click on remove
e.preventDefault();
$(this).parent().remove();
});
You need to go up to the parent element then remove it like :
$(ev).closest('.search_criteria1').remove();
NOTE 1: When you clone the div it will be cloned with the user inputs, means if the user typed 100 in the last input then you clicked the plus button, the value of the input in the new cloned div will be 100 too. if you want to init the input/select for the new instance you could use the cloned div cloned_div as variable and init them first then push them to the view.
NOTE 2: You don't need the queryDiv and $div variables in your code, just remove them.
var addMoreConditions = function(evt) {
var last_div = "div.search_criteria1:last";
var cloned_div = $(last_div).clone();
cloned_div.find('.fieldValue1').val("");
cloned_div.find('select').val("");
cloned_div.insertAfter(last_div);
};
var removeConditions = function(ev) {
$(ev).closest('.search_criteria1').remove();
}
$('button').click(function() {
$('.search_criteria1').each(function(index) {
index++;
console.log('Field Attribute ' + index + ' : ' + $('.field_attr1', this).val());
console.log('Condition Value ' + index + ' : ' + $('.condition_div1', this).val());
console.log('Field Value ' + index + ' : ' + $('.fieldValue1', this).val());
console.log('--------------------------------------');
})
})
.m-form__group {
padding-left: 30px;
padding-right: 30px;
}
.row {
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group m-form__group row">
<div class="search_criteria1 form-group m-form__group row">
<div class="col-4">
<select class="field_attr1 form-control m-input"></select>
</div>
<div class="col-3">
<select class="condition_div1 form-control m-input">
<option value="eq">=</option>
<option value="neq">!=</option>
</select>
</div>
<div class="col-3">
<input type="text" class="fieldValue1 form-control m-input" />
</div>
<div class="col-1" onclick="addMoreConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="+">
</div>
<div class="col-1" style="padding-left:20px" onclick="removeConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="-">
</div>
</div>
</div>
<button type="button">GET DATA</button>
Related
I was looking all over for a snippet to include another input bootstrap input group and I couldn't find one so wouldn't you know it I coded one myself.
<style>
.CENTERFORM {
display: table;
margin-left: auto;
margin-right: auto;
}
</style>
<!-- Player And Score -->
<div id="PLAYERCONTAINER">
<div class="col-9 col-md-8 CENTERFORM my-3 text-center">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="">Player 1</span>
</div>
<input type="text" class="form-control" id="PLAYER_NAME">
<div class="col-3">
<input type="number" class="form-control" id="PLAYER_SCORE">
</div>
</div>
<button class="btn btn-outline-success" onclick="cloneThis(this,this.parentNode)">Another?</button>
</div>
</div>
<script>
// Autoincrement button for player names and scores
let count = 1;
function cloneThis(button, playerform) {
const clone = playerform.cloneNode(playerform);
const playerNameInput = clone.childNodes[1].childNodes[3].id = `PLAYER_NAME${count}`;
const playerScoreInput = clone.childNodes[1].childNodes[5].childNodes[1].id = `PLAYER_SCORE${count++}`;
console.log(playerScoreInput);
button.remove();
console.log("clicked");
document.getElementById('PLAYERCONTAINER').append(clone);
}
</script>
My actual html code:
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="<?php echo $adminData->name; ?>">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="<?php echo $adminData->email; ?>">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
I have multiple such panels, each one with a button that has specific ID. My goal is to collect all the input within the panel that the button was pressed. Although this sounds easy, my MAIN goal is to reuse the same function on multiple pages that have multiple panels (since the structures is simillar), to then use ajax to update the information. The only thing that I would need to provide the function is the id of the button so it can find automatically the relative input.
I am trying to accomplish this in vanilla js, though im ok with jquery.
My actual js code:
document.getElementById('savePersInfo').onclick = function(){
var inputArray = ['adminName', 'adminEmail'];
console.log(collectInfo(inputArray));
};
function collectInfo(inputArray){
$inputValueArray = []
for(var c = 0; c < inputArray.length; c++){
$inputValueArray[c] = document.querySelectorAll('[name="' + inputArray[c] + '"]')[0].value;
}
return $inputValueArray;
}
As you see here I need to specify the name of the input to be able to retrieve it, what I want is not to do that and have JS find it automatically based on the panel is was clicked on.
Any suggestions/ideas on how this can be accomplished ?
ps: ignore the inline styling and other layout stuff, early development phase.
You can use either javasscript's closest() or jQuery's closest(), and with those find the closest element being ancestor to both the button and input's, e.g. panel-body.
From there you then simply use that element as starting point, e.g. with javascript element.querySelectorAll), and select all inputs and grab their value.
Note, if to use the javascript version and support IE (it doesn't know of closest()), you can make use of the "polyfill" I added at the end.
Updated based on a comment, where I added a checkbox and select to my "javascript" code sample to show it works with those too, and how to get the button id.
Stack snippet - javascript
document.querySelectorAll('button').forEach( function(btn) {
btn.addEventListener('click', findInputs);
})
function findInputs() {
console.clear();
var button_id = this.id;
this.closest('.panel-body').querySelectorAll('input, select').forEach( function(inp) {
var test_checked = ((inp.type == 'checkbox' && inp.checked) ? ' checked' : '');
console.log(button_id, inp.value + test_checked)
})
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test</span>
<input type="checkbox" name="adminTest" class="form-control" value="test 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test 2</span>
<select name="adminTest2" class="form-control">
<option value="Test2-a">Test2-a</option>
<option selected value="Test2-b">Test2-b</option>
<option value="Test2-c">Test2-c</option>
</select>
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
Stack snippet - jQuery
$('button').each( function() {
$(this).click(findInputs);
})
function findInputs() {
$(this).closest('.panel-body').find('input').each( function() {
console.log( $(this).val() );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal 2
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 2">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 2">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo2">Guardar Alteração 2</button>
</div>
</div>
</div>
Add javascript closest() support for IE9+
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
if (!Element.prototype.closest)
Element.prototype.closest = function(s) {
var el = this;
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
Src: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
You can use Element.closest() on the element with the passed id to target the panel you are looking for. Then use Array.prototype.map() to return the value of all inputs from the selected panel.
Try the following way:
document.getElementById('savePersInfo').onclick = function(){
console.log(collectInfo(this.id));
};
function collectInfo(id){
var panel = document.getElementById(id).closest(".panel.panel-primary")
var $inputValueArray = [...panel.querySelectorAll('input[type=text]')].map(i => i.value);
return $inputValueArray;
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="John Michale Kane">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="john#gmail.com">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
I have small form with checkbox. When I fill the form and save data to database and try to fill it with another data to save it to database my checkbox doesn't work. It works only when I refresh page. here is code.
<form action="javascript:saveNewBreakfast();" name="basic_validate"
id="breakfast_validate" novalidate="novalidate">
<div class="control-group" id="add_breakfast" style="display: none">
<div class="control-group">
<label class="control-label">Select new one</label>
<div class="controls">
<select name="required" id="breakfast_select">
</select>
</div>
</div>
<div class="control-group">
<label class="checkbox-inline"><input
id="is_free_breakfast" type="checkbox" checked>Is
free ? </label>
</div>
<div class="control-group" id="price_breakfast" style="display: none">
<label class="control-label">Price</label>
<div class="controls">
<input type="number" min="0"
style="border-radius: 5pc; height: 30px; width: 280px; margin-bottom: 0px;"
id="breakfast_price"> EUR
</div>
</div>
<div class="control-group">
<button type="submit" class="btn btn-mini; btn-success">Save</button>
</div>
</div>
</form>
$('#is_free_breakfast').change(function(){
getIsFree = $('#is_free_breakfast').is(':checked');
if(getIsFree){
$('#price_breakfast').hide();
}else{
$('#price_breakfast').show();
}
});
You will need to explicit reset the form if you are using js handler for form submit (action="").
Something like:
function saveNewBreakfast() {
// submit handler code
// reset the form to initial values
$('#breakfast_validate')[0].reset();
// show/hide the input based on checkbox's initial values
$('#is_free_breakfast').change();
}
NOTE: reset is a HTML DOM Element method (i.e. plain js function), and not
a jQuery one, so $('selector')[0] is used to convert jquery object to DOM element. Or you can use plain js
document.getElementById('breakfast_validate').reset();
Here's a demo:
function saveNewBreakfast() {
// submit hanlder code
alert('saved with price: ' + ($('#breakfast_price').val() || 'free'));
$('#breakfast_validate')[0].reset();
$('#is_free_breakfast').change();
}
$('#is_free_breakfast').change(function() {
getIsFree = $('#is_free_breakfast').is(':checked');
if (getIsFree) {
$('#price_breakfast').hide();
} else {
$('#price_breakfast').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="javascript:saveNewBreakfast();" name="basic_validate" id="breakfast_validate" novalidate="novalidate">
<div class="control-group" id="add_breakfast">
<div class="control-group">
<label class="control-label">Select new one</label>
<div class="controls">
<select name="required" id="breakfast_select">
</select>
</div>
</div>
<div class="control-group">
<label class="checkbox-inline"><input
id="is_free_breakfast" type="checkbox" checked>Is
free ? </label>
</div>
<div class="control-group" id="price_breakfast" style="display: none">
<label class="control-label">Price</label>
<div class="controls">
<input type="number" min="0" style="border-radius: 5pc; height: 30px; width: 280px; margin-bottom: 0px;" id="breakfast_price"> EUR
</div>
</div>
<div class="control-group">
<button type="submit" class="btn btn-mini; btn-success">Save</button>
</div>
</div>
</form>
$(document).ready(function () {
var html_content = '<label class="control-label">Price</label>' +
'<div class="controls">' +
'<input type="number" min="0"' +
'style="border-radius: 5pc; height: 30px; width: 280px; margin-bottom: 0px;"' +
'name="breakfast_price" id="breakfast_price"> EUR' +
'</div> ';
$('#is_free_breakfast').change(function () {
getIsFree = $('#is_free_breakfast').is(':checked');
if (getIsFree) {
$('#price_breakfast').empty();
} else {
$('#price_breakfast').html(html_content);
}
});
});
function form_submit(){
var queryString = $('#breakfast_validate').serialize();
console.log(queryString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="javascript:saveNewBreakfast();" name="basic_validate"
id="breakfast_validate" novalidate="novalidate">
<div class="control-group" id="add_breakfast">
<div class="control-group">
<label class="control-label">Select new one</label>
<div class="controls">
<select name="required" id="breakfast_select">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</div>
</div>
<div class="control-group">
<label class="checkbox-inline">
<input
id="is_free_breakfast" type="checkbox" checked>Is free ?
</label>
</div>
<div class="control-group" id="price_breakfast">
</div>
<div class="control-group">
<button type="button" onclick="form_submit()" class="btn btn-mini; btn-success">Save</button>
</div>
</div>
</form>
I am currently trying to get a basic but of functionality working where I say have 5 rows, each with there own number.
So I have 5 rows .......5,4,3,2,1 <--- If I remove say 3 it should then look like 4,3,2,1 and so am effectively reflecting I now only have 4 now instead of 5.....if I remove another value it then goes to 3,2, 1 and so on.
I have been somewhat close but cant quite get it to work.
Here is the JSfiddle
jQuery(function($) {
var countercontact = 0;
var counternum = 0;
$("#addcontact").on('click', function() {
countercontact++;
$("#contact_num").append('<div class="row"><div class="form-group col-xs-1 contactspan"><span class="countercontact">' + countercontact + '.</span></div><div class="form-group col-xs-3"><input type="text" class="form-control" id="pass" placeholder="No number"></div><div class="form-group col-xs-2"><select class="form-control" id="delay"><option>5</option><option>10</option><option>20</option><option>30</option><option>40</option><option>50</option><option>60</option></select></div><div class="form-group col-xs-2">\<input type="checkbox" class="form-control" id="confirm"></div><div class="form-group col-xs-2"><input type="checkbox" class="form-control" id="enable"></div><div class="form-group col-xs-2"><button type="submit" class="btn btn-primary form-control deletecontact">Delete</button></div></div>');
if (countercontact === 1) {
$(".deletecontact").addClass('disabled');
} else {
$(".deletecontact").removeClass('disabled');
}
});
$("#contact_num").on("click", ".deletecontact", function() {
if (countercontact <= 1) {
$(".deletecontact").addClass('disabled');
} else {
$(".deletecontact").removeClass('disabled');
$(this).closest('.row').remove();
countercontact--;
$(".contactspan").each(function(index) {
var ordernum = $(this).text();
console.log(ordernum);
if (ordernum !== 1) {
$(this).text(parseInt($(this).text()) - 1);
}
});
}
});
});
.container {
width: 75%;
}
.row {
margin-bottom: 12px;
font-size: 13px;
}
.panel {
border: none;
box-shadow: none;
}
.panel-heading {
background-color: #D9DBDE;
padding: 20px;
margin-bottom: 10px;
border-radius: 0;
}
.panel-heading.head {
padding: 20px 0;
background-color: #E1F2F9;
}
.panel-body {
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="panel panel-default">
<div class="panel-body row">
<div class="form-group" id="contact_num">
<div class="row">
<div class="form-group col-md-1">
<label for="pass"></label>
</div>
<div class="form-group col-md-3">
<label for="pass">Contact No(s)</label>
</div>
<div class="form-group col-md-2">
<label for="delay">Delay</label>
</div>
<div class="form-group col-md-2">
<label for="confirm">Confirm</label>
</div>
<div class="form-group col-md-2">
<label for="enable">Enable</label>
</div>
<div class="form-group col-md-2">
<label for="delete"></label>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" id="addcontact" style="margin-bottom: 10px;">Add</button>
</div>
</div>
You can write a function that corrects numbers and run whenever needed like after removing an item.
function correctIndex(){
$('#contact_num .row').each(function(){
$(this).find('.contactspan').html($(this).index()+1);
});
}
Or you just change this part of your code:
$(".contactspan").each(function(index) {
var ordernum = $(this).text();
console.log(ordernum);
if (ordernum !== 1) {
$(this).text(parseInt($(this).text()) - 1);
}
});
to:
$(".contactspan").each(function(){
$(this).html($(this).closest('.row').index() + '.')
});
Here is updated fiddle
Please check below snippet.
I have made change in the reassigning of number as following.
var ordernum = 1;
$(".contactspan").each(function(index) {
$(this).text(ordernum);
ordernum++;
});
First assign the order number to 1 and then gradually increase it further rows.
jQuery(function($) {
var countercontact = 0;
var counternum = 0;
$("#addcontact").on('click', function() {
countercontact++;
$("#contact_num").append('<div class="row"><div class="form-group col-xs-1 contactspan"><span class="countercontact">' + countercontact + '.</span></div><div class="form-group col-xs-3"><input type="text" class="form-control" id="pass" placeholder="No number"></div><div class="form-group col-xs-2"><select class="form-control" id="delay"><option>5</option><option>10</option><option>20</option><option>30</option><option>40</option><option>50</option><option>60</option></select></div><div class="form-group col-xs-2">\<input type="checkbox" class="form-control" id="confirm"></div><div class="form-group col-xs-2"><input type="checkbox" class="form-control" id="enable"></div><div class="form-group col-xs-2"><button type="submit" class="btn btn-primary form-control deletecontact">Delete</button></div></div>');
if (countercontact === 1) {
$(".deletecontact").addClass('disabled');
} else {
$(".deletecontact").removeClass('disabled');
}
});
$("#contact_num").on("click", ".deletecontact", function() {
if (countercontact <= 1) {
$(".deletecontact").addClass('disabled');
} else {
$(".deletecontact").removeClass('disabled');
$(this).closest('.row').remove();
countercontact--;
var ordernum = 1;
$(".contactspan").each(function(index) {
$(this).text(ordernum);
ordernum++;
});
}
});
});
.container {
width: 75%;
}
.row {
margin-bottom: 12px;
font-size: 13px;
}
.panel {
border: none;
box-shadow: none;
}
.panel-heading {
background-color: #D9DBDE;
padding: 20px;
margin-bottom: 10px;
border-radius: 0;
}
.panel-heading.head {
padding: 20px 0;
background-color: #E1F2F9;
}
.panel-body {
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="panel panel-default">
<div class="panel-body row">
<div class="form-group" id="contact_num">
<div class="row">
<div class="form-group col-md-1">
<label for="pass"></label>
</div>
<div class="form-group col-md-3">
<label for="pass">Contact No(s)</label>
</div>
<div class="form-group col-md-2">
<label for="delay">Delay</label>
</div>
<div class="form-group col-md-2">
<label for="confirm">Confirm</label>
</div>
<div class="form-group col-md-2">
<label for="enable">Enable</label>
</div>
<div class="form-group col-md-2">
<label for="delete"></label>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" id="addcontact" style="margin-bottom: 10px;">Add</button>
</div>
</div>
The following is causing the behaviour:
var ordernum = $(this).text();
console.log(ordernum);
if (ordernum !== 1) {
$(this).text(parseInt($(this).text()) - 1);
}
ordernum is in this case 1. so you have to convert it to an int just like you do in the if clause.
var ordernum = parseInt($(this).text());
console.log(ordernum);
if (ordernum !== 1) {
$(this).text(ordernum - 1);
}
See https://jsfiddle.net/YvCil/ajgm9rhw/1/
I have tried to add a form wizard with validation. The main problem I am facing is the disable function of the steps doesnt work. When I click on the step numbers on top, it just goes off without any validation.
Here is my html
<div class="x_content">
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Step 1</p>
</div>
<div class="stepwizard-step">
2
<p>Step 2</p>
</div>
<div class="stepwizard-step">
3
<p>Step 3</p>
</div>
</div>
</div>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 1</h3>
<div class="form-group">
<label class="control-label">First Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Last Name" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label class="control-label">Company Name</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Name" />
</div>
<div class="form-group">
<label class="control-label">Company Address</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Address" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 3</h3>
<button class="btn btn-success btn-lg pull-right" type="submit">Finish!</button>
</div>
</div>
</div>
</form>
</div>
</div>
My CSS:
.stepwizard-step p {
margin-top: 10px;
}
.stepwizard-row {
display: table-row;
}
.stepwizard {
display: table;
width: 100%;
position: relative;
}
.stepwizard-step button[disabled] {
opacity: 1 !important;
filter: alpha(opacity=100) !important;
}
.stepwizard-row:before {
top: 14px;
bottom: 0;
position: absolute;
content: " ";
width: 100%;
height: 1px;
background-color: #ccc;
z-order: 0;
}
.stepwizard-step {
display: table-cell;
text-align: center;
position: relative;
}
.btn-circle {
width: 30px;
height: 30px;
text-align: center;
padding: 6px 0;
font-size: 12px;
line-height: 1.428571429;
border-radius: 15px;
}
The JS:
$(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();
}
});
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']"),
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');
});
Please let me know what am I doing wrong. How can I get it to work normally.
Thanks a lot.
You are triggering the click event from allNextBtn.click(function(){.
You may consider trigger( event [, extraParameters ] ) can use extra parameters.
Taking advantage of this you may distinguish if you are triggering from the above function or from the user.
Moreover, before to remove disabled atribute for the next element:
nextStepWizard.removeAttr('disabled').trigger('click', {'isManual': true});
you need to add the disabled attribute to all (so only one will be enabled):
$('div.setup-panel div a[href^="#"]').attr('disabled', 'disabled')
My snippet:
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e, isManual) {
e.preventDefault();
//
// test if the click event is ....
//
if (($('div.setup-panel div a[disabled]').length == ($('div.setup-panel div a').length - 1)) &&
(isManual === undefined)) {
return;
}
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();
}
});
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']"),
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) {
if (nextStepWizard.index(('div.setup-panel div a')) == ($('div.setup-panel div a').length - 1)) {
//
// remove the disabled attribute to all
//
$('div.setup-panel div a[href^="#"]').removeAttr('disabled');
nextStepWizard.trigger('click', {'isManual': true});
} else {
//
// add the disabled attribute to all
//
$('div.setup-panel div a[href^="#"]').attr('disabled', 'disabled');
//
// remove disabled only for the right element
//
nextStepWizard.removeAttr('disabled').trigger('click', {'isManual': true});
}
}
});
$('div.setup-panel div a.btn-primary').trigger('click', {'isManual': true});
});
.stepwizard-step p {
margin-top: 10px;
}
.stepwizard-row {
display: table-row;
}
.stepwizard {
display: table;
width: 100%;
position: relative;
}
.stepwizard-step button[disabled] {
opacity: 1 !important;
filter: alpha(opacity=100) !important;
}
.stepwizard-row:before {
top: 14px;
bottom: 0;
position: absolute;
content: " ";
width: 100%;
height: 1px;
background-color: #ccc;
z-order: 0;
}
.stepwizard-step {
display: table-cell;
text-align: center;
position: relative;
}
.btn-circle {
width: 30px;
height: 30px;
text-align: center;
padding: 6px 0;
font-size: 12px;
line-height: 1.428571429;
border-radius: 15px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="x_content">
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Step 1</p>
</div>
<div class="stepwizard-step">
2
<p>Step 2</p>
</div>
<div class="stepwizard-step">
3
<p>Step 3</p>
</div>
</div>
</div>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 1</h3>
<div class="form-group">
<label class="control-label">First Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Last Name" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label class="control-label">Company Name</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Name" />
</div>
<div class="form-group">
<label class="control-label">Company Address</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Address" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 3</h3>
<button class="btn btn-success btn-lg pull-right" type="submit">Finish!</button>
</div>
</div>
</div>
</form>
</div>
</div>