adding and removing multiple form field - javascript

Hi I am sharing my code below. Can anyone help me for small changes.While creating new box the add button is at fixed position.I need make it dynamic.
$(document).ready(
function () {
var max_fields = 6;
var wrapper = $(".items");
var add_button = $(".add-more");
var x = 1;
$(add_button)
.click(
function (e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper)
.append(
'<div class="row add-more1"><div class="col-sm-11"><div class="col-sm-4"><form role="form"><div class="form-group">'
+ '<select class="full-width form-control"><option value="AK">- Select -</option><option value="AK">Name</option>'
+ '<option value="HI">Email</option><option value="AK">Contact No.</option><option value="HI">Assigned To</option>'
+ '<option value="AK">Next Action From</option><option value="HI">Next Action To</option><option value="AK">Status</option></select>'
+ '</div></form></div>'
+ '<div class="col-sm-4"><form role="form"><div class="form-group">'
+ '<select class="full-width form-control"><option value="AK">- Select -</option><option value="AK">=</option>'
+ '<option value="HI">></option><option value="AK">>=</option><option value="HI"><</option><option value="AK"><=</option>'
+ '<option value="HI">like</option></select>'
+ '</div></form></div>'
+ '<div class="col-sm-4"><form role="form"><div class="form-group">'
+ '<input type="text" class="form-control input-sm" name="name" placeholder="Enter value"/>'
+ '</div></form></div></div>'
+ '<span class="remove_field"><i class="fa fa-times"></i></span></div>');
}
});
$(wrapper).on("click", ".remove_field",
function (e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});

please add css maybe its work :
.remove_field{
position: absolute;
right: 0;
}

Related

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

JavaScript class did not function in asp.net

I have created a javascript function in my aspx page..
below are the sample code,
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
</script>
I would like this function execute in the property such as
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>
As the code running, the javascript function above should be executed and display the " Choose Year" propery inside as shown above.
I try to run this code but nothing happens to the property. Any help would be appreciated. Thank u.
Your code seems to be working as below. However you may be missing the jQuery script so you can check if that exists.
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>

How to disable value in select option when it already selected by another select option

