Use maskMoney in input that is created dynamic - javascript

In the form that opens by default the function in js works well.
But then in the form I have the possibility to create more fields dynamically, but in those fields that you create dynamically it doesn't work.
Let me explain.
Code:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
var length = wrapper.find("input:text").length;
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div id="teste"><div class="form-group col-md-2"><input type="text" class="form-control1 Preco" name="Valor[]" value="0.00" /><span class="form-highlight">$</span><span class="form-bar"></span><label class="label1" for="Valor">Valor</label></div><button class="remove_field" style="background-color: #313348;"><span class="fa fa-trash fa-fw" aria-hidden="true"></span></button></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$("#teste").remove();
x--;
})
});
$(function() {
$('.Preco').maskMoney({ decimal: '.', thousands: ' ', precision: 2 });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
<button class="btn btn-warning caixa add_field_button" style="float:right;"><i class="fa fa-plus-square fa-5x taman" aria-hidden="true"></i></button>
<div class="input_fields_wrap">
<div class="form-group col-md-2">
<input type="text" class="form-control1 Preco" name="Valor[]" value="0.00" required>
<span class="form-highlight">$</span>
<span class="form-bar"></span>
<label class="label1" for="Valor">Valor</label>
</div>
</div>
As I show in the example the first input works correctly, but when I create a dynamic input it lets the maskMoney function work

$(document).ready(function() { and $(function() { are the same thing. (This is mentioned in the jQuery documentation for .ready()) Because of that, you've essentially declared two onready handlers. onready handlers can happen in any order.
Combine them into one onready handler and order the contents such that the call to maskMoney happens last.

Related

Change button value after clicking on it [duplicate]

This question already has answers here:
Changing button text onclick
(19 answers)
Closed 4 years ago.
I have a function which returns bootstrap row and every row contains input field, textarea and remove button.
So I have multiple bootstrap rows as I am calling function for various time. After clicking on remove button I am changing border color of input and textarea just to indicate that I am not taking it into consideration. I have made remove button to work as toggle button so that it will add and remove error class that I am assigning to input and textarea.
Now I want to change the value of 'Remove' button to 'Add'. So that when I click on 'Add' button it will remove the style of input and textarea and it means that I can take those values into consideration.
function GetDynamicTextBox(value, tag) {
return'<div class="col-lg-4"><input class="form-control" type="text" value="'+tag+'" name="typetag" id="tags" data-role="tagsinput"/></div>'+'' +
'<div class="col-lg-6"><textarea class="form-control issuetext" name="comment" id="" cols="" rows="">'+value+'</textarea></div>'+
'<div class="col-lg-2">'+
'<input type="button" value="Remove" class="remove btn btn-default" /></div>'
}
$("body").on("click", ".remove", function () {
$(this).closest('#issue').find('.bootstrap-tagsinput').toggleClass('error')
$(this).closest('#issue').find('.issuetext').toggleClass('error')
});
<div class='row'id="issue">
<div class="col-lg-4">
<input class="form-control" type="text" value="'+tag+'" name="typetag"
id="tags" data-role="tagsinput"/></div>
<div class="col-lg-6">
<textarea class="form-control issuetext" name="comment" id="" cols=""
rows="">'+value+'</textarea></div>
<div class="col-lg-2">
<input type="button" value="Remove" class="remove btn btn-default" /></div>
</div>
It's pretty straightforward. Just add a click event to the button. The click event will give you an event (e) and you can then call the standard .innerText property on the element to set it. No need for jQuery here...
const btn = document.getElementById('testButton');
let clickCount = 0;
btn.addEventListener('click', (e) => {
e.currentTarget.innerText += clickCount++;
});
<button type="text" id="testButton">Initial Value</button>
You can add an event listener to the button and change its textContent according to the value of a global variable.
<button id="removeOrAdd">Remove</button>
<script>
var remove = true;
document.getElementById("removeOrAdd").addEventListener("click", function(e){
if(remove){
this.textContent = "Add";
remove = false;
} else {
this.textContent = "Remove";
remove = true;
}
});
</script>

jquery link not working after removeClass('disabled')

I have a script that disables links with a class "disabled"
//disabled links
$(document).ready(function() {
$(".disabled a").click(function() {
return false;
});
});
Additionally, I have a script that when the ".edit" button is clicked toggles the disabled state of the inputs in it's own form. It also does a removeClass('disabled') on any matching links in the form.
//toggle form edit
$("#edit").click(function(e) {
e.preventDefault();
$(this).closest("form").find("input").prop('disabled',false);
$(this).closest("form").find(".input-group-addon").removeClass('disabled');
$("#save").prop('disabled',false);
$("#edit").prop('disabled',true);
$(".alert").hide(400, "swing");
});
Then there is a script for adding and deleting input fields
//add input fields
$(".form-group").on('click', 'a.addInput', function() {
var original = $(this).closest(".input-group");
original.clone().insertAfter(original);
});
//remove input fields
$(".form-group").on('click', 'a.deleteInput', function() {
var original = $(this).closest(".input-group");
if($(this).closest(".form-group").children(".input-group").length > 1) {
original.remove();
}
});
HTML:
<form class="edit">
<div class="panel">
<div class="panel-heading">
<span><i class="fa fa-user" aria-hidden="true"></i> Basic Information</span>
<span class="pull-right"><input id="save" class="btn btn-success" type="submit" value="Save" disabled></span>
<span class="pull-right"><button id="edit" class="btn btn-default">Edit</button></span>
</div>
<div class="panel-body">
<div class="form-group">
<label for="email">Email</label>
<div class="input-group">
<input type="email" class="form-control" placeholder="Email" name="email" value="engelo#dingosoft.us" disabled required>
<div class="input-group-addon disabled"><span class="fa fa-plus"></span></div>
<div class="input-group-addon disabled"><span class="fa fa-minus"></span></div>
</div>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<input type="tel" class="form-control" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
<div class="input-group-addon disabled"><span class="fa fa-plus"></span></div>
<div class="input-group-addon disabled"><span class="fa fa-minus"></span></div>
</div>
</div>
</div>
</div>
</form>
The problem I am having is that when the class "disabled" is removed from the links, the links ('a.addInput') & ('a.deleteInput') do not function. What am I missing here?
Click handlers are attached to elements, not to selectors. So when you do this:
$(".disabled a").click(function() {
return false;
});
You are assigning that behavior to all elements which match at that moment (in this case, when the document loads). No matter what changes you make to the DOM after the fact, any elements which were matched when you invoked the above code will still have the above click handler.
One approach here could be to assign the click handler to a common unchanging parent, instead of to the elements themselves. By using .on() in this way, you can evaluate the selector dynamically when the click event happens instead of just once when the page loads. Something like this:
$(document).on("click", ".disabled a", function() {
return false;
});
Then the second selector (".disabled a") will be evaluated with each click. So if the DOM has changed such that an element no longer matches that selector, this click handler won't be used.
You need to add prevent the event.
$(".form-group").on('click', 'a.addInput', function(e) {
e.preventDefault();
var original = $(this).closest(".input-group");
original.clone().insertAfter(original);
});
//remove input fields
$(".form-group").on('click', 'a.deleteInput', function(e) {
e.preventDefault();
var original = $(this).closest(".input-group");
if($(this).closest(".form-group").children(".input-group").length > 1) {
original.remove();
}
});
or you can add a href="javascript:void(0);" to addInput and deleteInput.
I hope it will be help to achieve your goal...

error on removing divs dynamically

I'm trying to add 3 fields dynamically (2 text fields and 1 remove button) per row. The add button is working fine. The problem is the remove function. When I add 2 fields or more, and I try to remove the first, both added fields/rows are deleted
This is my html code:
<div class="col-lg-12">
<div class="field_wrapper form-group col-sm-12">
<div class="form-group col-sm-4">
<input type="text" name="id[]" value="" class="form-control"/>
</div>
<div class="form-group col-sm-4">
<input type="text" name="name[]" value="" class="form-control"/>
</div>
<div class="form-group col-sm-4">
Adicionar Valor
</div>
</div>
</div>
This is the javascript:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper:last'); //Input field wrapper
var wrapper_delete = $('.field_wrapper');
//var fieldHTML = '<div><input type="text" name="field_name[]" value=""/>Remover</div>'; //New input field html
var fieldHTML = '<div class="field_wrapper form-group col-sm-12"><div class="form-group col-sm-4"><input type="text" name="id[]" value="" class="form-control"/></div><div class="form-group col-sm-4"><input type="text" name="name[]" value="" class="form-control"/></div><div class="form-group col-sm-4"><i class="fa fa-trash-o"></i></div></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
wrapper = $('.field_wrapper:last'); //Input field wrapper
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
var count = $('.field_wrapper').length;
fieldHTML = '<div class="field_wrapper form-group col-sm-12"><div class="form-group col-sm-4"><input type="text" name="id_'+ count +'" value="" class="form-control"/></div><div class="form-group col-sm-4"><input type="text" name="name_' + count +'" value="" class="form-control"/></div><div class="form-group col-sm-4"><i class="fa fa-trash-o"></i></div></div>'; //New input field html
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper_delete).on('click', '.remove_button', function(e){ //Once remove button is clicked
wrapper_delete = $('.field_wrapper');
e.preventDefault();
$(this).closest('.field_wrapper').remove();
x--; //Decrement field counter
});
});
</script>
How can I fix this?
You're appending the new field_wrapper element to field_wrapper:last. You should place it after, so instead of .append() you should use .after().
$(wrapper).after(fieldHTML); // Add field html
And delegate click event on document (or closest static ancestor), because .field_wrapper element is also dynamicaly added and you can't attach event to it.
$(document).on('click', '.remove_button', function(e){
JSFiddle
Looking at what you're trying to do. I'd recommend to use .clone([with events]). You don't actually need to change input names (unless the reason is other than avoiding name duplicates), as they are set to arrays.
This way, all your code could be as simple as below:
$('.add_button').click(function(){
$('.field_wrapper').length >= maxField ||
wrapper.clone(true).find('a.btn').toggle().end().insertAfter('.field_wrapper:last');
});
$('.remove_button').hide().click(function(){
$(this).closest('.field_wrapper').remove();
});
var maxField = 10, wrapper = $('.field_wrapper').clone(true);
JSFiddle

Adding both textbox and textarea dynamically

Need to add textbox and textarea dynamically to one of my forms. I found this example which works fine for adding textbox dynamically.
Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Result
I tried adding a textarea
$(wrapper).append('<div><textarea name="desc[]"></textarea></div>Remove</div>');
to the above javascript
and to the HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
<div><textarea name="desc[]"></textarea></div>
</div>
but it turns out to be erroneous. How should I add a textarea along with the textbox?
Error
The maximum limit allowed is 10. Say I add 6 of these fields and then decide to use 5 of them. If, I remove the last (6th one in this case) all of them get removed.
EDIT
Link to the above code https://jsfiddle.net/x6krv00u/
** I do not know much about javascripts.**
I think you are doing like this
$(wrapper).append('<div><input type="text" name="mytext[]"/><textarea name="desc[]"></textarea></div>Remove</div>');
And for this following should work
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
$(this).parent().remove(); // you cannot pass 'div' in parent()
});
The input and textarea don't have the same parent. That's what's causing the problem.
This should be the DOM structure:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="mytext[]"><br>
<textarea name="desc[]"></textarea>
</div>
</div>
Of course, the <br> is optional. You should probably use CSS for formatting instead.
Here's how you add an input-textarea pair:
$(wrapper).append('<div>' +
'<input name="mytext[]"><br>' +
'<textarea name="desc[]"></textarea>' +
'Remove' +
'</div>');
Here's a working example, which you can copy-paste:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="mytext[]"><br>
<textarea name="desc[]"></textarea>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>' +
'<input name="mytext[]"><br>' +
'<textarea name="desc[]"></textarea>' +
'Remove' +
'</div>');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Hope this helps.
PS: I've tried to make minimal changes to your code. There are other (better) ways of accomplishing what you want.
Edit 0: Improved formatting.

How to generate different name for textbox input which is created dynamically

I have dynamically created textboxes with delete buttons for 7 days of the week using jQuery append. I'm using the same function for the 7 append buttons, its working fine, but I need to generate text boxes with different name.
I means if I click on Sunday add button textbox name or id should be sunday text1 sunday text2, and same for other weekdays, how can I do it?
<script>
$(document).ready(function() {
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var i = 1;
$(add_button).click(function(e){
e.preventDefault();
i++;
$(this).parent().append('<div><label class="titlesmall-font">From time</label><input type="text" class="form-control"/><label class="titlesmall-font"> To Time</label><input type="text" class="form-control" /><label class="titlesmall-font">Price</label><input type="text" class="form-control" /><input type="button" class="btn btn-danger remove_field padding-top-5 delete" style="margin-top:5px; margin-left:4%;" value="Delete"></div><div class="clearfix"></div>');
});
$(wrapper).on("click",".remove_field", function(e){
e.preventDefault(); $(this).parent('div').remove(); i--;
})
});
</script>
Observe following changes,
var $wrapper = $(".input_fields_wrap");
var $add_button = $(".add_field_button");
$add_button.click(function(e){
e.preventDefault();
i++;
$(this).parent().append('<div><label class="titlesmall-font">From time</label><input type="text" class="form-control"/><label class="titlesmall-font"> To Time</label><input type="text" class="form-control" /><label class="titlesmall-font">Price</label><input type="text" class="form-control" /><input type="button" class="btn btn-danger remove_field padding-top-5 delete" style="margin-top:5px; margin-left:4%;" value="Delete"></div><div class="clearfix"></div>');
});
$wrapper.on("click",".remove_field", function(e){
e.preventDefault(); $(this).parent('div').remove(); i--;
});
As,
$wrapper and $add_button already are jQuery Object so no need to wrap then again inside $

Categories