Dynamically adding and removing div using JQuery? - javascript

I'm trying to create a form that allows a user to enter their experience and education
I would like the user to be able to add and remove education or experience.
I am able to do this... sort of. Only the problem is my new divs that I am creating are being appended to the end of the page instead of being appended after the previous div.
These are my scripts:
$(document).ready(function() {
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name', 'input' + (++inputs));
$('.clonedInput:last').after(c);
});
$('.btnDel').click(function() {
if (confirm('continue delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled', ($('.clonedInput').length < 2));
}
});
});
$(document).ready(function() {
var inputs = 1;
$('#btnAdd2').click(function() {
$('.btnDel2:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name', 'input' + (++inputs));
$('.clonedInput:last').after(c);
});
$('.btnDel2').click(function() {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel2').attr('disabled', ($('.clonedInput').length < 2));
});
});
I understand it's bad form to duplicate code like this but I'm not sure how else to else to do it so that clicking the add button doesn't get pressed for the wrong div...
and my html is:
<form id="myForm">
<h2>Education</h2>
<p>Please add all of your education</p>
<div style="margin-bottom: 4px; border: 2px solid; border-style: dashed" class="clonedInput">
Level: <select>
<option value="secondary">Secondary</option>
<option value="someps">Some Post Secondary</option>
<option value="college">College</option>
</select> <br /> <br />
Did you receive a degree, diploma or certificate?<br />
<select>
<option value="certificate">Certificate</option>
<option>Diploma</option>
<option value="degree">Degree</option>
</select> <br />
<input type="button" class="btnDel" value="Remove Education" disabled="disabled" />
</div>
<div>
<input type="button" id="btnAdd2" value="add Education" />
</div>
<h2>Experience</h2>
<p>Please add all of your experience</p>
<div style="margin-bottom: 4px; class="clonedInput">
Position title: <input type="text"><br /> Years at position:
<input type="number"><br />
Responsibilities: <input type="text"><br />
<input type="text"><br />
Type: <select>
<option>Accounting, banking and Finance</option>
<option>Publishing & Journalism</option>
<option>Social Care & guidance work</option>
</select>
<input type="button" class="btnDel2" value="Remove Experience"
disabled="disabled" />
</div>
<div>
<input type="button" id="btnAdd2" value="add Experience" />
</div>
</form>
Any ideas on how I can fix my script so that when I click the add button for education, a new div containing all of the fields for "education" show up below the previous education box and the same for education?
Any help would be appreciated. Thanks!

Firstly, why do you have 2x $(document).ready? Combine your code into one.
The reason why your duplicated div appear at the end of the form is because both your Education and Experience divs have class="clonedInput", hence $('.clonedInput:last').after(c) causes the duplicated div to be placed after the Experience section (which happens to be the last div that matches the .clonedInput selector).
A solution would to be give each of these sets of divs their own unique class name, such as eduInput and expInput respectively.
The corrected code would hence be:
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.eduInput:first').clone(true);
c.children(':text').attr('name', 'input' + (++inputs));
$('.eduInput:last').after(c);
});
for the education div.
To clean up your code, I suggest binding both Add buttons to the same handler, but act upon them differently by checking the target parameter and determining which set (Education or Experience) to duplicate. Such as:
// single handler and click event for both buttons
var clickHandler = function (e) {
// determine which btnAdd was clicked, such as e.getAttribute('id')
}
$('.btnAdd').click(clickHandler);
But seriously you should clean up your code a little.

Related

How to cut short multiple if else statements in Javascript

I recently came across a situation where I was working on a huge form with atleast 60 fields and I wanted that form to only submit if all fields were filled and if not, I wanted to show a custom message (Sweetalert) for every field not filled.
For example, If first name was left empty, show the message "Please enter your first name", If country of residence was not selected, show them the message that "Please select your country of residence" so on and so forth.
While I was writing tons of if and else statements to match every field using document.getElementById(), this thought of not doing things right came into my mind. I tried searching the web for this but was unable to find a suitable way of doing such things. Can anyone suggest me a better way rather then writing if else statements of 100 lines ?
By adding a specific class to your form controls you'd be able to retrieve them and iterate through them in order to check which ones are not filled.
Let's say this is your form:
<form id="myForm" name="myForm" novalidate>
<div>
<label for="control_1">Label_1:</label>
<input type="text" id="control_1" name="control_1" class="control" />
</div>
<div>
<label for="control_2">Label_2:</label>
<input type="text" id="control_2" name="control_2" class="control" />
</div>
<div>
<label for="control_3">Label_3:</label>
<input type="text" id="control_3" name="control_3" class="control" />
</div>
<div>
<label for="control_4">Label_4:</label>
<select id="control_4" name="control_4" class="control">
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
</select>
</div>
<div>
<input type="submit" value="Submit!" />
</div>
</form>
Then you can use the .control class to retrieve all controls and check them:
function onSubmit(e) {
e.preventDefault();
const controls = document
.getElementById("myForm")
.querySelectorAll(".control");
controls.forEach(control => {
if (!isControlFilled(control)) {
console.log(control.id);
// Do whatever you want with control's id
}
});
}
// This is just for illustrative purposes
// Should be adapted to cover all control types
function isControlFilled(control) {
return control.value ? true : false;
}