So, i have a simple form like this:
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
<script type="text/javascript">
var count = 0;
$(function(){
$('#add_field').click(function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv"><?php $noInv = $this->modelku->select_inv() ?> <?php foreach($noInv->result() as $inv){ ?> <option value="<?php echo $inv->no_inv ?>"><?php echo $inv->no_inv ?></option><?php } ?></select><br>' );
});
});
</script>
</div>
When i click the button the field will regenerate select option, and the value is from database
select_inv function:
public function select_inv()
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where("kondisi = 'Ada' ");
$query = $this->db->get();
return $query;
}
My Question: How can i disable value in select option when it already selected by another select option?
Try this if this is what you need.
i just created a sample dropdown and in my jquery i trigger the event change using the class of all select option then i will get the value of the select and id. after getting the value i check the val if it is empty or not if not empty then i will use the each function for all the select and get their id attribute so i can compare it with the id of the select and if their id is not the same then i will disabled the option with the same value of the selected dropdown.
and i use focus event for getting the previous value so i can reset whether the user change the value of the selected option.
$( document ).ready(function() {
$('body').on('click','#add_field',function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv select_alternate"> <option value="">select</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select><br></select><br>' );
});
var count =0;
var previous;
var selectedData = [];
$('body').on('click','.select_alternate',function(){
previous = this.value;
});
$('body').on('change','.select_alternate',function(){
var val = this.value;
var id = $(this).attr('id');
if(val != ''){
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + val + '"]').prop('disabled',true);
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
selectedData.splice($.inArray(val, selectedData),1);
}else{
selectedData.push(val);
}
});
}else{
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
</div>

How can I set up a button handler to remove a parent table row?

I have this HTML & jQuery project, and everything currently works perfectly for what I want them to do. What I need right now is to add a Delete/Remove Button that is linked to this line:
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
As you can see the buttons are visible only if you click the add button and create a new TR with values.
I tried creating a jQuery function:
function removeThis(a) {
$('tr-' + 'a').remove();
}
But of course, it's not doing what I need it to do.
Can anyone help me resolving this?
Thanks in advance.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
$('tr-' + 'a').remove();
}
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >
I don't want any of the other functions to be deleted.
BTW the Delete button is already added with ID removeThis.
Thank you very much in advance.
You can achieve this without jQuery at all, and I highly recommend that.
function removeThis(e){
const parentTd = e.parentNode;
const parentTr = parentTd.parentNode;
const parentTable = parentTr.parentNode;
return parentTable.removeChild(parentTr);
}
And on your button you do
<button onClick='removeThis(this)'>Delete me</button>
This way you create a testable and reusable function that you can use to remove all DOM Elements.
Oh, and by the way, this way you work from inside-out rather than querying the whole document for the element intended to remove.
Your example function below builds a string 'tr-' + 'a' which will always just look for "tr-a":
function removeThis(a) {
$('tr-' + 'a').remove();
}
Just remove the quotes from around 'a':
function removeThis(a) {
$('tr-' + a).remove();
}
Remove the quotes around the letter 'a' so you can use the variable there:
function removeThis(a) {
$('.tr-' + a).remove();
}
You should also consider using a different way to number the table rows. The row numbers will start to get reused if you delete a row and then add a new one:
Row 0, Row 1, Row 2, Row 3, Row 4
Add row. There are 5 rows, so the new row is row 5.
Row 0, Row 1, Row 2, Row 3, Row 4, Row 5
Remove row 1.
Row 0, Row 2, Row 3, Row 4, Row 5
Add row. There are 5 (!!!) rows, so the new row is (also!!!) row 5.
Row 0, Row 2, Row 3, Row 4, Row 5, Row 5
Instead of getting a new value for tr every time you add a row, instead consider a global variable that you increment every time you add a row:
var rowCounter = 0;
function addNewTr() {
//snip
rowCounter++;
$('table tbody').append('' +
'<tr class="tr-' + rowCounter + '">' +
//snip
}
I think you just need to remove the quotes from 'a':
function removeThis(a) {
$('.tr-' + a).remove();
}
EDIT: This snippet is totally working! I did need to add a dot before 'tr' since it is a class.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
alert('.tr-'+a);
$('.tr-' + a).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >

How to do client side validations if some text boxes are generated dynamically

I'm working on a form which has this add button, if the button is clicked a text box is foing to generate and i have a minus button to cancel it.
my problem is i have to work on client side validations in this page
the code i used to generate new text boxes is
i = 0;
var counter = 2;
$("#addButton").click(function () {
optionCount++;
i++;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv'+i);
newTextBoxDiv.after().html('<label>Option : </label>' +
'<input type="text" class="add_input" name="textbox' + counter + '" id="textbox' + counter + '" > <input type="button" class="rem_img minusclick" id="removeButton'+i+'" alt="Remove" title="Remove" onclick="RemoveButton(\''+i+'\',\''+counter+'\')">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
optionIds.push(counter);
counter++;
The validation is to be done after clicking the submit button. and i need to display an error message beside each empty text box(that is generated by clicking add button)
im confused where to start and what exactly i have to do for this
Please help..
I add onchange method textbox;
i = 0;
var counter = 2;
$("#addButton").click(function () {
optionCount++;
i++;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv'+i);
newTextBoxDiv.after().html('<label>Option : </label>' +
'<input type="text" onchange="Validate(this,\"ValueControl\")" class="add_input" name="textbox' + counter + '" id="textbox' + counter + '" > <input type="button" class="rem_img minusclick" id="removeButton'+i+'" alt="Remove" title="Remove" onclick="RemoveButton(\''+i+'\',\''+counter+'\')">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
optionIds.push(counter);
counter++;
Create This function;
function Validate(elementObject,validType){
if(validType=="ValueControl"){
if($(elementObject).val()==''){
$(elementObject).css("background-color","#000000");
}
}
}

Categories

Resources