I am dynamically adding and removing textboxes though I can successfully adds textbox but unable to remove textbox on clicking the remove button every time i have to reload the browser to remove the textboxes after clicking remove button.
here is my javascript for adding and removing textboxes.
<script type="text/javascript">
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
});
</script>
here is my html for textboxes.
<div id="TextBoxesGroup">
<div class="control-group">
<label class="control-label">answer_1: </label>
<div class="controls">
<input type="text" name="answer_1" id="answer_1" required="true" >
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1">Rank 1</label>
<div class="controls">
<input type="text" name="rank_1" id="rank_1" required="true">
</div>
</div>
<div class="control-group">
<label class="control-label">answer_2: </label>
<div class="controls">
<input type="text" name="answer_2" id="answer_2" required="true" >
<button class="btn btn-mini btn-danger" data-toggle="button" type="button" id="removeButton">
-
</button>
<button class="btn btn-mini btn-success" data-toggle="button" type="button" id="addButton">
+
</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1" required="true">Rank 2</label>
<div class="controls">
<input type="text" name="rank_2" id="rank_2" required="true">
</div>
</div>
</div>
can anyone what's wrong in it so that I am unable to remove textboxes on clicking the button ? Thanks
you need to modify 2 things here:
1- when appending the new elements, mark their holding div with the current COUNTER value at the end, so it's easy to target them later (like on step 2 below).
so adding new elements should be like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group'+COUNTER+'">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
...
...
instead of this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
2- when removing elements, we will target those with the current COUNTER value at the end of their class name,this way you will remove the last group, and still check if the groups are 3 or lower, no removal should happen.
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$(".control-group"+COUNTER).remove();
});
});
Update: check my updated fiddle http://jsfiddle.net/qqqyC/1/
note: considering that we are appending the COUNTER value at the end of the class name. if class is giving you any styles it will not work. in this case you should not use class name as the target property and consider marking the new group using another attribute/property, and target this attribute/property when removing your elements.
Use .on as you want to bind $("#removeButton").click(function () { to dynamically added elements. It should be
$("#removeButton").on("click", function () {
//.....
});
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#answer_" +COUNTER).parent('div').parent('div').remove();
$("#rank_" +COUNTER).parent('div').parent('div').remove();
});
});
Please update script or check this fiddle http://jsfiddle.net/Cne2Q/
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
What you're doing here, - you're trying to remove an element like $("#TextBoxesGroup1") which obviously doesn't exist. So what you need to do is modify your create new input like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div id="textBoxContainer'+COUNTER+'" class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
and your remove button
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#textBoxContainer" +COUNTER).remove();
});
Related
I want to SUM the price of all dynamically created rows and display into total input field..I have tried some things but not working for me.I have posted my script and image that explains how it should works. Everything is working and saving in database just want total amount of all items. Please see image for clear concept. Total of 1st row is saving in total but not working for dynamically created rows.
Image:
It should work like this
Html:
<div class="form-group">
<label>Total</label>
<input readonly type="text" id="total_amount" class="form-control"
name="total_amount">
</div>
Script:
<script>
var counterr = 1;
$(document).ready(function () {
$('#unit_price,#item_quantity').change(function () {
// alert();
var unitPrice = $('#unit_price').val();
// console.log(unitPrice);
var quantity = $('#item_quantity').val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price').val(total);
$('#total_amount').val(total);
});
// Input Fields
var maxField = 100; //Input fields increment limitation
var addButton = $('#add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
$(addButton).click(function (e) {
e.preventDefault();
counterr++;
//Check maximum number of input fields
if (counterr < maxField) {
fieldHTML = makeNewRow(counterr);
$(wrapper).append(fieldHTML); //Add field html
// $('#department-'+counterr).select2();
// console.log("Unit price", counterr);
$('.unit_price' + counterr).change(function () {
// console.log("hello");
var unitPrice = $('.unit_price' + counterr).val();
// console.log(unitPrice);
var quantity = $('#item_quantity' + counterr).val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price' + counterr).val(total);
$('#total_price').each(function() {
subtotal += parseFloat($(this).val());
console.log('test',subtotal);
});
$('#total_amount').val(subtotal);
});
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('#newrow').remove(); //Remove field html
counterr = counterr--; //Decrement field counter
})
});
function makeNewRow(counterr) {
return '<div class="row" id="newrow">' +
'<div class="col-md-4">' +
'<div class="form-group">' +
'<select onChange="getPurchasePrice(this.value);" style="background-color: #f5f6f9" id="item_name' + counterr + '" class="form-control dep"' +
'placeholder="Enter Item" name="testing[]"' + '>' +
'<option value = "">Select Item</option>' + '>' +
'#foreach($items as $item)' + '>' +
'<option value = "{{$item->id}}">{{$item->item_name}}</option>' + '>' +
'#endforeach' + '>' +
'</select>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="item_quantity' + counterr + '" class="form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="unit_price' + counterr + '" class="unit_price' + counterr + ' form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-3">' +
'<div class="form-group">' +
'<input value="0" style="background-color: #f5f6f9" disabled type="text" id="total_price' + counterr + '" class="form-control"' +
'placeholder="Total" name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<a style="height:40px;margin-left:25px" href="javascript:void(0);" class="btn btn-danger remove_button">X</a>' +
'</div>'; //New input field html
}
/*function removeDiv(no){
$("#testingrow-"+no).remove();
x--;
}*/
</script>
Add a function to recalculate the grand total 'recalcGrandTotal'
var recalcGrandTotal = function() {
var grandTotal = 0; // Declare a var to hold the grand total
$("[id^=total_price]").each(function() { // Find all elements with an id that starts with 'total_price'
grandTotal += parseInt($(this).val()); // Add the value of the 'total_price*' field to the grand total
})
$('#total_amount').val(grandTotal); // append grand total amount to the total field
}
Then, hook this function up to the 'total price' recalculation function:
Find
$('#total_price' + counterr).val(total);
Add after:
recalcGrandTotal();
To substract from grand total upon removal of an item, hook this function up to the item removal function. Find:
counterr = counterr--; //Decrement field counter
Add after:
recalcGrandTotal();
This is my jQuery add and remove textbox task, I just want to add my previous all textbox on Add Button. So if I will click first time it will add only 1 and if I will click again it will add 2nd textbox and if I will click again it will add 3rd textbox for me. I want just count the counter variable and then add +2 textbox in it.
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
div {
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h1>jQuery add / remove textbox example</h1>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
If I understand you want the number of input in creation to be always even number .
so simple just check the $("#TextBoxesGroup input").length % 2 wether it's 0 or 1 and create inputs using loop , (this last will create one or input at same time )
See below snippet :
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var num_to_create = 0;
$("#TextBoxesGroup input").length%2 === 0 ? num_to_create = 2 : num_to_create = 1;
for(var inc=0 ; inc < num_to_create; inc++) {
var newTextBoxDiv = $('<div>')
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
}
});
$("#removeButton").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
div {
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h1>jQuery add / remove textbox example</h1>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
I want to add text to dynamically created textbox.
var dynamicTextBox= "";
for (var i = 0; i < vm.FitToWork.length; i++) {
dynamicTextBox+= '<input class="form-control" name = "DynamicTextBox" id= "DynamicTextBox" type="text" value = "'vm.FitToWork[i]'" /> ' +
'<button id="btnAdd" class="delete-decl">+</button>';
}
document.getElementById("TextBoxContainer").innerHTML=dynamicTextBox;
its not working..
You have syntax error. You are trying to concatenate a variable vm.FitToWork[i] but not using concatenation operator (+). Try the following code:
var dynamicTextBox= "";
// ignore this. just have this to get the code working
var vm = {FitToWork : ["test","rest","vest"]};
for (var i = 0; i < vm.FitToWork.length; i++) {
dynamicTextBox += '<input class="form-control" name = "DynamicTextBox" id= "DynamicTextBox" type="text" value = "' + vm.FitToWork[i] + '" />';
dynamicTextBox += '<button id="btnAdd" class="delete-decl">+</button></br>';
}
document.getElementById("TextBoxContainer").innerHTML = dynamicTextBox;
<div id="TextBoxContainer"></div>
You missed concat.
var dynamicTextBox= "";
for (var i = 0; i < vm.FitToWork.length; i++) {
dynamicTextBox+= '<input class="form-control" name = "DynamicTextBox" id= "DynamicTextBox" type="text" value = "'+vm.FitToWork[i]+'" /> ' + '<button id="btnAdd" class="delete-decl">+</button>';
}
document.getElementById("TextBoxContainer").innerHTML=dynamicTextBox;
You forgot to add pluses in value:
... value="' + vm.FitToWork[i] + '" ...
value should be in + + value = "' + value + '"
so value = "'+vm.FitToWork[i]+'"
or you can try this
'<input name = "DynamicTextBox" type="text" value = "' + value + '" />' +
'<input type="button" value="+" id="btnAdd" class="delete-decl" />'
See below code. I am creating 2 text fields at a time. Now how could I type on one text field and make the other twin text field have the same values simultaneously?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
<script>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..."/>' + '<br>' + '</div>' + '</div>');
$(OuterWrapper).append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '">' + '</div>');
x++;
return false;
});
});
</script>
I created a fiddle that I think does what you want: http://jsfiddle.net/3h1h5j7y/
Here is the code.
HTML
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
JavaScript
I added a data- attribute to the inputs with the tfCont id so that they can operate in pairs as they are added.
Also, I am using the on() method so that objects can be added dynamically. It is filtering on the fTypex class.
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});
I had to change $(OuterWrapper) from your example to $("#OuterWrapper") because there was not a variable.
Try something like this :
use onkeyup to call a function which binds the values
HTML
<body>
<input id='ip1' onkeyup='updateOther(this);' type='text'>
<input id='ip2' type='text'>
<script src="script.js"></script>
</body>
JS:
function updateOther(obj){
$('#ip2').val($(obj).val()) ;
}
http://plnkr.co/edit/dpwav5fGcisZcjBIzYyz?p=preview
html code:
<div id="localPropList"></div>
<div id="assignedPropList"> </div>
js code:
function getLocalProposals()
{ // filling these radio buttons dynamically
var htmlStringLocalPro = '<fieldset id="local_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var k = 0; k < result.rows.length; k++) {
var localProposal = result.rows.item(k);
if( !(jQuery.inArray( localProposal.id, arrForQueuePropId ) >=0 ) )
{var fieldId = 'localPro' + k;
htmlStringLocalPro += '<input group="1" type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + localProposal.enquiry_no + ',' + localProposal.id + '"/>'
+ '<label for="' + fieldId + '" data-iconpos="right">' + localProposal.enquiry_no+'-'+localProposal.caller_name+'</label>';
}
htmlStringLocalPro += '</fieldset>';
}
function getAssignedproposals()
{
var htmlString = '<fieldset id="assigned_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var i = 0;i < obj.Proposal.length; i++) {
proposalIds += obj.Proposal[i].id + ',';
if( !(jQuery.inArray( obj.Proposal[i].id, arrForQueuePropId ) >=0 ) ){
var fieldId = 'ap' + i;
htmlString += '<input group="1" type="radio" name="assigned_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
// htmlString += '<input type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
}
}
htmlString += '</fieldset>';}
$("input:radio[name=local_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
$("input:radio[name=queue_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
i need to select only one radio button at a time if radiobutton having name="assigned_proposal_id" is selected then it should not allow to select any radio buttons for name="local_proposal_id]" i cannot assign id different i need to do selection on the basis of name and i cant assign same name to separate group as well
please tell me whats the solution
Checking / Unchecking in jQuery Mobile, you need to use .prop to checked or unchecked and then call .checkboxradio('refresh').
Demo
$(document).on('pageinit', function () {
$(document).on('change', '[type=radio]', function (e) {
// Uncheck radio buttons in #group1 and #group2
$('#group1 [type=radio]:checked, #group2 [type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// "OR" to select all radio buttons in DOM
$('[type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// Check clicked radio
$(this).prop('checked', true).checkboxradio('refresh');
});
});
try the following
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
$('input [name="assigned_proposal_id"]').click(function(){
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
});
It will work like what hussain told
Here A FIDDLE for your purpose. It will uncheck all the radio button, then check the one we clicked on.
HTML :
<div id="localPropList">
<input name="assigned_proposal_id" type="radio" value="value1-1" />value1-1
<input name="assigned_proposal_id" type="radio" value="value1-2" />value1-2
<input name="assigned_proposal_id" type="radio" value="value1-3" />value1-3
</div>
<br/>
<div id="assignedPropList">
<input name="local_proposal_id" type="radio" value="value2-1" />value2-1
<input name="local_proposal_id" type="radio" value="value2-2" />value2-2
<input name="local_proposal_id" type="radio" value="value2-3" />value2-3
</div>
div selected : <span></span>
JQUERY :
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').change(function(){
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').prop('checked', false);
$(this).prop('checked', true);
$('span').html($(this).val());
});
Disable Syntax:
$('input[name="name_here"]').attr('disabled', 'disabled');
Don't go for the hardest thing
Hussein Nazzal is correct but space matters
between input and '[' bracket
if($('input[name="assigned_proposal_id"]:checked').val() != '')
{
$('input[name="local_proposal_id"]:radio').attr('disabled', 'disabled');
}
Demo
This worked for me, take into account that according to the selector this change will apply to all RadioButtons in the document with the same class, in this case class="chartIndex":
$(".chartIndex").change(function () {
$('[type=radio]:checked').prop('checked', false);
$(this).prop('checked', 'checked');
});
Hope this helps someone. Regards.