Clearing an input field on blur - javascript

I'm attempting to clear all inputs with the class "new" on blur, but for some reason it just won't work. I've bashed my head at the this for three hours now, which obvious point am I missing? Relevant code below.
UPDATE 2
I tried changing out the switch-case block with corresponding if blocks, and they give the expected result. This eliminates the current problem, but I don't find it to be a viable answer to the original question which is why my origianl code with switch-case doesn't work.
UPDATE 1
After some research and experimenting I've discovered that I can clear all inputs with the class "new" as long as they're not inside my switch-case block. The selector I'm testing with is $('.new'), once inside the switch-case block this gives no visible effect.
#{
ViewBag.Title = "Viser infrastruktur";
Layout = "~/Views/Shared/_SuperOfficeLayout.cshtml";
}
<table class="table table-striped compact hover row-border">
<thead>
<tr>
<th>Produsent</th>
<th>Modell</th>
<th>Serienummer</th>
<th>Firmware</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="manufacturer" placeholder="Produsent" value="" />
<input type="hidden" class="autosave new" name="id" value="" />
<input type="hidden" class="autosave new" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="model" placeholder="Modell" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="serialNumber" placeholder="Serienummer" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="firmware" placeholder="Firmware" />
</div>
</td>
</tr>
#foreach (var infrastructure in Model.Infrastructures)
{
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="manufacturer" placeholder="Produsent" value="#infrastructure.Manufacturer" />
<input type="hidden" class="autosave" name="id" value="#infrastructure.Id" />
<input type="hidden" class="autosave" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="model" placeholder="Modell" value="#infrastructure.Model" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="serialNumber" placeholder="Serienummer" value="#infrastructure.SerialNumber" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="firmware" placeholder="Firmware" value="#infrastructure.Firmware" />
</div>
</td>
</tr>
}
</tbody>
#section SpecializedScripts
{
<script type="text/javascript">
function saveSettings(element, ajaxUrl, ajaxType) {
var fields = $(element).closest('tr').children('td').children('div').children('.autosave');
var abort = false;
var ajaxData = {};
$(fields).each(function () {
abort = ($(this).val() == '' || $(this).val() == null);
backgroundColor = abort == true ? '#d9534f' : '#f9f598';
$(this).css('background-color', backgroundColor).css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
ajaxData[$(this).prop('name')] = $(this).val();
});
if (abort == true) {
return false;
}
$.ajax({
url: ajaxUrl,
type: ajaxType,
data: ajaxData
}).success(function (data, textStatus, jqXHR) {
$(fields).each(function() {
$(this).css('background-color', '#5cb85c').css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
});
switch(data.status)
{
case 'Deleted':
$(element).closest('tr').remove();
break;
case 'Added':
var tableBody = $('tbody');
var html = '<tr>';
for (var field in data.result) {
if (field == 'id' || field == 'superOfficeCustomerId')
{
html += '<input type="hidden" class="autosave" name="' + field + '" value="' + data.result[field] + '" />';
}
else {
html += '<td>'
+ '<div class="control-group">'
+ '<input type="text" class="col-md-12 autosave form-control" name="' + field + '" value="' + data.result[field] + '" />'
+ '</div>'
+ '</td>';
$('input.new[name=' + field + ']').val('');
}
}
html += '</tr>';
$(tableBody).append(html);
case 'Modified':
$(fields).each(function () {
$(this).val(data.result[$(this).prop('name')]);
});
break;
}
}).fail(function () {
});
}
$(document).on('blur', 'input.autosave', function () {
saveSettings($(this), '/Link/SaveInfrastructure', 'POST');
});
$(document).on('change', 'input.new', function () {
});
</script>
}

Something like this should work:
$('input.new').on('blur', function() { $(this).val(''); $(this).text(''); });
just make sure the input exists when you bind the event otherwise you can do:
$(document).on('blur', 'input.new', function() { $(this).val(''); $(this).text(''); });

For vanilla JavaScript, you can use
<input onBlur={(event) => { event.target.value = ''; }} />

Related

Prevent form submission by checking every dynamically created text boxes are empty

