Delete div with JavaScript - javascript

In my View, I'm dynamically add divs like this via JS:
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" value="Delete" />
</div>
The question is how to delete the chosen one by clicking the Delete button in div?
JavaScript that adds new divs:
<script>
$(function() {
var i = 0;
$('.plus').click(function()
{
++i;
var html2add = "<div id='detail[" + i + "]'>" +
"<input name='detail.Index' type='hidden' value='" + i + "' />" +
"<input name='detail[" + i + "].details_name' type='text' />" +
"<input name='detail[" + i + "].details_value' type='text' />" +
"<input class='btn' type='button' value='Delete' />"+
"</div>";
$('#details_part').append(html2add);
})
})

To delete the div containing the delete button, just use the remove() function:
$(document).on('click', '.btn', function(){
var cur = $(this);
cur.parent().remove();
});

A node cannot commit suicide (remove itself), therefore you must remove it from its parent node like this:
<script>
function deleteItem (id) {
var item = document.getElementById(id);
item.parentNode.removeChild(item)
}
</script>
<div>
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" value="Delete" onclick="deleteItem('detail[0]')" />
</div>
</div>
Codepen example: https://codepen.io/getreworked/pen/MmVMJB

If you are using Jquery you can do
$(".btn").click(function () {
$(this).closest("div").remove();
})

There are many ways to do this.
This one will hide the div using purely JavaScript.
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" onclick="removeDiv('detail[0]')" value="Delete" />
</div>
<script>
function removeDiv(id){
document.getElementById(id).style.display = 'none';
}
</script>
Just pass the parameter of the ID of your parent div.
This is Using jQuery:
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" value="Delete" />
</div>
<script>
$(function(){
$('.btn').click(function(){
$(this).parent().remove();
});
});
</script>
Cheers,

// Include below jquery 1.7 script in your file first
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js">
// then use this code to remove
<script type="text/javascript">
$(function(){
$('.btn').live('click' , function(){
$(this).parent('div').remove();
});
});
</script>

Related

How can I delete an element in an object?

