jQuery dynamic fields after validation are disappearing - javascript

I have a problem with my jQuery and with validation.
Here is my Code:
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" name="somename[]" id="field_' + field + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" name="somename2[]" id="field_' + field + '"></textarea>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<textarea class="from-control" name="somename[]" id="field"></textarea>
<button class="btn add-field">add</button>
<textarea class="from-control" name="somename2[]" id="field"></textarea>
</div>
<div class="row" id="newfield">
<!-- new textarea -->
</div>
The problem is that I have an validation and I have an button submit, after checking that one field empty is, the code make and redirect and after this redirect to the same page so that user can give his parameter in textarea. But after this redirect, by the user added field are disappeared.
How can I fix it?

You are using the same id in each and every textarea. Id must be unique. Mistakenly you are using "field" which must be replaced with "fielddd" that is being incremented.
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" id="field_' + fielddd + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" id="field_' + fielddd + '"></textarea>');
});

Related

Why val() function doesn't work with later rendered html?

so I have an add minus button rendered with javascript because I needed data from a database and if I don't render it with javascript it will work but it doesn't work.
HTML:
<div id="cart">
<div class="row">
</div>
</div>
JS (rendering):
var output = [];
var food_template = [];
//res is the data got from database
for(var f in res) {
id = res[f]["id"];
name = res[f]["name"];
description = res[f]["description"];
price = res[f]["price"];
food_template = [
'<div class="col-6">',
' <div class="single_food_item media">',
' <div class="media-body", style="margin-right:10px; margin-top: 20px; height: 200px">',
` <h3>${name}</h3>`,
` <p>${description}</p>`,
` <h5>$${price}</h5>`,
//add minus button starts
' <div class="input-group" style="width:50%">',
' <span class="input-group-btn">',
' <button class="btn btn-danger btn-minus" type="button">-</button>',
' </span>',
' <input type="text" class="form-control no-padding add-color text-center height-25" maxlength="3" value="0">',
' <span class="input-group-btn">',
' <button class="btn btn-success btn-plus" type="button">+</button>',
' </span>',
' </div>',
//add minus button ends
' </div>',
' </div>',
'</div>'
];
output.push(food_template.join("\n"));
}
("#cart .row").html(output.join("\n"));
JS (add minus button):
$('#cart .row').delegate('.btn-minus', 'click', function(){
$(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) - 1);
});
$('#cart .row').delegate('.btn-minus', 'click', function(){
$(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) + 1)
});
(all functions are called)
What I test made me think that the problem is probably the val() function isn't changing the value of the input HTML since if I use console.log to show it it works but it doesn't update on the web
I think you have both the plus and the minus event handlers attached to the minus button, so when you click it, the plus handler increments the value and the minus handler decrements it, therefore you see no change regarding the value of the input

Adding div on click only once and allowing customer to delete it and reclick it

I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>

dynamic Accordion post and answer

I have this fiddle
http://jsfiddle.net/nesreen/m5TMF/763/
$("#AddansId").click(function(){
//get the parent of the div with id(Collapse+x)
// to abend the data content of the textarea beside the word
//Account Registeration at PrepBootstrap
});
I can create a dynamic accordion with button
inside each accordion I need to make another textarea and button to add another texts in the same collapse
but I face the problem of how can I get the parent of the button in each time even if the parent id is dynamic also
Let's see. A few steps to take here:
First you need to bind the click a bit differently(event
delegation) in this case because you want to click on dinamically
added elements
Second, we get the parent id using closest() method and attr('id')
For getting the textarea value you can use
$(this).parent().prev().find('textarea').val()
and then use append() method to append the text next to the word you want and finally use $(this).closest('.container').append(answer); to add the textbefore the word(this was a bit unclear so I added it before Account Registeration at PrepBootstrap. I hope that is what you meant)
var x = 1;
$(document).on('click', "#AddansId", function() {
var idOfParent = $(this).closest('.panel-collapse').attr('id');
//console.log(idOfParent);
var answer = $(this).parent().prev().find('textarea').val();
$(this).closest('.container').append(answer);
});
$(document).on('click', '#AddQuestId', function() {
x = x + 1;
$("#accordion").append('<div class="panel panel-default">' +
'<div class="panel-heading">' +
'<h4 class="panel-title"> ' +
'<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse' + x + '">' + $("#comment").val() + '</a> </h4>' +
'</div>' +
'<div id="collapse' + x + '" class="panel-collapse collapse in">' +
'<div class="panel-body">' +
'<div class="container"> ' +
' <form>' +
'<div class="form-group" >' +
'<label for="comment">answer:</label>' +
'<textarea class="form-control" rows="5" id="answer' + x + '"></textarea> ' +
' </div>' +
' <div style="float: right;"> <input type="button" class="btn btn-info" value="answer" id="AddansId"></div>' +
'</form>' +
'</div>' +
'Account registration at <strong>PrepBootstrap</strong>' +
'</div>' +
'</div>' +
'</div>' +
'</h4>' +
'</div>');
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="container">
<form>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div style="float: right;"> <input type="button" class="btn btn-info" value="Add Question" id="AddQuestId"></div>
</form>
</div>
<div class="panel-group" id="accordion">
</div>

add input fields dynamically with codeigniter

I'm trying to add dynamically input fields in Codeigniter when the user clicks the link but it doesn't seem to work. It will be really helpful if someone can figure it out.
My JS code is:
<script src="js/jquery.js" type="text/javascript">
var count = 1;
jQuery(document).ready(function() {
$('p#add_field').click(function(){
count += 1;
$('#language').append(
'<strong>Language #' + count + '</strong><br />'
+ '<input id="language' + count + '"name="languages[]' + '" type="text" /><br />' );\
});
});
</script>
And my form code is:
<div id="container">
some code
<div id="body">
some more code
<div id="language">
<p id="add_field">Προσθηκη Γλώσσας</p>
</div>
</div>
</div>
var count = 1;
$('p#add_field').click(function(){
count += 1;
var html='<strong>Language #'+ count +'</strong><br />'+'<input id="language'+ count +'"name="languages[]'+'" type="text" /><br />';
$('#language').prepend(html);
});
remove all the spaces in appending html . javascript gives Unterminated String literal errors
fiddle

Jquery - dynamically added input field doesn't send value to post

I have this particular jquery code to add/remove fields on a form and then send its values:
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#reglas div").length + 1;
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');
var fName = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fName2 = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fName2);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function() {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
In which you can add/remove fields on the Cache section but the form sends every value except those which were added dynamically.
How can I solve it? You can see the posted form data with Firebug.
Here is a JS Fiddle for you: http://jsfiddle.net/34rYv/121/
Also I realized that when I delete fields, its name doesn't rename.
Maybe you can help me with this too :)
Thanks in advance
Nicolas
Your Cache section stands outside the <form> tags as i see in the source code, so that could be why your fields are not submitted.
Put your form around the left/right div like this:
<div id="wrapper" align="center">
<div class="container" align="center">
<form id="formsite"> // your form starts here
<div id="left">
</div>
<div id="right">
</div>
</form>
</div>
</div>
Instead of this ( what you have right now ):
<div id="wrapper" align="center">
<div class="container" align="center">
<div id="left">
<form id="formsite"> // your form starts here
// the form will automatically be closed in this div
</div>
<div id="right">
</form> // this one will go away
</div>
</div>
</div>
Also, try to keep your code clean, For example:
var fieldWrapper = $('<div></div>',{
class: 'fieldwrapper',
id: 'field'+intId
});
This is way cleaner than:
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');

Categories