Here I am trying to check each and every dynamically created textboxes whether it is empty or not before the form submission.
Here is the HTML code,
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Here is the Ajax code
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
swal({
title: "Are you sure?",
text: "You wanna proceed this Payment!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-success",
confirmButtonText: "Yes, Proceed It!",
closeOnConfirm: false
},
function(isConfirm){
if (!isConfirm) return;
$.ajax({
url: "testquery/test_payments.php", // Url to which the request is send
method: "POST", // Type of request to be send, called as method
data: {
'test_id': test_id,
'amount': amount,
'p_id': p_id,
'pres_id': pres_id,
'description':description
},
success: function (data) {
if (data == 'Password Changed') {
swal("Success", "Invoice has been Generated :)", "success");
} else {
swal("Sorry", "Something Went Wrong. Please try again later:(", "error");
}
},
error: function (data) {
//other errors that we didn't handle
swal("Sorry", "Failed to Proceed. Please try later :(", "error");
}
});
});
};
// check validations
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
if (!$("#test_id").val()) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
});
I want to check the test_id textbox is empty. Before dynamically generating the textboxes there, already there is a row of textboxes including test_id textbox. My problem is, before generated, it check the textbox as empty or not by using function, but after generated it does not check. I don't know where I went wrong.
Please help me may highly appreciated.
Rather than using the elementID use class name to get the collection of elements and iterate through them. the problem we have here is all input have the same id so jquery will return the first element it finds and ignore the rest since with ID we assume that it is unique throughout the DOM
function checkname(el){
}
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
debugger;
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
alert('invoice generated')
};
// check validations
function validateContact() {
debugger;
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
//list of test_id inputs
var testIdList =
document.getElementsByClassName('test_id')
for(let i= 0 ; i<testIdList.length; i++){
if (!testIdList.item(i).value) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
}
return valid;
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Use class, name or other attributes instead id, because you have a several elements with the same ids - it's always create problems. If you need check inputs with class "text_id" before submit try to change validation function
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
$('.text_id').map(function(i, el){
if(!$(el).val() || $(el).val().trim() == '') {
valid = false;
$("#test_id_info").html("(Required)");
$(el).css('background-color', '#FFFFDF');
}
});
return valid;
}

Keyup not working for dynamically added input-groups

