I'm trying to add an input field when clicking on add, and it should be removed when clicking on delete click.
Here is JS Bin link:
JS issue with deletion
var newTextBoxDiv;
var rowCount = 0;
var counter = 1;
var delCounter = 1;
$(document).ready(function() {
$(document).on('focus', '.txtFocus', function() {
$(this).next('.clearContent').hide()
});
$(document).on('focusout', '.txtFocus', function() {
$('.clearContent').show()
})
});
function addTags(obj) {
var newTextBoxDiv = '<div class="col-md-4 TextBoxMainDiv"><div style=""><div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px;float:left;width:80%;"><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" class="txtFocus" required placeholder="Add Tag" autocomplete="false" style="width: 100%" ><span class="clearContent"><i class="fas fa-times"></i></span> </div><div style="width: 15%;display: inline-block;text-align:right;"><span id="addMore" onClick="addTags(this);"><i class="fas fa-plus-square"></i></span></div></div></div>';
$(obj).hide();
$("#tagElement").append(newTextBoxDiv);
$('.txtFocus').focus();
counter++;
if (counter == 1) {
$(obj).show()
}
}
function deleteTag(obj) {
$(obj).closest('.TextBoxMainDiv').last().find('#addMore').show();
$(obj).closest('.TextBoxMainDiv').last().find('#addMore').css('display', 'block');
$(obj).closest('.TextBoxMainDiv').remove();
counter--;
if (counter == 1) {
$('#addMore').show()
}
}
<div class="row">
<div id="tagElement">
<div> </div>
<div class="col-md-4 TextBoxMainDiv">
<div style="">
<div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px;float:left;width:80%;">
<input type="text" class="txtFocus" required placeholder="Add Tag" id="textBox" autocomplete="false" autofocus="autofocus" style="width: 100%">
<span class="clearContent">
Add
</span>
</div>
<div style="width: 15%;display: inline-block;text-align:right;">
<span id="addMore" onClick="addTags(this);">
cancel
</span>
</div>
</div>
</div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
I manage to add the input fields properly, but have issues deleting them. They seem to be deleted randomly.
I think the add and delete button are mixed up, but I couldn't spend time on analysing the code because it's too much code for something that does very little. The following demo:
has a single button that adds a row of form controls:
a checkbox
a text input
a button that deletes it's own row as well as itself.
Demo
var index = 0;
var template = `
<figure class='frame'><input class='status' type='checkbox'><label class='tag'></label><input class='text' type='text' placeholder='Enter New Task'><button class='del' type='button'>➖</button></figure>`;
$('.set').on('click', 'button', function(e) {
if ($(this).hasClass('add')) {
index++;
$('.set').prepend(template);
$('.status:eq(0)').attr('id', 'chx' + index);
$('.tag:eq(0)').attr('for', 'chx' + index);
} else {
$(this).prevUntil('.del, .add').add(this).remove();
}
});
.set {
position: relative;
padding: 2px 0 1px 2px;
min-height: 28px;
border-radius:7px;
}
.frame {
padding: 0;
margin: 0;
min-width:90vw;
}
.add {
position: absolute;
right: 6px;
top: 3px;
display:block;
}
.status {
display: none
}
.tag {
display: inline-table;
font-size: 28px;
line-height: 1;
vertical-align: middle
}
.tag::before {
content: '\2610';
}
.status:checked+.tag::before {
content: '\2611'
}
.text {
display:inline-table;
width: 75%;
margin: 2px 5px 0
}
<form id='ui'>
<fieldset class='set'>
<figure class='frame'>
<input id='chx0' class='status' type='checkbox'>
<label for='chx0' class='tag'></label>
<input class='text' type='text' placeholder='Enter New Task' style='margin:2.5px 2px 0 0' autofocus>
<button class='del' type='button'>➖</button>
</figure>
<button class='add' type='button'>➕</button>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I think your code's logic is working, however, the icon for addition and deletion of inputs is not being rendered.
You can replace your newTextBoxDiv with this:
var newTextBoxDiv = `
<div class="col-md-4 TextBoxMainDiv">
<div style="">
<div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px; float:left; width:80%;">
<input type="text" name="textbox${counter}" id="textbox${counter}" value="" class="txtFocus" required placeholder="Add Tag" autocomplete="false" style="width: 100%" >
<span class="clearContent">
Delete<i class="fas fa-times"></i>
</span>
</div>
<div style="width: 15%;display: inline-block;text-align:right;">
<span id="addMore" onClick="addTags(this);">
Add
</span>
</div>
</div>`;
Notice that I added the word "Add" and "Delete" between the tags, so that you have something to click on
Also, I think you need to swap the word "Add" and "Cancel" in the initial HTML to convey a clearer message, as they are now doing the opposite thing.
Another fix that's needed is to replace the id="addMore" with class="addMore"
<span class="addMore" onClick="addTags(this);">
Since id is meant to be unique. In your code, however, when you append new element, you added new elements with duplicate id, making jquery's selector not selecting the element you want.
After replacing id with class, you also need to change the deleteTag function to select the last "addMore" span and show it.
function deleteTag(obj) {
$(obj).closest('.TextBoxMainDiv').last().find('.addMore').show();
$(obj).closest('.TextBoxMainDiv').last().find('.addMore').css('display', 'block');
$(obj).closest('.TextBoxMainDiv').remove();
counter--;
$('.addMore').last().show();
}
For the layout, you need to do it with css, removing float and setting the div tag with appropriate width and display: inline-block. I suggest you use a separate css file to style the elements instead of doing it inline.
function deleteTodo() {
$(this).parent().remove();
}
function addTodo() {
var inputTemplate =
'<div class="todo-input-wrapper">' +
'<input class="todo-input" type="text" placeholder="Add Tag" />' +
'<button class="delete-button">Delete</button>' +
'</div>';
$('.todo-wrapper').append(inputTemplate);
$('.delete-button').last().on('click', deleteTodo);
$('.todo-input').last().focus();
}
$(document).ready(function () {
$('.delete-button').on('click', deleteTodo);
$('.add-button').on('click', addTodo);
});
.todo-wrapper {
display: inline-block;
width: max-content;
font-size: 0;
}
.todo-input-wrapper {
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="todo-wrapper">
<div class="todo-input-wrapper">
<input class="todo-input" type="text" placeholder="Add Tag" />
<button class="delete-button">Delete</button>
</div>
</div>
<button class="add-button">Add</button>
Related
I have a input field that takes numeric inputs. Then i have a button which display the number of divs as per that input. after displaying div there is two radio-box buttons (paired end and single end) if I select paired end then i want two file upload fields in each divs. and if i select single end then i want only one file upload fields in each div.
I have tried but fileupload fields working on only first div.
function CreateText() {
var text = `<div class="row border-top py-3">
<div class="col-md-3">
<label">sample name *</label></br>
<input type="sample" id="sample" name="sample[]">
</div>
<div class="col-md-3" style="display:none" id="showsingle">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename1[]">
</div>
</div>
<div class="col-md-3" style="display:none" id="showpair">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn">Remove</button>
</div>
</div>
</div>`;
var textCount = document.getElementById('textInput').value;
var html = '';
for (var i = 0; i < $('#textInput').val(); i++) {
html = document.getElementById('divDynamicTexts').innerHTML;
document.getElementById('divDynamicTexts').innerHTML = html + text.replace('', i);
}
}
function onlyOne() {
let SradioBox = document.getElementById("singleradio"),
Sfileupload = document.getElementById("showsingle"),
PradioBox = document.getElementById("pairedradio"),
Pfileupload = document.getElementById("showpair");
if (SradioBox.checked == true) {
Sfileupload.style.display = "block",
Pfileupload.style.display = "none";
} else if (PradioBox.checked == true) {
Pfileupload.style.display = "block",
Sfileupload.style.display = "none";
} else {
Pfileupload.style.display = "none",
Sfileupload.style.display = "none";
}
};
$(document).ready(function() {
$(document).on('click', '.remove_add_btn', function(e) {
e.preventDefault();
let row_item = $(this).parent().parent().parent();
$(row_item).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-center">
<input type="text" id="textInput" value="" />
<input type="button" id="" value="Create upload fields" onclick="CreateText();" />
<div class="col-md-4" id="filebutton">
<div class="form-group ">
<label for="form_need">Library Type *</label>
</br>
<div class="px-2">
<label for="myradio">Single end:</label>
<input type="radio" id="singleradio" name="check" onclick="onlyOne();">
<label for="myradio">Paired end:</label>
<input type="radio" id="pairedradio" name="check" onclick="onlyOne();">
</div>
</div>
</div>
</div>
<div id="divDynamicTexts"></div>
ID attributes must be unique. It would be better to remove the IDs altogether ( or change to dataset attributes perhaps ) and use a delegated event listener to process the various clicks related to the task of adding/removing dynamic elements.
In the code below all ID attributes were either removed entirely or changed to data-id type values.
To avoid the need to process different form file input fields at the server the file-input fields are named the same but have an index so can be identified more readily in PHP ( or whatever backend you have )
The delegated listener, because it is bound to the document, will work for all elements whether or not they are static or added dynamically and makes heavy use of the event.target property to help identify the element that invoked the event.
The label element was being used incorrectly previously. If the form-input is within the label then there is no need for the for="ID" syntax ( note that the ID should be the ID of the input element to which the label belongs! ) - as it was the label's appeared to have a for attribute which did not related to an element in the form!
Using querySelector and querySelectorAll you can easily identify nodes of interest within the DOM so button clicks or radio button selection can fire a query to find nodes that are relevant - thus simplifying the hiding/showing of the file input elements.
const strhtml = `
<div data-id="dynrow" class="row border-top py-3">
<div class="col-md-3">
<label>sample name *<input type="text" name="sample[]"></label>
</div>
<div class="col-md-3" style="display:none" data-id="single" data-role="file-field">
<div class="form-group">
<label>Upload file *<input type="file" name="filename[1]" /></label>
</div>
</div>
<div class="col-md-3" style="display:none" data-id="pair" data-role="file-field">
<div class="form-group ">
<label>Upload file *<input type="file" name="filename[1]" /></label>
<label>Upload file *<input type="file" name="filename[2]" /></label>
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn" data-id='remove'>Remove</button>
</div>
</div>
</div>`;
const _radio = document.querySelectorAll('[type="radio"][data-id]');
const _bttn = document.querySelector('[type="button"][data-id="add"]');
const _div = document.querySelector('#divDynamicTexts');
const _input = document.querySelector('input[type="number"][data-id="textInput"]');
let choice = false;
let qty = false;
/*
Disable radio buttons and the "Create" button initially
and enable when changes are made in the correct sequence.
1: select quantity -> enable radio bttns
2: select single or double -> enable "create" bttn
3: click bttn, create as per radio selection
*/
_input.addEventListener('change', e => {
_radio.forEach(n => {
n.disabled = e.target.value > 0 ? false : true;
});
qty=e.target.value;
});
document.addEventListener('click', e => {
if (e.target instanceof HTMLInputElement && e.target.dataset.id != null) {
/*
set global "choice" variable
and enable "Create" bttn.
*/
if (e.target.type == 'radio') {
choice = e.target.dataset.id;
_bttn.disabled = false;
}
}
/*
If the "choice" has been made the radio
buttons will be enabled. Based on radio
button selected create new HTML and then
unhide the appropriate single/pair DIV
element
*/
if (choice && qty > 0 && e.target.type == 'button') {
_div.innerHTML = '';
for (let i = 0; i < qty; i++) _div.insertAdjacentHTML('afterbegin', strhtml);
let expr = `div[data-id="${choice}"]`;
document.querySelectorAll(expr).forEach(n => n.style.display = 'block');
}
/*
unchanged: delete DIV & contents when "Remove" bttn is clicked.
*/
if (e.target instanceof HTMLButtonElement && e.target.dataset.id != null) {
if (e.target.dataset.id == 'remove') {
_div.removeChild(e.target.closest('[data-id="dynrow"]'));
}
}
});
body {
font-family: arial;
}
label {
display: block;
}
.px-2 {
display: inline-block;
}
.px-2 label {
display: inline-block;
margin: 0.5rem;
}
h2 {
font-size: 1.1rem;
margin: 1rem 0 0 0;
display: inline-block;
width: auto;
}
.inline {
display: inline;
margin: 0 1rem 0 0;
}
#divDynamicTexts {
min-height: 1rem;
margin: 2rem auto
}
div.row {
padding: 0.5rem;
border: 1px dotted grey;
margin: 0.5rem;
}
div[data-id='single'] .form-group label {
background: aliceblue
}
div[data-id='pair'] .form-group label {
background: lightsteelblue
}
div[data-id] .form-group label {
outline: 1px solid grey;
padding: 0.5rem;
margin: 0.5rem 0
}
.bold {
font-weight: bold
}
[disabled]{
border:1px solid red;
outline:2px solid red;
background:rgba(255,0,0,0.25);
}
<div class='text-center'>
<label class='inline bold'>Quantity:<input type='number' data-id='textInput' /></label>
<div class='col-md-4'>
<div class='form-group'>
<h2>Library Type</h2>
<div class='px-2'>
<label>Single end: <input type='radio' data-id='single' name='check' disabled /></label>
<label>Paired end: <input type='radio' data-id='pair' name='check' disabled /></label>
</div>
</div>
</div>
<input type='button' data-id='add' value='Create upload fields' disabled />
</div>
<div id='divDynamicTexts'></div>
So i'm trying to remove the label and its value from my input html tag whenever the person enters a value, and the code that I have right now does the job but it only removes the value when I click on the input box. Once I enter a value the label is stuck there along with the value of the input. Can someone help me make it so the label is removed completely not just when it's clicked on. And is this something I can do with css? if I can't then how would I do it with javascript?
.text-input-wrapper {
position: relative;
}
.text-input-wrapper label {
position: absolute;
left: 0;
}
.text-input-wrapper label::before {
transition: 0s;
}
.text-input-wrapper label.icon1::before {
content: 'Email';
}
.text-input-wrapper label.icon2::before {
content: 'Password';
}
.text-input-wrapper input {
padding: 0 2rem 0;
}
.text-input-wrapper input:focus+label::before,
.text-input-wrapper input:active+label::before {
display: none;
}
<form class="clearfix credentials-form login-form" method="POST">
<div class="credentials-form__fields">
<div class="text-input standard login-text-input login-email">
<div class="text-input-error-wrapper">
</div>
<div class="text-input-wrapper">
<input type="email" id="login_email2812380460348143" class="text-input-input" name="login_email" value="" autocomplete="off" aria-invalid="false" inputmode="text">
<label for="login_email2812380460348143" class="icon1"></label>
</div>
</div>
<div>
<div class="tooltip-container">
</div>
<div class="text-input standard login-text-input login-password">
<div class="text-input-error-wrapper">
</div>
<div class="text-input-wrapper">
<input type="password" id="login_password5101720956289264" class="text-input-input password-input" name="login_password" value="" autocomplete="off" aria-invalid="false" inputmode="text">
<label for="login_password5101720956289264" class="icon2"></label>
</div>
</div>
</div>
</div>
<button class="login-button signin-button button-primary" type="submit">
<div class="signin-text">Sign in
</div></button>
</form>
Try this way...
const inputs = document.querySelectorAll('.text-input-wrapper input');
const labels = document.querySelectorAll('.text-input-wrapper label');
inputs.forEach((input, i) => {
input.addEventListener('input', () => {
labels[i].style.opacity = 0;
});
});
Use an onInput event instead of an onChange one.
I'm having a problem with an error: jQuery input val() is undefiend.
I have 3 inputs which are referring to one item.
On add Row i can add an new Item ( 3 rows ).
All those rows have to be prepared in array to be sent to a PHP file.
I believe that my id="item[0]['name']" is wrong.
$(document).ready(function() {
var counter = 1;
$("#addRow").click(function() {
$("#ItemContainer").append(`
<div class="item">
<div><input type="text" id="item[${counter}]['name']" placeholder="Name" ></div>
<div><input type="text" id="item[${counter}]['amount']" placeholder="Amount" ></div>
<div><input type="text" id="item[${counter}]['count']" placeholder="Count" ></div>
<div></div>
</div>
`);
counter = counter + 1;
});
$("#setKasse").click(function() {
for (let i = 0; i <= (counter - 1); i++) {
console.log($(`#item[${i}]`));
console.log($(`#item[${i}]["name"]`).val());
};
});
});
*{
padding: 0;
margin: 0;
}
body{
background-color: #E6E6FA;
color : #191970;
padding-left : 5%;
padding-top : 70px
}
#Container, #ItemContainer, .item {
width: 20%;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: auto;
row-gap : 18px;
}
#ItemContainer, .item{
width: 100%;
row-gap : 2px;
}
input{
height: 30px;
width: 100%;
border: none;
box-sizing: border-box;
padding-left: 4px;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Container">
<div><button id="addRow"> Add Row </button></div>
<div id="ItemContainer">
<div class="item">
<div><input type="text" id="item[0]['name']" placeholder="Name" ></div>
<div><input type="text" id="item[0]['amount']" placeholder="Amount" ></div>
<div><input type="text" id="item[0]['count']" placeholder="Count" ></div>
<div></div>
</div>
</div>
<div><button id="setKasse"> Set Kasse </button></div>
</div>
So, I want a way to be able to cycle and loop into objects|Arrays
My main goal is to send the data via Ajax Post request, and for that I want to refactor the Array in another Format.
In selectors, [ is used to indicate an attribute selector. If you want to use it as a literal character in the ID, you need to escape it with backslash. You also need to escape the ' characters.
You also need to include the ['name'] part of the ID (or ['amount'] or ['count'] if you want to get those inputs).
$(document).ready(function() {
var counter = 1;
$("#addRow").click(function() {
$("#ItemContainer").append(`
<div class="item">
<div><input type="text" id="item[${counter}]['name']" placeholder="Name" ></div>
<div><input type="text" id="item[${counter}]['amount']" placeholder="Amount" ></div>
<div><input type="text" id="item[${counter}]['count']" placeholder="Count" ></div>
<div></div>
</div>
`);
counter = counter + 1;
}); // end of $("#addRow").click
$("#setKasse").click(function() {
for (let i = 0; i <= (counter - 1); i++) {
console.log($(`#item\\[${i}\\]\\[\\'name\\'\\]`).val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Container">
<div><button id="addRow"> Add Row </button></div>
<div id="ItemContainer">
<div class="item">
<div><input type="text" id="item[0]['name']" placeholder="Name"></div>
<div><input type="text" id="item[0]['amount']" placeholder="Amount"></div>
<div><input type="text" id="item[0]['count']" placeholder="Count"></div>
<div></div>
</div>
</div>
<div><button id="setKasse"> Set Kasse </button></div>
</div>
In my opinion, it's best to avoid using characters that have special meaning in CSS selectors in your IDs, it complicates the code unnecessarily. You could use id="item-${counter}-name". Or don't use IDs for dynamically created elements at all. Use a class like class="name", and then use dynamic indexing. $(".item").eq(i).find("input.name").
$(document).ready(function() {
var counter = 1;
$("#addRow").click(function() {
$("#ItemContainer").append(`
<div class="item">
<div><input type="text" class="name" placeholder="Name" ></div>
<div><input type="text" class="amount" placeholder="Amount" ></div>
<div><input type="text" class="count" placeholder="Count" ></div>
<div></div>
</div>
`);
counter = counter + 1;
}); // end of $("#addRow").click
$("#setKasse").click(function() {
for (let i = 0; i < counter; i++) {
console.log($(".item").eq(i).find(".name").val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Container">
<div><button id="addRow"> Add Row </button></div>
<div id="ItemContainer">
<div class="item">
<div><input type="text" class="name" placeholder="Name"></div>
<div><input type="text" class="amount" placeholder="Amount"></div>
<div><input type="text" class="count" placeholder="Count"></div>
<div></div>
</div>
</div>
<div><button id="setKasse"> Set Kasse </button></div>
</div>
I have an HTML checkbox next to a paragraph. When the user check the box, I want to put a strike through the paragraph using css bootstrap.
To add the strike through, I should wrap the paragraph with <del></del> tag.
I am able to wrap the paragraph correctly with the <del></del> when the box is checked. However, I am unable to remove the <del></del> tag when the user uncheck the box.
My code seems to be failing to check if the element is a del.
I created a fiddler to show you what is happening https://jsfiddle.net/vo1npqdx/1335/
in the fiddler, you will see that the code if (display.is('del')) { .... } is failing so the code inside the if statement never gets fired.
I tried to print the html code to the console to make sure I am dealing with the correct element, and it is clearly showing the correct code.
How can I unwrap my paragraph from the del tag?
Here is my JS code
$(function(){
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
} else {
var firstDisplay = display.parent().children().first();
console.log(firstDisplay.html())
if (display.is('del')) { // this is failing
firstDisplay.unwrap();
}
}
});
});
Here is my HTML code
$(function(){
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
} else {
var firstDisplay = display.parent().children().first();
console.log(firstDisplay.html())
if (display.is('del')) { // this is failing
firstDisplay.unwrap();
}
}
});
});
body {
padding-top: 65px;
padding-bottom: 20px;
}
/* Set padding to keep content from hitting the edges */
.body-content {
padding-left: 15px;
padding-right: 15px;
}
/* Override the default bootstrap behavior where horizontal description lists
will truncate terms that are too long to fit in the left column.
Also, add a 8pm to the bottom margin
*/
.dl-horizontal dt {
white-space: normal;
margin-bottom: 8px;
}
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea,
.input-width-input {
max-width: 380px;
}
.uploaded-file-name {
max-width: 310px;
}
.help-block-standard {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
/* Vertically align the table cells inside body-panel */
.panel-body .table > tr > td
{
vertical-align: middle;
}
.panel-body-with-table
{
padding: 0;
}
.mt-5 {
margin-top: 5px !important;
}
.mb-5 {
margin-bottom: 5px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="http://laravel54.dev/assets/asset/6" accept-charset="UTF-8" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" name="_token" value="UA428wC4vxZgb9OmNCGBIkosCN4KuS49VgFiUTET">
<input name="_method" type="hidden" value="PUT">
<div class="form-group ">
<label for="name" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input class="form-control" name="name" type="text" id="name" value="Some new test" minlength="1" maxlength="255" required="true" placeholder="Enter name here...">
</div>
</div>
<div class="form-group ">
<label for="notes" class="col-md-2 control-label">Notes</label>
<div class="col-md-10">
<textarea class="form-control" name="notes" cols="50" rows="10" id="notes" maxlength="1000"></textarea>
</div>
</div>
<div class="form-group " style="margin-bottom: 5px;">
<label for="picture" class="col-md-2 control-label">Picture</label>
<div class="col-md-10">
<div class="input-group uploaded-file-group">
<label class="input-group-btn">
<span class="btn btn-default">
Browse <input type="file" name="picture" id="picture" class="hidden">
</span>
</label>
<input type="text" class="form-control uploaded-file-name" readonly>
</div>
<div class="input-group input-width-input">
<span class="input-group-addon">
<input type="checkbox" name="custom_delete_picture" class="custom_delete_file"> Delete
</span>
<span class="input-group-addon custom_delete_file_name">
<p>uploads/zCmPgC5yMor77DaM50nTTnSnxh4y75e7B06WUFFM.jpeg</p>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input class="btn btn-primary" type="submit" value="Update">
</div>
</div>
</form>
Maybe something like this?
var del = display.children().first();
console.log(del)
if (del.is('del')) {
del.contents().unwrap();
}
The del is element should be the first child of display. I've used console.log(del) because using html() is effectively giving you the innerHTML, which isn't particular helpful.
In your original code, display is your p element and this line was just going 'up one, down one', ending up back at the p:
var firstDisplay = display.parent().children().first();
This is the solution to your answer.
$(function(){
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
} else {
$(".custom_delete_file_name:eq(0) p").html($(".custom_delete_file_name:eq(0) p del").html());
}
});
});
But keep in mind you don't have to wrap it with a tag to make it strike through. You can simply add a css class or a style property with
text-decoration: line-through;
and toggle it.
This is the best approach.
A different approach... Intead of unwrap, just overwrite the p again with the content inside of del...
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
}
else {
display.html(display.find('del').text());
}
});
I hope it helps
can any one let me know
how can i add the delete button on each row pls
from the below code
[Jsfiddle][1]
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<div class="row"><div class="col-lg-6"><input type="text" name="first_name' +
counter + '"/></div><div class="row"><div class="col-lg-6"><input type="text" name="last_name' +
counter + '"/></div></div>');
jQuery('div.row').append(newRow);
});
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-6"><input type="text" name="first_name" /></div><div class="col-lg-6"><input type="text" name="last_name" /></div>
</div>
Add Author
To "delete" an element you can use the jQuery('element').remove() function.
By using the jQuery('element').on() you can listen to events even if the element is created later on.
Please read the documentation about .on() carefully!
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<div class="row"><div class="col-lg-6"><input type="text" name="first_name' +
counter + '"/></div><div class="col-lg-6"><input type="text" name="last_name' +
counter + '"/></div><div>delete</div></div>');
jQuery('.add-author').before(newRow);
});
//Bound to 'body' for this sample, bind to you own wrapper element when using this!
jQuery('body').on('click', '.delete', function(event)
{
event.preventDefault();
$(this).closest('.row').remove();
});
.row { position: relative; width: 500px; height: auto; margin: 5px 0; overflow: hidden; }
.row div { position: relative; float: left; width: 150px; height: auto; overflow: hidden; }
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-6"><input type="text" name="first_name" /></div><div class="col-lg-6"><input type="text" name="last_name" /></div>
</div>
Add Author