Generating dynamic ID's in HTML elements with jQuery

I'm builtin an web resume-generator to learn how to develop for web. I've made a HTML form which the user can add more fields to add more information's about him. Example: he has more than one professional experience, but the form starts with a single prof-exp field to fill. So he clicks in a "add new exp" button and the JS creates a new field for it. I used the clone() method from jQuery to do this, but this gives me with the problems I've listed bellow. Also, here's the code I've made:
var index = 0;
$(document).ready(() => {
$("#add-exp").click(() => {
$("#professional").clone().attr("id", "professional" + index++).
appendTo("#professional-info").find("select, input, textarea").val("");
})
})
<!DOCTYPE html>
<html>
<body>
<form action="" method="GET" id="main">
<fieldset id="professional-info">
<legend><h2>professional experience</h2></legend>
<div id="professional">
<label for="level">Nível: <select name="level" id="level" >
<option value="empty">Selecione</option>
<option value="estagio">Estágio</option>
<option value="junior-trainee">Junior/Trainee</option>
<option value="aux-opera">Auxiliar/Operacional</option>
<option value="pleno">Pleno</option>
<option value="senior">Sênior</option>
<option value="sup-coord">Supervisão/Coordenação</option>
<option value="gerencia">Gerência</option>
</select></label>
<label for="position"> Cargo: <input type="text" name="carrer" id="carrer" ></label><br>
<label for="company"> Empresa: <input type="text" name="company" id="company" ></label><br>
<label for="begin"> Início: <input type="month" name="begin" id="begin" ></label>
<label for="break"> Término: <input type="month" name="break" id="break" ></label>
<label for="stl-work"><input type="checkbox" name="stl-work" id="stl-work" >Ainda trabalho aqui</label><br>
<label for="job-desc"> Descrição: <textarea name="job-desc" id="job-desc" placeholder="Conte um pouco sobre o que você fazia lá." cols="40" rows="1"></textarea></label>
<button type="button" id="remove-exp" >Remove this professional xp</button>
</div>
<button type="button" form="main" id="add-exp">Add other professional exp</button>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
The problems are:
Only the divs have dynamic ID's, which causes me the following two other problems;
I don't know how to implement the remove button logic, since I cannot make difference between the 1st button and the other ones from other divs;
Since the labels use their correspondent input ID to make reference, when the user clicks it, they point to the first field inputs;
I hope you guys could understand my problem and help me with it. Also, sorry for my english - i'm learning too. Thank you all!
As suggested, Vue.js is cool, but jQuery has some forgotten powers too.
And, since you create elements dynamically, don't use IDs.
And submit to the backend your experiences as arrays []: i.e: name="carrer[]", name="company[]" etc. Than on the backend loop those data arrays to retrieve all the user experiences.
const new_exp = () => $('<div>', {
'class': 'professional-exp',
html: `
<label>Nível:
<select name="level[]">
<option value="empty">Selecione</option>
<option value="estagio">Estágio</option>
<!-- etc... -->
</select>
</label>
<label>Cargo: <input type="text" name="carrer[]"></label><br>
<label>Empresa: <input type="text" name="company[]"></label><br>
<label>Início: <input type="month" name="begin[]"></label>
<label>Término: <input type="month" name="break[]" ></label>
<label><input type="checkbox" name="stl-work[]"> Ainda trabalho aqui</label><br>
<label>Descrição: <textarea name="job-desc[]" placeholder="Conte um pouco sobre o que você fazia lá." cols="40" rows="1"></textarea></label><br>
`,
append: $('<button>', {
type: 'button',
text: 'Remove',
click() {
$(this).closest('.professional-exp').remove();
}
}),
appendTo: '#professional',
});
jQuery($ => { // DOM ready and $ alias in scope
new_exp(); // On init (Create first exp)
$("#new_exp").on('click', new_exp); // On click
});
.professional-exp {
padding: 10px;
margin-bottom: 10px;
background: #eee;
}
<form action="" method="POST" id="main">
<fieldset>
<legend>
<h2>Professional experience</h2>
</legend>
<div id="professional"></div>
<button type="button" id="new_exp">+ Add more</button>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Above we're defining the Remove's button action right within the template, but if you want you can also hardcode the button into the template and create a dynamic click handler (using jQuery's .on()) like:
const exp_new = () => $('<div>', {
'class': 'professional-exp',
html: `
<label>Nível:
<select name="level[]">
<option value="empty">Selecione</option>
<option value="estagio">Estágio</option>
<!-- etc... -->
</select>
</label>
<label>Cargo: <input type="text" name="carrer[]"></label><br>
<label>Empresa: <input type="text" name="company[]"></label><br>
<label>Início: <input type="month" name="begin[]"></label>
<label>Término: <input type="month" name="break[]" ></label>
<label><input type="checkbox" name="stl-work[]"> Ainda trabalho aqui</label><br>
<label>Descrição: <textarea name="job-desc[]" placeholder="Conte um pouco sobre o que você fazia lá." cols="40" rows="1"></textarea></label><br>
<button class="exp_delete">REMOVE</button>
`,
appendTo: '#professional',
});
jQuery($ => { // DOM ready and $ alias in scope
exp_new(); // On init (Create first exp)
$("#exp_new").on('click', exp_new); // and on click.
$('#main').on('click', '.exp_delete', ev => $(ev.target).closest('.professional-exp').remove());
});
.professional-exp {
padding: 10px;
margin-bottom: 10px;
background: #eee;
}
<form action="" method="POST" id="main">
<fieldset>
<legend>
<h2>Professional experience</h2>
</legend>
<div id="professional"></div>
<button type="button" id="exp_new">+ Add more</button>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Details of demo code are commented in the code itself. There are minor changes to some classes for <fieldset>s and <button>s. The structure is altered a little so keep that in mind. jQuery is versatile and it allows you to generalize DOM operations and do away with dependency on ids -- it's very possible to just use classes.
Events registered to dynamic tags fail unless you delegate events. To delegate a click event to all buttons existing currently and in the future, register an ancestor tag that the buttons commonly share (ex. #main). Then assign the selectors of the buttons in the second parameter (event data):
$('#main').on('click', '.add, .remove', function(e) {...
As for removing a by clicking a nested button -- $(e.target) and $(this) can be used to reference the button that was currently clicked. When you need to find the appropriate ancestor of a clicked button (ex. .professional) use .closest() method like so:
$(e.target).closest('.professional').remove();
Demo
let index = 0;
// Hide the first .remove button
$('#remove').hide();
/*
Register the form to the click event
Event data directs .add and .remove buttons
*/
$("#main").on('click', '.add, .remove', function(e) {
// if the clicked button has .add
if ($(this).hasClass('add')) {
/*
clone the first .professional
increment counter
Reference all form controls of the clone
on each form control modify its id
*/
const dupe = $(".professional:first").clone(true, true);
index++;
const formControls = dupe.find('select, button, input, textarea');
formControls.each(function() {
let ID = $(this).attr('id');
$(this).attr('id', ID + index);
});
/*
Remove the legend from clone
Show the .add and .remove on clone
Hide the clicked button
Add clone to form
Stop event bubbling
*/
dupe.find('legend').remove();
dupe.find('.add, .remove').show();
$(e.target).hide();
$('#main').append(dupe);
e.stopPropagation();
// Otherwise if clicked button has .remove...
} else if ($(e.target).hasClass('remove')) {
/*
Find clicked button ancestor .professional and remove
it.
Hide all .add buttons
Show the last .add
Stop event bubbling
*/
$(e.target).closest('.professional').remove();
$('.add').hide();
$('.add:last').show();
e.stopPropagation();
} else {
// Otherwise just stop event bubbling
e.stopPropagation();
}
});
:root {
font: 400 14px/1 Consolas
}
fieldset {
width: fit-content
}
legend {
margin-bottom: -15px
}
label {
display: block
}
input,
select,
button {
display: inline-block;
font: inherit;
height: 3ex;
line-height: 3ex;
vertical-align: middle
}
.text input {
width: 24ch
}
select {
line-height: 4ex;
height: 4ex;
}
label b {
display: inline-block;
width: 7.5ch;
}
button {
position: absolute;
display: inline-block;
height: initial;
margin: 0;
}
.add {
position: absolute;
right: 0;
}
[for=level] b {
width: 6ch
}
.btn-grp {
position: relative;
width: 97%;
min-height: 26px;
padding: 0
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="" method="GET" id="main">
<fieldset class="professional">
<legend>
<h2>Professional Experience</h2>
</legend>
<label for="level">
<b>Nível: </b>
<select name="level" id="level">
<option value="empty">Selecione</option>
<option value="estagio">Estágio</option>
<option value="junior-trainee">
Junior/Trainee
</option>
<option value="aux-opera">
Auxiliar/Operacional
</option>
<option value="pleno">Pleno</option>
<option value="senior">Sênior</option>
<option value="sup-coord">
Supervisão/Coordenação
</option>
<option value="gerencia">
Gerência
</option>
</select>
</label>
<fieldset class='text'>
<label for="carrier"><b>Cargo: </b>
<input type="text" name="carrer" id="carrer">
</label>
<label for="company"><b>Empresa: </b>
<input type="text" name="company" id="company">
</label>
<label for="begin"><b>Início: </b>
<input type="month" name="begin" id="begin">
</label>
<label for="break"><b>Término: </b>
<input type="month" name="break" id="break">
</label>
</fieldset>
<label for="stl-work">
<input type="checkbox" name="stl-work" id="stl-work" >Ainda trabalho aqui
</label>
<label for="job-desc"><b>Descrição: </b></label>
<textarea name="job-desc" id="job-desc" placeholder="Conte um pouco sobre o que você fazia lá." cols="35" rows="1"></textarea>
<fieldset class='btn-grp'>
<button type="button" id='remove' class='remove'>Remove</button>
<button type="button" id='add' class="add">Add</button>
</fieldset>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
if you already wrap your input inside a label, you dont need id anymore,
and you can use this as a parameter of delete button, so you can use it to delete your block.
Please check the following example
$(function(){
// keep the first block hidden as an empty template
$('.form-row:first').hide();
// trigger add new item
AddItem();
})
function AddItem(){
var container = $('#container');
// clone the form, show it & append before add button
var cloned = $('.form-row:first').clone().show().insertBefore($('#addBtn'));
}
function RemoveItem(elm){
// get form element & remove it
$(elm).closest('.form-row').remove()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style type="text/css">
.form-row {border:1px solid #ccc; margin:5px 0;padding:10px;}
</style>
<div id="container">
<div class="form-row">
<!-- wrap your input inside label tag to avoid using id as reference -->
<label>Field 1 : <input type="text" name="field1"></label>
<label>Field 2 : <input type="text" name="field2"></label>
<input type="button" value="Remove this item" onclick="RemoveItem(this)">
</div>
<input id="addBtn" type="button" value="Add new item" onclick="AddItem()">
</div>
One way to connect your new "remove" button with its "professional" div would be to add an extra statement in your event handler to update its id parallel to the new div's id, something like:
let lastIndex = index - 1;
$("#professional" + lastIndex).find("button").attr("id", "add-exp" + lastIndex);
(This code may not have the correct syntax -- I don't use jQuery very much -- but you can see the idea.)
A better way might be, when the "remove" button is clicked, don't remove according to ID, but instead find the closest ancestor div and remove that div.
For labels, you should leave out the ids (because no two elements on the same page should ever have the same id). And because the inputs are nested in the labels, you should be able to leave out the for attribute as well and let the the association be implicit. (See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label.)

Displaying text with JavaScript from multiple conditions in form

In this question I would like to display some HTML text depending on a which combination of options is selected in a form. In this example for instance, I want to display some text if spelling is selected as a subcategory and 'greater-depth' (equivalent to an 'A' grade) is selected as the performance grade. I've developed this in Rails form_for but have shown the form as rendered in the browser.
<form class="new_english_grade" id="new_english_grade" action="/english_grades" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="VTtOS/86shuyQPW6/HfaduffmQiVXLiJb06IQp7+56LM8cD8KRnD3qLGbQBit4OuAIc92MYbFpPObR6ePYmY1g==" />
<div class="field">
<label for="english_grade_subcategory">Subcategory</label>
<select name="english_grade[subcategory]" id="english_grade_subcategory"><option value="Spelling">Spelling</option>
<option value="Reading">Reading</option>
<option value="Writing">Writing</option></select>
</div>
<div class="field">
<label for="english_grade_performance_grade">Performance grade</label>
<select name="english_grade[performance_grade]" id="english_grade_performance_grade"><option value="Not-started">Not-started</option>
<option value="Working-towards">Working-towards</option>
<option value="Working-at">Working-at</option>
<option value="Greater-depth">Greater-depth</option></select>
</div>
</form>
The text I'd like to display for instance is like:
<div id = "spelling_greater_depth">
This text is displayed only if 'spelling' and 'greater-depth' are selected in options
</div>
I have initially set my CSS to be:
#spelling_greater_depth
{
display: none;
}
My JavaScript is not really working yet so I have not included it but I was trying to implement it using this:
I think this might be enough to get you started https://jsfiddle.net/sxh0n7d1/37/
However it is very difficult to answer the question, can you clarify your question or give feedback to this answer if it is close?
$('select[name="english_grade"]').change(function () {
$('#spelling_working_at').css("display","none");
console.log($(this).val());
var fieldToShow = $(this).val();
$("#" + fieldToShow).css("display","block");
});

POST DATA issues when adding new elements to the page

Hi all I have a form in which I dynamically add in a new row consisting of a text box and check button on button press. However I need some sort of way to know which checkbuttons were pressed in the post data and therefore need a value field consisting of an ID on each of the the check buttons, code is seen below:
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS to add new row:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
can anyone suggest a good way to help me know in the post data which text field, links to which check button, and to know if it was pressed?
at the moment if you were to add 3 rows and check row 3 I have no way of identifying that row three was the button pressed - This is my issue
after you cloned it, change the name so you know about this input
also it's good to have a counter for naming:
like : 'somename[myInput' + counter + ']'
update:
var counter = 0;
var $template = $('.template');
$('input[type=button]').click(function() {
counter++;
$template.clone().attr('name' , 'somename[myInput' + counter + ']').insertAfter($template);
});
now you have array named:somename which you can have a loop over its content on your form handler.

How to remove a particular div tag and reset its content using javascript

Code below contains certain tags in all four.
Image-1
here is the code :
<div style='background-color:YellowGreen;height:20px;width:100%;margin-top:15px;font-weight: bold;'>
Delegate(s) details: </div>
<div style="border:1px solid black;"><br/>
<div id="delegates">
<div id="0">
Name of the Delegate:
<input name='contact_person[]' type='text' size="50" maxlength="50" />
Designation:
<select name='delegate_type_name[]' class='delegate_type'>
<option value='select'>Select</option>
<option value='Main'>Main</option>
</select>
</div><br/>
</div>
<div>
<input type="button" name="more" value="Add More Delegates" id="add_more" />
<br />
<br />
</div>
</div>
In the above code on line 5 where <div id="0"> changes to value 1 in script that I mentioned in "add_more"
And the javascript for "add_more" is given below
jQuery('#add_more').click(function(){
var id = jQuery('#delegates > div:last').attr('id');
var temp = "<div id='"+(parseInt(id)+parseInt('1'))+"'> Name of the Delegate: <input type='text' size='50' maxlength='50' name='contact_person[]' /> Designation:";
temp += "<select name='delegate_type_name[]' class='delegate_type additional_delegate'><option value='select'>Select</option><option value='Additional'>Additional</option><option value='Spouse'>Spouse</option></select> <input type='button' name='rem' value='Remove' id='remove' /></div><br/>";
jQuery('#delegates').append(temp);
});
In the javascript code above I have added a remove button in the temp+ variable
<input type='button' name='rem' value='Remove' id='remove' />
Image-2 shows the remove button every time I click on "Add more Delegates" button.
In the image-2 I click on Add More Delegates button it shows the "remove" button on the right of drop down select list.
I want a jQuery function for remove button, so that when I click on remove it should remove <div id="1"> and also reset content before removing the div tag. Below image-3 is the output that I want when I click on remove button.
code that I tried was this from some reference is this
jQuery('#remove').click(function(){
var id = jQuery('#delegates > div:last').attr('id').remove();
});
but no luck.
Thanks.
You can't give an element id that is only a number, it must be #mydiv1, #mydiv2 or something similar, i.e. beginning with a letter not a number.
For starters your markup is a total mess. There is no way you should be using for layout purposes. Read up on tableless layouts and css.
The first thing you need to change is the id's of your div. An id cannot start with a numeric. I suggest naming the first div delegate0. Secondly, you are adding a remove button on every new row with the same id - all id's on a page should be unique so i suggest you change this to class="remove".
As for your question, it really boils down to needing to add a jQuery handler to the remove buttons using the .livedocs method.
This is as simple as:
jQuery('.remove').live('click',function(){
$(this).closest('div').remove();
});
Also, you need to keep a running counter of the id of the items added, and increment this every time a new row is added.
var nextDelegate = 1;
jQuery('#add_more').click(function(){
... your code here
nextDelegate++;
});
Also, I removed the superfluous <br/> after each div.
Live example: http://jsfiddle.net/cb4xQ/

Categories

Resources