Remove form field javascript - javascript

I have a form where I have a table with an employee and every time I click on plus a new row for employee is added but when I click the remove field the script add a new row till the maximum. So what I want is the "-" icon to remove the field added.
This is what I came up with so far ...
$(document).ready(function () {
// Input fields increment limitation
var maxField = 3;
// Add button selector
var addButton = $('.add_button');
// Input field wrapper
var emp = $('#employee_tbl');
// New input field html
var fieldHTML = '<tr><td><label for="employee"><i class="fas fa-minus-circle"></i></label><input type="text" name="employee" class="remove_button" id="employee" required></td></tr>';
// Initial field counter is 1
var x = 1;
// Once add button is clicked
$(addButton).click(function () {
// Check maximum number of input fields
if (x < maxField) {
// Increment field counter
x++;
// Add field html
$(emp).append(fieldHTML);
}
});
// Once remove button is clicked
$(emp).on('click', '.remove_button', function (e) {
e.preventDefault();
// Remove field html
$(this).parent('div').remove();
// Decrement field counter
x--;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<table id="employee_tbl">
<tr>
<th>
<b><span data-i18n-key="employee">Employee</span></b>
</th>
</tr>
<tr>
<td>
<label for="employee"><i class="fas fa-plus-circle"></i></label>
<input type="text" name="employee" class="add_button" id="employee" required/>
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You're removing parent('div') while there is no one. Use closest('tr') instead.
Also, you had classes add_button and remove_button on wrong elements.
And id should be unique in HTML.
$(document).ready(function () {
// Input fields increment limitation
var maxField = 3;
// Add button selector
var addButton = $('.add_button');
// Input field wrapper
var emp = $('#employee_tbl');
// New input field html
var fieldHTML = '<tr><td><label for="employee"><i class="fas fa-minus-circle remove_button"></i></label><input type="text" name="employee" required></td></tr>';
// Initial field counter is 1
var x = 1;
// Once add button is clicked
$(addButton).click(function () {
// Check maximum number of input fields
if (x < maxField) {
// Increment field counter
x++;
// Add field html
$(emp).append(fieldHTML);
}
});
// Once remove button is clicked
$(emp).on('click', '.remove_button', function (e) {
e.preventDefault();
// Remove field html
$(this).closest('tr').remove();
// Decrement field counter
x--;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<table id="employee_tbl">
<tr>
<th>
<b><span data-i18n-key="employee">Employee</span></b>
</th>
</tr>
<tr>
<td>
<label for="employee"><i class="fas fa-plus-circle add_button"></i></label>
<input type="text" name="employee" required/>
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

First of all the OP needs to sanitize the HTML structure.
What is currently used is too complex and constantly at risk of becoming invalid markup due to how the label-control relationship gets handled. The "label for="<id>"" management is not needed especially since with this kind of structure one always is in danger of providing identical id values.
Thus the first change provides a generic id agnostic structure ...
<tr>
<td>
<label for="employee"><i class="fas fa-plus-circle"></i></label>
<input type="text" name="employee" class="add_button" id="employee" required/>
</td>
</tr>
... changes to ...
<tr>
<td>
<label>
<i class="fas fa-plus-circle add_button"></i>
<input type="text" name="employee" required/>
</label>
</td>
</tr>
... and for all removable rows to ...
<tr>
<td>
<label>
<i class="fas fa-minus-circle remove_button"></i>
<input type="text" name="employee" required/>
</label>
</td>
</tr>
Looking into the above two code blocks one also might notice the class-name changes of 'add_button' and 'remove_button' to where both really belong to ... each to its iconized add/remove element.
Thus, the only necessary JavaScript/jQuery code change needs to take place within the remove handler. Since the OP already takes advantage of event delegation, one just has to access the event object's target reference. From there one queries the closest </tr> element which then gets removed.
Prove ...
$(document).ready(function () {
// Input fields increment limitation
var maxField = 3;
// Add button selector
var addButton = $('.add_button');
// Input field wrapper
var emp = $('#employee_tbl');
// New input field html
var fieldHTML = `
<tr>
<td>
<label>
<i class="fas fa-minus-circle remove_button"></i>
<input type="text" name="employee" required/>
</label>
</td>
</tr>`;
// Initial field counter is 1
var x = 1;
// Once add button is clicked
$(addButton).click(function () {
// Check maximum number of input fields
if (x < maxField) {
// Increment field counter
x++;
// Add field html
$(emp).append(fieldHTML);
}
});
// Once remove button is clicked
$(emp).on('click', '.remove_button', function (evt) {
evt.preventDefault();
// Remove field html
$(evt.target).closest('tr').remove();
// Decrement field counter
x--;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<table id="employee_tbl">
<tr>
<th>
<b><span data-i18n-key="employee">Employee</span></b>
</th>
</tr>
<tr>
<td>
<label>
<i class="fas fa-plus-circle add_button"></i>
<input type="text" name="employee" required/>
</label>
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How to execute JS when page load instead of event trigger?

I'm trying to come up with a JS that detects number of empty fields in my form. I have 3 fields. If JS counted 2 or more empty fields, JS will change the css color to red. If JS counted 1 empty field, JS will change the css color to green. This works fine when i enter data into the input field. However, when i load the page with data already inside the two fields, the color still remain red. How can make the JS check if there already values in the input box and switch color accordingly based on number of empty fields when the page is loaded?
Below is when the page is loaded but showing red even though there are only 1 empty field.
I have checked all forums but no answer to my problem
'''HTML'''
<table>
<tr></tr><td> Field 1: <input class="user_field" type="text" name="1[user_fname]" value="1" autofocus/></td></tr>
<tr><td>Field 2: <input class="user_field" type="text" name="1[user_lname]" value="2"/></td></tr>
<tr><td>Field 3: <input class="user_field phone" type="text" name="1[user_mobile]"/></td></tr>
<tr><td> </td></tr>
</table>
<div id="result"></div>
<div class="containerbox">
<div id="centerbox1" style="background-color: #FF6C60;">
<div class="value">
<p><span style="color: #fff ;font-weight:bold; font-size:36px">test</span></p>
</div>
</div>
</div>
</div>
'''JS'''
$(document).ready(function(){
$('.user_field').blur(function() {
var text = "field(s) empty";
var count = $('.user_field').not(function() {
return this.value;
}).length;
$('#result').html(count + " " + text);
//*alert(count);
var udata = count;
if (udata > 2){
document.getElementById("centerbox1").style.backgroundColor = '#FF6C60';
}
else
if (udata <= 2)
{
document.getElementById("centerbox1").style.backgroundColor = '#99C262';
}
});
});
I expected the background color to be green as there are 2 data in the fields when the page is loaded but the page shows color red.
Move the function out of the blur event handler, and call it from the ready() handler:
$(document).ready(function() {
// Function of its own
function checkFields() {
var text = "field(s) empty";
var count = $('.user_field').not(function() {
return this.value;
}).length;
$('#result').html(count + " " + text);
//*alert(count);
var udata = count;
$('#centerbox1').css('background-color', udata > 2 ? '#FF6C60' : '#99C262');
}
// Set up event handler
$('.user_field').blur(checkFields);
// Call function
checkFields();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr></tr>
<td> Field 1: <input class="user_field" type="text" name="1[user_fname]" value="1" autofocus/></td>
</tr>
<tr>
<td>Field 2: <input class="user_field" type="text" name="1[user_lname]" value="2" /></td>
</tr>
<tr>
<td>Field 3: <input class="user_field phone" type="text" name="1[user_mobile]" /></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
<div id="result"></div>
<div class="containerbox">
<div id="centerbox1" style="background-color: #FF6C60;">
<div class="value">
<p><span style="color: #fff ;font-weight:bold; font-size:36px">test</span></p>
</div>
</div>
</div>
</div>

Adding new input using Jquery breaks tooltips

I'm writing a form and I have to let the user add as many rows as required.
As you can see, my inputs are treated as arrays to later save the data to the DB. (That will be another new thing to me)
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<tr> <td><input type="text" id="NombreProyecto" name="NombreProyecto[]"></td> <td><input type="text" id="Descripcion" name="Descripcion[]"></td> <td><input type="text" id="AplicacionesProyecto" name="AplicacionesProyecto[]"></td> <td style="width: auto"> <div class="range-field "> <input type="range" name="NivelTRL[]" min="1" value="1" max="9" /> </div> </td> </tr>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="step-content">
<div class="container">
<div id="table" class="table-editable ">
<table class="table field_wrapper">
<tr>
<th>Nombre</th>
<th>Descripción</th>
<th>Aplicaciones</th>
<th>Nivel TRL</th>
<th><i class="material-icons">add</i>
</th>
</tr>
<tr class="">
<td><input type="text" id="NombreProyecto" name="NombreProyecto[]"></td>
<td><input type="text" id="Descripcion" name="Descripcion[]"></td>
<td><input type="text" id="AplicacionesProyecto" name="AplicacionesProyecto[]"></td>
<td>
<div class="range-field">
<input type="range" name="NivelTRL[]" min="1" value="1" max="9" />
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
Everything looks perfect but when the user adds a new row and interacts with the range input, this won't feedback the user about the value he/she is picking.
Just the original one will have the tooltip.
After some testing, it even affects the 'tooltipped' class used to, well, show tooltips over any element.
This is the codepen, It's all ready to show you the problem
How to reproduce it:
In the codepen provided, you will see the blue cross, when you click on it a new row will be added.
Play around with the first range input, it will show you the value on the tooltip.
In the later added range input, it wont.
Thank you for reading, have a nice day.
You should reinit your range elements.
Simply add this code
M.Range.init($('input[type=range]'));
after this
$(wrapper).append(fieldHTML); //Add field html
First, it's not a tooltip on that range input... It's the Materialize nouiSlider effect. So you have to initialyse this on the new element.
M.Range.init(element);
By the way, I did not found this specific is the documentation about range... But I got inspired by this other initialisation example.
CodePen updated

How to clear Input data from within JQuery Div

I have a simple form users can fill out and also add a new form to add multiple entries.
Everything works fine except when I enter data in the first set of inputs and click create new memberships it will take the data from the form and put it in the text boxes.
How can I stop that?
http://jsfiddle.net/811yohpn/2/
I have tried a couple different ways.
$('#education').find('input:text').val('');
$('#education: input').val('');
However that will clear all entries.
Call find on the newDiv, instead of all inputs within #education.
Updated fiddle
newDiv.find('input:text').val('');
var ed = 1;
function new_education() {
ed++;
var newDiv = $('#education div:first').clone();
newDiv.attr('id', ed);
var delLink = '<a class="btn btn-danger" style="text-align:right;margin-right:65px" href="javascript:deled(' + ed + ')" > Delete Education ' + ed + ' </a>';
newDiv.find('tr:first th').text('Education ' + ed);
newDiv.append(delLink);
newDiv.find('input:text').val(''); // <----------- added this
$('#education').append(newDiv);
}
function deled(eleId) {
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('education');
parentEle.removeChild(ele);
//ed--;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<legend>Education</legend>
<div id="education">
<div id="1">
<table border=3>
<tr>
<th colspan="4" style="background-color:#b0c4de;">Education 1</th>
</tr>
<tr>
<td>
<label>School Name</label>
<input type="text" name="schoolname[]" maxlength="30" size="30"/>
</td>
<td>
<label>Degree Type</label>
<input type="text" name="degreetye[]" maxlength="30" size="30"/>
</td>
<td>
<label>Degree Field</label>
<input type="text" name="degreefield[]" maxlength="30" size="30"/>
</td>
</tr>
</table>
</div>
</div>
<br/><a class="js-addNew btn btn-info" href="javascript:new_education()"> Add New Education </a>
You need to clear the inputs under the cloned element
newDiv.find('input').val('')
Demo: Fiddle
Your selectors are selecting all input elements within the #education container, that is not what you want. The newDiv variable refers to the newly created element so you can use that to find the input elements within in and then clear it

How can I automatically generate a new input field when a certain input field is navigated to?

Inspired by the Chrome Postman extension, I want to implement a multi-field form section by automatically adding a new input field when a certain field is navigated to, and give focus to the new field. The below screenshot shows how this works in Postman; the down-most row contains a couple of inputs that, when navigated to, results in a new row being added above it, which can be typed into.
How can I achieve this behaviour in JavaScript/jQuery? To simplify matters, I need only one input field per row. I've created a fiddle that should serve as a starting point for a solution.
Example HTML:
<div id="last-row">
<input name="multifield" placeholder="Value"></input>
</div>
​
See how I'd do it: http://jsfiddle.net/jCMc8/8/
html:
<section>
<div id="initRow">
<input name="multifield" placeholder="Value">
</div>
</section>​
javascript:
function addRow(section, initRow) {
var newRow = initRow.clone().removeAttr('id').addClass('new').insertBefore(initRow),
deleteRow = $('<a class="rowDelete"><img src="http://i.imgur.com/ZSoHl.png"></a>');
newRow
.append(deleteRow)
.on('click', 'a.rowDelete', function() {
removeRow(newRow);
})
.slideDown(300, function() {
$(this)
.find('input').focus();
})
}
function removeRow(newRow) {
newRow
.slideUp(200, function() {
$(this)
.next('div:not(#initRow)')
.find('input').focus()
.end()
.end()
.remove();
});
}
$(function () {
var initRow = $('#initRow'),
section = initRow.parent('section');
initRow.on('focus', 'input', function() {
addRow(section, initRow);
});
});
​
​
This is how I would do it.
HTML:
<table>
<tbody>
<tr class="item">
<td><input name="multifield" placeholder="Value" /></td>
<td><i class="icon delete"></i></td>
</tr>
<tr class="item inactive">
<td><input name="multifield" placeholder="Value" /></td>
<td><i class="icon delete"></i></td>
</tr>
</tbody>
</table>
JavaScript:
$("table")
.on("click focus", ".item.inactive", function(e) {
var curRow = $(this);
curRow.clone().appendTo("table tbody");
curRow.removeClass("inactive").find("input:first").focus();
})
.on("click", ".icon.delete", function(e) {
$(this).closest("tr").remove();
});
See test case on jsFiddle.
I have come up with a solution that seems to work so far, but I'm interested in hearing from others as to whether it is a good one. What I do is catch the focus event for the last input field, add a new row and give focus to the input field within that row. See this fiddle for working code.
HTML:
<div id="last-row">
<input name="multifield" placeholder="Value">
</div>
JavaScript:
var lastRow = $('#last-row');
var lastInput = lastRow.find('input');
function addRow() {
var newRow = $('<div><input name="multifield" placeholder="Value"><a class="row-delete"><img src="http://i.imgur.com/ZSoHl.png" /></a></div>');
var newInput = newRow.find('input');
lastRow.before(newRow);
newInput.focus();
var newDelete = newRow.find('a');
newDelete.click(function() {
newRow.remove();
});
}
lastInput.focus(function() {
addRow();
});

Javascript Add button after field and get value on click

I have a pre compiled form which i need to insert a button into after a specific field with and ID of addr_postcode can any one show me how to, using javascript, add a button after the field which when clicked takes the value of the field and launches a new window with the value as part of the url. for example:
../DIR/default.aspx?postcode=postcode here
Thanks a nice simple one I hope!
HTML
<TR>
<TD vAlign=top>
<SPAN id=_Captaddr_postcode class=VIEWBOXCAPTION>Post Code:</SPAN>
<BR>
<SPAN id=_Dataaddr_postcode class=VIEWBOX>
<INPUT id=addr_postcode class=EDIT name=addr_postcode maxLength=10 value=test size=15><INPUT name=_HIDDENaddr_postcode type=hidden>
</SPAN>
</TD>
</TR>
Try this:
function makeButton() {
var buttonDiv = document.getElementById("addr_postcode");
var Button = document.createElement("input");
Button.setAttribute("type", "button");
Button.setAttribute("id", "ButtonClick");
Button.setAttribute("value", "New button");
Button.setAttribute("onclick", "btnClick(" + buttonDiv.value.toString() + ");");
buttonDiv.appendChild(Button);
}
btnClick(URL) {
window.open(URL,'','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}

Categories