I have a checkbox which add an id of his value in array when checked and I want to delete this value when I uncheck it
I tried to remove my id with and indexOf() + splice() but I can't use indexOf() because I'm using an object
Some one have an idea to how can I delete my id when I uncheck my checkbox,
or if there is a trick to use indexOf with an object?
there is my script :
$(document).ready(function() {
const formInputIds = $('form#export input[name="ids"]');
$('.exportCheckbox:checkbox').on('change', function() {
const announceId = $(this).data('id');
if (this.checked) {
formInputIds.push(announceId);
console.log(formInputIds);
} else {
const index = formInputIds.val().indexOf(announceId);
if (index > -1) {
formInputIds.val().splice(index, 1);
}
console.log(formInputIds);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<some data of product displayed>
<input type="checkbox" data-id="{{annonce._id}}" class="exportCheckbox"/>
there is the console.log of formInputIds with 3 ids :
Consider the following.
$(function() {
var formInputIds;
function getChecked(target) {
var results = [];
$("input[type='checkbox']", target).each(function(i, elem) {
if ($(elem).is(":checked")) {
results.push($(elem).data("id"));
}
});
return results;
}
$('.exportCheckbox').on('change', function(event) {
formInputIds = getChecked($(this).parent());
console.log(formInputIds);
});
$("#export").submit(function(event) {
event.preventDefault();
console.log(formInputIds);
$("[name='ids']", this).val("[" + formInputIds.toString() + "]");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<div class="some content">
<input type="checkbox" data-id="1001" class="exportCheckbox" />
<input type="checkbox" data-id="1002" class="exportCheckbox" />
<input type="checkbox" data-id="1003" class="exportCheckbox" />
<input type="checkbox" data-id="1004" class="exportCheckbox" />
<input type="checkbox" data-id="1005" class="exportCheckbox" />
<input type="checkbox" data-id="1006" class="exportCheckbox" />
</div>
This way, you build the Array based on just the checked items. No need to find and slice the exact item.

jquery ajax submit 2 diffrent or many form

i'm new in jquery ajax and i need some help.
This is my basic html.
<form id="replayForm1">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(1)">Click Me</button>
</form>
<form id="replayForm2">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(2)">Click Me</button>
</form>
This is my jquery:
<script>
function getmsg(formID) {
var formName = '#replayForm' + formID;
$(formName).submit(function (e) {
e.preventDefault();
var msg_id = $('input[name=msg_id]').val();
var msg_replay = $('input[name=msg_replay]').val();
alert(msg_id + msg_replay);
});
}
</script>
My problem is, when i fill the second form i get empty value. First form don't have problem it return value and don't have problem. How to deal this problem? i try make this form unique to easy submit form just using 1 function.
jQuery will look for the first instance which it finds of the inputs, so use the formName to match the correct ones.
You should also remove the previous event or you will get multiple alerts after the second click on the same button.
function getmsg(formID) {
var formName = '#replayForm' + formID;
$(formName).off('submit').on('submit', function (e) {
e.preventDefault();
var msg_id = $(formName + ' input[name=msg_id]').val();
var msg_replay = $(formName + ' input[name=msg_replay]').val();
alert(msg_id + msg_replay);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="replayForm1">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(1)">Click Me</button>
</form>
<form id="replayForm2">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(2)">Click Me</button>
</form>
In both the case the name is same. Change the name & pass those values to getmsg function
function getmsg(formID, inputName, msgReplyName) {
var formName = '#replayForm' + formID;
$(formName).submit(function(e) {
e.preventDefault();
var msg_id = $('input[name=' + inputName + ']').val();
var msg_replay = $('input[name=' + msgReplyName + ']').val();
alert(msg_id + ' ' + msg_replay);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="replayForm1">
msg_id:
<input type="text" name="msg_id">
<br> msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(1,'msg_id','msg_replay')">Click Me</button>
</form>
<form id="replayForm2">
msg_id:
<input type="text" name="msg_id_2">
<br> msg_replay
<input type="text" name="msg_replay_2">
<button onClick="getmsg(2,'msg_id_2','msg_replay_2')">Click Me</button>
</form>

Pass the values from View to Controller for Dynamically populated forms

I have a form in which the TextBox is dynamically populated. The user has the flexibility to add and remove TextBox which is done using JQuery.
I would need to pass the value of TextBox to my Controller on Submit.
This is my View.
#using (Html.BeginForm("Controller", "Admin", FormMethod.Post, new { required = "required" }))
{
<h4>Add new Q&A</h4>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type="text" name="Question" id="Question" required placeholder="Question 1" class="form-control" /><br />
</div>
</div>
<input type="button" name="Add" id="Add" value="Add" class="btn btn-success" />
<input type="button" name="Remove" id="Remove" value="Remove" class="btn btn-danger" /> <br /><br />
<textarea rows="5" name="Answer" id="Answer" placeholder="Answer" required class="form-control"></textarea><br />
#Html.DropDownList("Intent", ViewData["Intent"] as List<SelectListItem>, "Select Intent", new { #class = "form-control", required = "required" })
<br /><input type="text" name="PrimaryEntity" id="PrimaryEntity" placeholder="Primary keyword" required class="form-control" /><br />
<input type="text" name="SecondaryEntity" id="SecondaryEntity" placeholder="Secondary keyword (optional)" class="form-control" /><br />
<input type="submit" name="Submit" id="Submit" class="btn btn-success" />
}
This is how my JS looks
$(document).ready(function () {
var counter = 2;
$("#Add").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
'" id="Question' + counter + '" value="" class="form-control" required placeholder="Question ' + counter +
'"> <br />');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#Remove").click(function () {
if (counter == 2) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
Sorry if I sound lame. Just getting started with MVC!
You can create a simple model having property Questions of List<string> type and other required properties.
Then from jQuery you can add multiple TextBoxes using a simple logic:
<input type="text" name="Model.Questions[" + index + "]" id="Model_Questions_" + index />
Render using:
#for (int i = 0; i < Model.Questions.Count; i++)
{
#Html.TextBoxFor(x => Model.Questions[i], { .... })
}
When you post your form, all values in questions textboxes will be posted to your model's Questions list.
Note: I have not written above code in VS, so there may be some errors which you can fix yourself.

How to get values of multiple textboxes generated dynamically?

I have a button called 'AddTextArea', on clicking, I get new text area, but how can I get the values that I have entered in the new text areas?
I tried like this-
var x= document.getElementById("div_quotes").value;
but it's not working.
Please help, as I am new to JS, thanks in advance.
<html>
<head>
<script type="text/javascript">
function addTextArea(){
var div = document.getElementById('div_quotes');
div.innerHTML += "<textarea name='new_quote[]' />";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>
var x= document.getElementById("div_quotes").value;
Above code will not work as div_quotes is a div and div do not have value property.
You will have to search for textareas in this div.
Sample
function addTextArea() {
var div = document.getElementById('div_quotes');
div.innerHTML += "<textarea name='new_quote[]' />";
div.innerHTML += "\n<br />";
}
function validate(){
var tas = document.querySelectorAll('#div_quotes textarea[name="new_quote[]"]')
for(var i = 0; i< tas.length; i++){
console.log(tas[i].value)
}
}
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="button" name="submitted" onclick="validate()" value="Validate">
</form>
Version 2
Now if you notice in above sample, if you type and then add another textarea, it will flush value of previous ones. This is because, you are setting .innerHTML += .... This will destroy and recreate all elements again. You should use document.createElement
function addTextArea() {
var div = document.getElementById('div_quotes');
var wrapper = document.createElement('div')
var ta = document.createElement('textarea');
ta.name = "new_quote[]"
wrapper.append(ta);
div.append(wrapper)
}
function validate(){
var tas = document.querySelectorAll('#div_quotes textarea[name="new_quote[]"]')
for(var i = 0; i< tas.length; i++){
console.log(tas[i].value)
}
}
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="button" name="submitted" onclick="validate()" value="Validate">
</form>
You can add a CSS Class to the new text area that is generated and get the data using
var x = document.getElementsByClassName("dynamicTxtArea")
I have added the class to the Text area that is being dynamically generated. Please check the code below.
<html>
<head>
<script type="text/javascript">
function addTextArea(){
div.innerHTML += "<textarea name='new_quote[]' class='dynamicTxtArea'/>";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>

How to generate HTML with jquery clone with different names?

I have HTML like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
</div>
<input type='button' id='add' value='Add'>
jQuery:
$("input#add").live( 'click', function(){
$("#main").append("<br />");
$("#child-0").clone(false).appendTo( $("#main") );
});
Above code is working but it is creating elements with same name. I want to generate it something like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
<div id='child-1'>
<input type='text' name='data[1][name]'>
<input type='text' name='data[1][dob]'>
<input type='text' name='data[1][location]'>
</div>
</div>
What is the simple solution.
Thanks
$("input#add").live( 'click', function(){
$("#main").append("<br />");
var cloned = $("#main div:last").clone(false).appendTo( $("#main") );
cloned.find('[name^=data]').attr('name', function() {
var index = this.name.match(/\[(\d)\]/);
if (index != null && index.length > 1) {
var newIndex = parseInt(index[1], 10) + 1;
return this.name.replace(/\[(\d)\]/, '[' + newIndex + ']');
}
return this.name;
});
});​

Categories

Resources