What I want is, I want to generate a new input type = text whenever a plus icon is getting clicked. SO I have written below code for the same.
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
alert(numItems);
if (numItems != 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.substr(13, lastfieldsid.length));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata1" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata1" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'></i></div></td></tr>"
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
</div>
Couple of problem in your code.
Use slice(-1) to get last character of id. It's remove your dependency using hardcode substr(13,... and you can use that value to increase new generated id by +1 .
Check length for input using $('.form-group').find('input').length < 5 which check the length of input inside form-group class and user only able to add 5 inputs.
Finally don't forgot to append your generated element on form-group class using $('.form-group').append(tr); .
I also add example to delete added tr using minus class.
Example:
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
if ($('.form-group').find('input').length < 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.slice(-1));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'>Remove</i></div></td></tr>";
}
$('#yourid').append(tr);
} else {
alert("warning........")
}
}
$(document).on('click', 'div.minus', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group" id="yourid">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true">icon</i>
</div>
</div>
Assuming that you are going to add new input field in div#dvDVRdata1. You need to append the HTMLcontent to that div as following:
$('#dvDVRdata1').append(tr);
The thing is you need to append the element, which you did not do in the code in your question.
As for remove, you also have not done it in your question yet. Here's the example of add and remove.
$(document).ready(function(){
$('.add').on('click', function () {
addDynamicTextbox();
});
$('.del').click(function (e) {
deleteDynamicTextbox(e);
});
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems != 5) {
var formGroup = $('.form-group');
var elem = `<div class="dvDVRdata" id="dvDVRdata${numItems+1}">
<label for="txtDVRAddress${numItems+1}">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress${numItems+1}" runat="server" />
</div>`;
formGroup.append(elem);
}
}
function deleteDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems > 1) {
$(`#dvDVRdata${numItems}`).remove();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/js/all.min.js" integrity="sha512-rpLlll167T5LJHwp0waJCh3ZRf7pO6IT1+LZOhAyP6phAirwchClbTZV3iqL3BMrVxIYRbzGTpli4rfxsCK6Vw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<div class="dvDVRdata" id="dvDVRdata1">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" />
</div>
</div>
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
<div class="del">
<i class="fa fa-minus" aria-hidden="true"></i>
</div>
Related
I am trying to create a dynamic Question List along with its dynamic options. With each option I maintain a flag using checkbox. If the checkbox is clicked the AnalysisFlag value should be true and if not then it should be false. However using the below mentioned method, I am always getting the false value whether I clicked the checkbox or not.
Can someone please take a look and suggest me how I can maintain the AnalysisFlag value along with its equivalent option?
function GetDynamicTextBox(value) {
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("class", "form-control").attr("placeholder","Your Answer");
textBox.val(value);
debugger;
**var allVals = [];
$('[name="DynamicAnalysisFlag"]:checked').each(function () {
allVals.push($(this).val());
});**
return textBox, allVals;
}
var j = 66;
var x = 2;
var option = 'option' + x;
function AddTextBox() {
for (var i = j; i <= j; i++) {
$('#TextBoxContainer' + x).after("<br id='Removebr" + (x + 1) + "'><div class='input-group' id='TextBoxContainer" + (x + 1) + "'><div class= 'input-group-prepend'><div class='input-group-text'> " + String.fromCharCode(i) + " **<input type='checkbox' id='DynamicAnalysisFlag' value= 'true' name='DynamicAnalysisFlag' class='checklistitem''></div>**</div><input autocomplete='off' class='form-control test-option test-option" + x + " text-box single-line' data-val='true' data-val-required='Answer is required' id=" + option + " name='DynamicTextBox' placeholder='Your Answer' type='text' value=''><span class='field-validation-valid text-danger' data-valmsg-for='AnalysisFlag' data-valmsg-replace='true'></span></div>");
}
j++;
x++;
}
function RemoveTextBox() {
if (x != 2) {
$('#TextBoxContainer' + x).remove();
$('#Removebr' + x).remove();
--x;
--j;
}
}
$('#btnNext').on('click', function() {
var radioValue1 = $("input[name='AnalysisFlag']:checked").val();
var txtVal = $('.test-option' + radioValue1).val();
$('#hiddenRadioValue').val(txtVal);
});
$(function() {
var values = eval('#Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function() {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
<div id="radio" class="col-xs-12">
<br id="Removebr2">
<div class="input-group" id="TextBoxContainer2">
<div class="input-group-prepend">
<div class="input-group-text">
A
<input type="checkbox" id="radio1" value="1" name="AnalysisFlag" onselect="alert('clicke')">
</div>
</div>
<input autocomplete="off" class="form-control test-option test-option1 text-box single-line" data-val="true" data-val-required="Option is required" id="opt1" name="opt1" placeholder="Your Answer" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="opt1" data-valmsg-replace="true"></span>
<input data-val="true" data-val-required="The AnalysisFlag field is required." id="hiddenRadioValue" name="AnalysisFlag" type="hidden" value="">
<br>
</div>
</div>
<div class="card-footer">
<input type="submit" id="btnNext" value="Next ยป" class="btn btn-primary vigor-btn">
</div>
<button type="button" id="btnRemove" class="btn btn-primary vigor-btn" onclick="RemoveTextBox()">Remove Options</button>
<button type="button" id="btnAdd" class="btn btn-primary vigor-btn" onclick="AddTextBox()">Add Options</button>
I have edited the GetDynamicTextBox() function in which I am getting the DynamicAnalysisFlag value which I add at the time of adding another textbox in AddTextBox() function. But now the issue is, if I tick the checkbox I am getting the true value but if I don't tick the checkbox I am getting nothing. So, what changes should I do in this code so if I check the code, I get true and if not then I get false.
i am creating a select list dynamically where user can add options after adding select list. Below is my code
<script type="text/html" id="select_field">
<div class='row'>
<div class='col-md-3'><label>Select list name</label>
<div class='form-group'><input type='text' class='form-control select_name'></div>
</div>
<div class="col-md-3">
<label for=""></label>
<select name="" class="form-control select-list" ></select>
</div>
<div class="append_list"></div>
<a class="btn btn-primary pull-right add_values">Add Values</a>
</div>
</script>
JS:
Below JS adds an text field with 2 buttons option to add / remove field to the select list
$form_holder.on('click','.add_values', e => {
var html = "<div class='clearfix'></div>" +
"<div class='col-md-4'><input type='text' class='form-control add_select_option' name='add_value' ><br>" +
"<a class='add_option btn btn-default' value='Add' >Add</a>" +
"<a class='remove_option btn btn-danger' value='Remove' >Remove</a><br></div>";
let $target = $(e.target);
let $value= e.target.value;
let $div = $target.closest('.row').find('.append_list');
$div.append(html);
});
Below Code adds an option to the select list :
$form_holder.on('click','.add_option', e => {
let $target = $(e.target);
console.log($target);
let $value= e.target.value;
let $value_toadd = $target.closest('.col-md-4').find('.form-control').val();
console.log($value_toadd);
let $select_list = $target.closest('.row').find('.select-list');
$($select_list).append($('<option>', {
value: $value_toadd,
text: $value_toadd
}));
});
Now values are added successfully , but my problem is that ::
if I have added value using one text field and click on add button again it embeds new value to the select list using the same text field, how do i uniquely identify each of the text fields while adding entries to select list , please advise .
I also have to use same unique value to remove the entry from the select list
You can give custom attribute to your inputs i.e : data-id . Then , whenever user click on add button check if the custom attr is already present in one of the option of select if yes show some message else add new data to selects .
Demo Code :
var $form_holder = $("form")
$form_holder.on('click', '.add_values', e => {
let $target = $(e.target);
let $value = e.target.value;
let $div = $target.closest('.row').find('.append_list');
//add custom attr
var html = "<div class='clearfix'></div>" +
"<div class='col-md-4'><input type='text' class='form-control add_select_option' name='add_value' data-id='" + $div.find(".col-md-4").length + "'><br>" +
"<a class='add_option btn btn-default' value='Add' >Add</a>" +
"<a class='remove_option btn btn-danger' value='Remove' >Remove</a><br></div>";
$div.append(html);
});
$form_holder.on('click', '.add_option', e => {
let $target = $(e.target);
let $value = e.target.value;
var data_id = $target.closest('.col-md-4').find('.form-control').data('id'); //get custom attr added
let $value_toadd = $target.closest('.col-md-4').find('.form-control').val();
let $select_list = $target.closest('.row').find('.select-list');
//check if select doesn't have that data-id
if ($select_list.find("option[data_value=" + data_id + "]").length <= 0) {
//then only add
$($select_list).append($('<option>', {
data_value: data_id,
value: $value_toadd,
text: $value_toadd
}));
} else {
console.log(" already there ")
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class='row'>
<div class='col-md-3'><label>Select list name</label>
<div class='form-group'><input type='text' class='form-control select_name'></div>
</div>
<div class="col-md-3">
<label for=""></label>
<select name="" class="form-control select-list"></select>
</div>
<div class="append_list"></div>
<a class="btn btn-primary pull-right add_values">Add Values</a>
</div>
</form>
kinda worried with following code that should automatically generate checkbox content AND limit up to 3 the number of checked boxes.
Separately both codes work fine, the issue occurs when they are combined:
Fiddle
$('input[type=checkbox]').change(function(e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
}
})
var skills = ["centres", "tirs", "dribbles", "passes", "vitesse"]
var skillContainer = $("#skillsContainer");
skills.forEach(skill => skillContainer.append('<li> <input type=\"checkbox\" id=\"' + skill + '\" value=\"' + skill + '\"> <label for=\"' + skill + '\"> ' + skill + ' </label> </li>'));
$("#skillsContainer").append(checkboxElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="competencies" action="algo.php" method="POST">
<div class="container">
<ul class="ks-cboxtags" id="skillsContainer">
<input class="button" type="submit" value="Valider">
</ul>
</div>
</form>
You mean this?
You need to delegate when you create dynamic elements
OR add the event handler after the generation
$('#skillsContainer').on("change", 'input[type=checkbox]', function(e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
}
})
var skills = ["centres", "tirs", "dribbles", "passes", "vitesse"]
$("#skillsContainer").html(skills.map(skill => '<li> <input type=\"checkbox\" id=\"' + skill + '\" value=\"' + skill + '\"> <label for=\"' + skill + '\"> ' + skill + ' </label> </li>').join(""));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="competencies" action="algo.php" method="POST">
<div class="container">
<ul class="ks-cboxtags" id="skillsContainer">
<input class="button" type="submit" value="Valider">
</ul>
</div>
</form>
Pure javascript to check checked checkbox length
var eLength = element.length;
var i = 0;
var checkedCheck;
checkbox.forEach(checkBox => {
checkBox.addEventListener('click',function(){
if(this.checked){
i++;
if(i > 3){
checkBox.disabled = true;
alert('Limit reached');
}
}
});
});
Hi I am trying to create an invoicing system. I have a form that I add fields to for every line item and that works I can add and remove the form fields. My problem is I dont know a way to get the price from the prepended line item and add it up to get a subtotal.
this is the html nothing interesting here
<div class="form-row">
<strong>Line Items:</strong>
<br>
<div class="line-items">
<div class="line-item">
<div class="line-item-box description">
<label>Description:</label>
<textarea name="description" id="description"></textarea>
</div>
<div class="line-item-box quantity">
<label>Qty:</label>
<input type="text" name="quantity" id="quantity">
</div>
<div class="line-item-box price">
<label>Price:</label>
<input type="text" name="price" id="price">
</div>
<button class="btn add-item">Add Item</button>
</div>
</div>
</div>
Here is the jquery
$(document).ready(function() {
$('.add-item').click(function() {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price price-saved">$' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
if (!$('.price-summation')[0]) {
$('.line-items').append('<div class="price-summation"><div class="price-row">' + subtotal + '</div><div class="price-row">Taxes</div><div class="price-row">Total</div></div>');
}
return false;
});
$(document).on('click', '.remove-btn', function() {
$('.line-item').remove();
});
});
So I would like to add up the price var for each line item which will be added to the dom dynamically and then display it with the subtotal var.
Is this possible? If so how can I do this?
For a total use a each loop and sum each parsed value of the price,put this in a function and trigger it each time you update the list of items
js:
function price_subtotal(){
var subtotal = 0;
$('.price-saved').each(function(i,v){
subtotal+= parseFloat($(v).text().replace('$',''));
});
$('.subtotal').html(subtotal);
}
$(document).ready(function() {
$('.add-item').click(function() {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price price-saved">$' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
if (!$('.price-summation')[0]) {
$('.line-items').append('<div class="price-summation"><div class="subtotal price-row">0</div><div class="price-row">Taxes</div><div class="price-row">Total</div></div>');
}
price_subtotal();
return false;
});
$(document).on('click', '.remove-btn', function() {
$(this).closest('.line-item').remove();
price_subtotal();
});
});
DEMO
I have a form field calls 'No of Partners' that depends and appear on the selection of the previous dropdown . else it is hidden . with the class 'hide'.My problem I am not able to append a class has-success after validation of this feild. The Code is as follows:
<div class="row" id="divtypeofb">
<div class="col-xs-12">
<div class ="col-md-6">
<div class="form-group">
<label><li class="hide"></li>No of partners<span style="color: red;"> *</span></label>
<input type="number" name="no_of_promoters" id="number_of_promoters" min="2" value="<?=$business_info_details['no_of_promoters'];?>" class="form-control" placeholder="No of Partners involved" onkeyup="numberValidation('no_of_promoters')" >
<span class="help-block hide"><li class="hide"></li>Select the number of partners involved.</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#company_type_id').change(function(){
if($('#company_type_id').val()!=1){
$("#divtypeofb").show(1000).removeClass("hide");
} else {
$("#divtypeofb").hide(1000).addClass("hide");
$("#no_of_promoters").val('');
}
});
});
function numberValidation(id){
if($("#" + id).val() == null || $.trim($("#" + id).val()) == "" || !$.isNumeric($("#" + id).val())){
var div = $("#" +id).closest('div');
var label = div.find('label');
var span = div.find('span');
div.removeClass("has-success");
div.addClass("has-error");
label.find('li').removeClass('fa fa-check hide');
label.find('li').addClass('fa fa-times-circle-o');
span.removeClass("hide");
$("#" + id).focus();
//$("#" + id).scrollTo($(this),1000);
return false;
} else{
var div = $("#" +id).closest('div');
var label = div.find('label');
var span = div.find('span');
div.removeClass("has-error");
div.addClass("has-success");
label.find('li').removeClass('fa fa-times-circle-o hide');
label.find('li').addClass('fa fa-check');
span.addClass("hide");
return true;
}
}
</script>
The keyup attribute is calling the validator with the wrong id: numberValidation('no_of_promoters'). The name of the element is no_of_promoters but the id is number_of_promoters:
<input type="number" name="no_of_promoters" id="number_of_promoters" ...
Your code could also use a clean up since it contains duplicate code in the if and else.
<div class="row" id="divtypeofb">
<div class="col-xs-12">
<div class ="col-md-6">
<div class="form-group">
<label><li class="hide"></li>No of partners<span style="color: red;"> *</span></label>
<input type="number" name="no_of_promoters" id="number_of_promoters" min="2" value="<?=$business_info_details['no_of_promoters'];?>" class="form-control" placeholder="No of Partners involved" onkeyup="numberValidation('number_of_promoters')" >
<span class="help-block hide"><li class="hide"></li>Select the number of partners involved.</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#company_type_id').change(function(){
if($('#company_type_id').val()!=1){
$("#divtypeofb").show(1000).removeClass("hide");
} else {
$("#divtypeofb").hide(1000).addClass("hide");
$("#number_of_promoters").val('');
}
});
});
function numberValidation(id){
var input = $("#" + id);
var value = input.val();
var div = input.closest('div');
var label = div.find('label');
var span = div.find('span');
var li = label.find('li');
if(value == null || $.trim(value) == "" || !$.isNumeric(value)){
div.removeClass("has-success")
.addClass("has-error");
li.removeClass('fa fa-check hide')
.addClass('fa fa-times-circle-o');
span.removeClass("hide");
input.focus();
//input.scrollTo($(this),1000);
return false;
} else{
div.removeClass("has-error")
.addClass("has-success");
li.removeClass('fa fa-times-circle-o hide')
.addClass('fa fa-check');
span.addClass("hide");
return true;
}
}
</script>