I have already gone through questions available on this topic and have tried everything, but still my keyup function is not working.
$(document).ready(function() {
$(document).on('keyup', '.pollOption', function() {
var empty = false;
$(".pollOption").each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$("#cpsubmit").attr('disabled', 'disabled');
$("#moreop").attr('disabled', 'disabled');
} else {
$("#cpsubmit").removeAttr('disabled');
$("#moreop").removeAttr('disabled');
}
});
//Keep Track of no. of options on the page
var noOfOptions = 2;
// Function to add input fields (since I may have to delete them I've use bootstrap's input-groups, I guess this is causing issue)
$("#moreop").on('click', function() {
noOfOptions++;
$("#options").append("<div class='input-group pollOption'><input class='form-control' type='text' placeholder='New Option' name='op" + noOfOptions + "'/><span class='input-group-addon'><a href='#' id='removeOption' class='text-danger'>Remove</a></span></div>");
});
// To delete any option (only the dynamically created options can be deleted)
$("#cpform").on('click', '#removeOption', function() {
$(this).parents('.input-group').remove();
noOfOptions--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cpform" method="POST" action="/polls/add">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" placeholder="Ask your question here..." name="title" class="form-control" />
</div>
<div id="options" class="form-group">
<label>Options</label>
<input type="text" placeholder="Option 1" name="op1" class="form-control pollOption" />
<input type="text" placeholder="Option 2" name="op2" class="form-control pollOption" />
</div>
<button id="moreop" type="button" disabled="disabled" class="btn btn-outline-info btn-primary">More Options</button><br/><br/>
<button id="cpsubmit" type="submit" disabled="disabled" class="btn btn-info btn-primary">Submit</button>
</form>
This code works perfectly for the two inputs already in the HTML part.
When I click on the "More Option" button the new field gets added but the "keyup" does not work on it. In fact, when I enter something on the new added inputs then my "More Option" & "Submit" button gets disabled (really do't know why this is happening).
You've to add the class pollOption to the input and not the div in your append :
$("#options").append("<div class='input-group'><input class='pollOption form-control' ...
_____________________________________________________________^^^^^^^^^^
Instead of :
$("#options").append("<div class='input-group pollOption'><input class='form-control' ...
______________________________________________^^^^^^^^^^
Demo:
$(document).ready(function() {
$(document).on('keyup', '.pollOption', function() {
var empty = false;
$(".pollOption").each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$("#cpsubmit").attr('disabled', 'disabled');
$("#moreop").attr('disabled', 'disabled');
} else {
$("#cpsubmit").removeAttr('disabled');
$("#moreop").removeAttr('disabled');
}
});
//Keep Track of no. of options on the page
var noOfOptions = 2;
// Function to add input fields (since I may have to delete them I've use bootstrap's input-groups, I guess this is causing issue)
$("#moreop").on('click', function() {
noOfOptions++;
$("#options").append("<div class='input-group'><input class='pollOption form-control' type='text' placeholder='New Option' name='op" + noOfOptions + "'/><span class='input-group-addon'><a href='#' id='removeOption' class='text-danger'>Remove</a></span></div>");
$(this).attr('disabled','disaled');
});
// To delete any option (only the dynamically created options can be deleted)
$("#cpform").on('click', '#removeOption', function() {
$(this).parents('.input-group').remove();
noOfOptions--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cpform" method="POST" action="/polls/add">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" placeholder="Ask your question here..." name="title" class="form-control" />
</div>
<div id="options" class="form-group">
<label>Options</label>
<input type="text" placeholder="Option 1" name="op1" class="form-control pollOption" />
<input type="text" placeholder="Option 2" name="op2" class="form-control pollOption" />
</div>
<button id="moreop" type="button" disabled="disabled" class="btn btn-outline-info btn-primary">More Options</button><br/><br/>
<button id="cpsubmit" type="submit" disabled="disabled" class="btn btn-info btn-primary">Submit</button>
</form>

Dynamically add dropdown box in laravel. Javascript and laravel

I want to add dynamic dropdown & textbox. But for textbox is ok. I am not ok in dropdown. The Data are not include in Dropdown.I am loop to retrieve data in blade.I am describe my code.
form.blade.php
<div class="form-group">
<label for="type">Gas Container Type</label>
<select class="form-control input-sm" name="gas" id="gas">
#foreach($gass as $gas)
<option value="{{$gas->name}}">{{$gas->name}}</option>
#endforeach
</select><!-- end of Item_Drop_Down -->
</div>
<input name="name[]" type="text" id="name" class="name" placeholder="Input 1">
Add More Input Field
master.blade.php
<script>
$(document).ready(function () {
var e = document.getElementById("gas");
$('#add').click(function () {
var inp = $('#box');
var i = $('input').size() + 1;
$('<div id="box' + i + '">' + '' +
'<input type="text" id="name" class="name" name="name[]" placeholder="Input ' + i + '"/>' + '' +
'<select id="gas" name="gas[]" ' + i + '"/><img src="remove.png" width="32" height="32" border="0" align="top" class="add" id="remove" /> </div>')
.appendTo($('#box form'));
i++;
});
{{--<select data-bind="options: availableCountries, optionsText: 'name', optionsValue: 'value'"></select>--}}
$('body').on('click', '#remove', function () {
$(this).parent('div').remove();
});
});
controller.php
public function store(Request $request)
{
foreach ($request->get('name') as $name) {
$kg = new WarehouseGasIn();
$kg->kg = $name;
//dd($request->get('name'));
$kg->save();
}
<script>
$(document).ready(function () {
$('#add').click(function () {
var inp = $('#box');
var i = $('input').size() + 1 - 2;
$('<div id=box' + i + '"><input type="text" id="name" class="name" name="name[0][]" placeholder="Input ' + i + '"/><select class="form-control input-sm" name="shop" id="shop"><option value="">{{"Shop"}}</option>#foreach($branches as $branch)<option value="{{$branch->id}}">{{$branch->name}}</option>#endforeach</select><select name="name[1][]" id="gas" ' + i + '>#foreach($gass as $gas) <option value="{{$gas->id}}">{{$gas->name}}</option>#endforeach</select><img src="remove.png" width="32" height="32" border="0" align="top" class="add" id="remove" /> </div>').appendTo($('#box form'));
i++;
});
$('body').on('click', '#remove', function () {
$(this).parent('div').remove();
});
});
</script>
is this the sort of thing you are trying to achieve?
$(document).ready(function () {
var boxesWrap = $('#boxes-wrap');
var boxRow = boxesWrap.children(":first");
var boxRowTemplate = boxRow.clone();
boxRow.find('button.remove-gas-row').remove();
// nb can't use .length for inputCount as we are dynamically removing from middle of collection
var inputCount = 1;
$('#add').click(function () {
var newRow = boxRowTemplate.clone();
inputCount++;
newRow.find('input.name').attr('placeholder', 'Input '+inputCount);
boxesWrap.append(newRow);
});
$('#boxes-wrap').on('click', 'button.remove-gas-row', function () {
$(this).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes-wrap">
<div>
<div class="form-group">
<label>Gas Container Type</label>
<select class="form-control input-sm" name="gas[]">
<option value="gas-1">Container 1</option>
<option value="gas-2">Container 2</option>
</select><!-- end of Item_Drop_Down -->
</div>
<input name="name[]" type="text" class="name" placeholder="Input 1">
<button class="remove-gas-row" type="button">Remove</button>
</div>
</div>
Add More Input Field

Repopulate form input after delete another field

Good day, i have this section of javascript that's causing me trouble
https://jsfiddle.net/o5x8qgvt/2/
When i add a new field the position gets incremented when i delete a field the position is repopulated but on product name it doesn't repopulate the fields it gives me blank even if i added data in each of them. Can you please help me out?
Javascript:
// setup an "add a tag" link
var $addTagLink = $('<button href="#" class="btn btn-info add_tag_link">Adauga Produs</button>');
$('.form-buttons > .btn-group').prepend($addTagLink);
var $newLinkLi = $('.append-me');
jQuery(document).ready(function() {
// Get the ul that holds the collection of product-group
var $collectionHolder = $('#products-group');
// add the "add a tag" anchor and li to the product-group ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see code block below)
addTagForm($collectionHolder, $newLinkLi);
typeInitialize();
});
});
function regenerateTagList() {
var vals = $('.product-group > .product-counter > input').toArray().map(function(v, i) {return v.value;});
var products = $('.product-group > .product-name > span > input:last').toArray().map(function(v, i) {return v.value;});
console.log(products);
$('.product-group').remove();
$('#products-group').data('index', 1);
for (var i = 0; i < vals.length; i++) {
if (vals[i] !== i + 1) {
vals[i] = i + 1;
}
addTagForm($('#products-group'), $newLinkLi);
typeInitialize();
$('.product-group > .product-counter > input:last').val(vals[i]);
$('.product-group > .product-name > span > input:last').val(products[i]);
}
}
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
if (index === 0) {
index = 1;
}
// Replace '$$name$$' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<tr class="product-group"></tr>').append(newForm);
// also add a remove button, just for this example
//$('<button type="button" class="product-highlight btn btn-primary">Highlight</button>
// <button type="button" class="remove-tag btn btn-primary">Sterge</button>').appendTo($newFormLi);
$newLinkLi.append($newFormLi);
// handle the removal, just for this example
$('.remove-tag').click(function(e) {
e.preventDefault();
$(this).closest('tr').remove();
regenerateTagList();
return false;
});
$('.product-highlight').on('click', function(e) {
e.preventDefault();
$(this).closest('tr').toggleClass('toggle-highlight');;
});
}
// Initialize Typeahead
function typeInitialize() {
// Create typeahead instance
var url = Routing.generate('offer_ajax_search', {
name: 'WILDCARD'
});
// Trigger typeahead + bloodhound
var products = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
console.log('fired');
return obj.u_name;
},
prefetch: '/export/json/products.json',
remote: {
url: url,
wildcard: 'WILDCARD',
}
});
products.initialize();
$('.product-group').find('.typeahead:last').typeahead({
minLength: 3,
highlight: true,
limit: 10,
}, {
name: 'product',
display: 'u_name',
source: products.ttAdapter()
}).on('typeahead:select', function(e, datum) {
e.preventDefault();
/* Act on the event */
var information = '<div class="col-md-2"><label for="boxCode" class="label-control">BEX Code</label><input class="form-control" type="text" disabled="true" value="' + datum.u_bexCode + '"/></div>';
information += '<div class="col-md-2"><label for="base-price">Pret de baza</label><input class="form-control " type="text" disabled="true" value="' + datum.u_image + '"/></div>';
var div = $(this).parent().closest('.form-group').find('.product-information');
$(div).empty().append(information);
}).on('typeahead:autocomplete', function(e, datum) {
e.preventDefault();
/* Act on the event */
var information = '<div class="col-md-2"><label for="boxCode" class="label-control">BEX Code</label><input class="form-control" type="text" disabled="true" value="' + datum.u_bexCode + '"/></div>';
information += '<div class="col-md-2"><label for="base-price">Pret de baza</label><input class="form-control " type="text" disabled="true" value="' + datum.u_image + '"/></div>';
var div = $(this).parent().closest('.form-group').find('.product-information');
$(div).empty().append(information);
});
$("input[type='text']").on("click", function() {
$(this).select();
});
}
HTML:
<div class="row">
<div class="col-md-12">
<form name="offer" method="post" action="/app_dev.php/offer-generator/new/submited" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label required" for="offer_name">Name</label><div class="col-sm-10"><input type="text" id="offer_name" name="offer[name]" required="required" maxlength="255" class="form-control"></div>
</div>
<div id="products-group" data-prototype="<td class="product-counter col-md-1"><input type="text" id="offer_products___name___position" name="offer[products][__name__][position]" disabled="disabled" required="required" class="counter form-control" value="__name__" /></td>
<td class="product-name"><input type="text" id="offer_products___name___name" name="offer[products][__name__][name]" required="required" class="typeahead product form-control" name="product" id="products" data-provider="product" placeholder="Nume Produs" autocomplete="false" /></td>
<td class="col-md-1"><input type="text" id="offer_products___name___price" name="offer[products][__name__][price]" required="required" class="form-control" /></td>
<td class="col-md-1"><input type="text" id="offer_products___name___quantity" name="offer[products][__name__][quantity]" required="required" class="form-control" /></td>
<td class="product-action">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="product-highlight btn btn-warning">Highlight</button>
<button type="button" class="remove-tag btn btn-danger">delete</button>
</div>
</td>
"><table class="table table-striped table-hover table-bordered append-me">
<thead>
<tr>
<th class="col-md-1">Position</th>
<th>Product</th>
<th class="col-md-1">Price</th>
<th class="col-md-1">Quantity</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table></div>
</form></div>
<div class="form-buttons">
<div class="btn-group" role="group" aria-label="..."><button href="#" class="btn btn-info add_tag_link">Add Product</button>
<button type="submit" id="offer_save" name="offer[save]" class="btn-default btn">Create Offer</button>
<button type="submit" id="offer_send_email" name="offer[send_email]" class="btn-default btn">Send Email</button>
<button type="submit" id="offer_export_excel" name="offer[export_excel]" class="btn-default btn">Export Excel</button>
<button type="submit" id="offer_export_pdf" name="offer[export_pdf]" class="btn-default btn">Export PDF</button>
</div>
</div>
<div class="form-group"><div class="col-sm-2"></div><div class="col-sm-10"><div id="offer_products" data-prototype="<div class="form-group"><label class="col-sm-2 control-label required">__name__label__</label><div class="col-sm-10"><div id="offer_products___name__"><div class="form-group"><label class="col-sm-2 control-label required" for="offer_products___name___pricePerLine">Line Total</label><div class="col-sm-10"><input type="text" id="offer_products___name___pricePerLine" name="offer[products][__name__][pricePerLine]" required="required" class="form-control" /></div>
</div></div></div>
</div>"></div></div>
</div><input type="hidden" id="offer__token" name="offer[_token]" class="form-control" value="cSVdt50kupA_BwFeY4T43PslnfjiA-UgjT4EA_HBdqs">
</div>

Cant remove the div which added runt time by appending another div in MVC view

I am developing ASP.NET MVC application.
I am adding the Div Run time by click event on View using Jquery.
After adding div , I am trying to remove it... but It cant get removed.
I have put alert box on the click function of remove link but that also not working.
here is my Complete Code....
<script type="text/javascript">
$(document).ready(function () {
$('.remove').click(function () {
alert("asd");
$(this).parent().parent().remove();
});
function getProductList(rIndex) {
//alert("In Product list");
var productList;
var mainList;
var productListArray = [];
$.ajax({
url: '#Url.Content("~/Product/GetProductList")',
success: function(data) {
mainList = data;
var options = '';
temp = 0;
for (var index = 0; index < data.length; index++) {
productListArray[index] = data[index].Id;
options += '<option value="' + data[index].Id + '">' + data[index].Name + '</option>';
}
productList = options;
$("select#ddProductList_" + rIndex).html(productList);
}
});
}
$('#lnkAddProduct').click(function () {
var rIndex = $("select.clsProductId").length;
// $('#ProductList').append("<div><span style='font-size:12px;'><select class='clsProductId' id='ddProductList_" + rIndex + "' name='ProductId' style = 'font-size:12px;width:120px;margin-right:10px;margin-left:0px;' /></span><input type='text' id='SectionCode' style='width:10%; margin-right:30px;'></div>");
$('#ProductList').append("<div><span style='font-size:12px;'><select class='clsProductId' name='ProductId' id='ddProductList_" + rIndex + "'name='ProductId' style = 'font-size:12px;width:150px;margin-right:10px;margin-left:0px;' /></span><input type='text' id='SectionCode' name='SectionCode' style='width:10%; margin-left:7px;'><input type='text' id='Size' name='Size' style='width:5%; margin-left:20px;'><input type='text' id='Length' name='Length' style='width:8%; margin-left:25px;'><input type='text' name='Thickness' id='Thickness' style='width:8%; margin-left:25px;'><input type='text' id='Weight' name='Weight' style='width:8%; margin-left:25px;'/><input type='text' id='Quantity' name='Quantity' style='width:8%; margin-left:30px;'/><span style='margin-left:10px;padding-top:6px;'> <a href='#' style='font-size:14px;text-decoration:none;font-weight:bold;' id='lnkRemove' class='clsRemove remove'>X</a></span></div>");
getProductList(rIndex);
});
getProductList(0);
});
</script>
<html>
<body>
<div class="span11 " style="margin-bottom : 20px; ">
<div class="row-fluid">
<div class="span1" style="margin-left:10px; width:100px;">
Section Name
</div>
<div class="span1" style="margin-left:60px;width:120px;">
Section Code
</div>
<div class="span1" style="margin-left:10px;width:60px;">
Size
</div>
<div class="span1" style="margin-left:20px;width:80px;">
Length
</div>
<div class="span1" style="margin-left:20px;width:80px;">
Thickness
</div>
<div class="span1" style="margin-left:20px;width:90px;">
Avg. Weight
</div>
<div class="span1" style="margin-left:35px;width:80px;">
Quantity
</div>
</div>
<div class="row-fluid" id="ProductList">
#*<input type="text" id="SectionName" style="width:10%; margin-right:40px;" />*#
<span style='font-size: 12px;margin-left:0px;'><select class='clsProductId span11' id='ddProductList_0' name='ProductId' style='font-size:12px;width:150px;margin-right:3px;margin-left:0px;'>
<option selected="selected" value=""></option>
</select></span>
<input type="text" id="SectionCode" name="SectionCode" style="width:10%; margin-left:10px;" />
<input type="text" id="Size" name="Size" style="width:5%; margin-left:20px;" />
<input type="text" id="Length" name="Length" style="width:8%; margin-left:20px;" />
<input type="text" id="Thickness" name="Thickness" style="width:8%; margin-left:20px;" />
<input type="text" id="Weight" name="Weight" style="width:8%; margin-left:20px;" />
<input type="text" id="Quantity" name="Quantity" style="width:8%; margin-left:30px;" />
#* <span style="margin-left:10px;padding-top:6px;"> <a href='#' style='font-size:14px;text-decoration:none;font-weight:bold;' id='lnkRemove' class='clsRemove remove'>X</a></span>
<a href='#' class='123'>X</a>
<div class="span10" style="margin-left:0px;">
Add Product
<span id="LinkErrorMsg" class="field-validation-error"></span>
</div>
</div>
</body>
</html>
Try event delegation using .on() as your remove link is created runtime.
$("#ProductList").on('click','.remove',function () {
alert("asd");
$(this).closest("div.row-fluid").remove(); // Avoid parent().parent() you can use .closest()
});
ref:
.closest() API docs

Categories