Remove clicked id from the input value - javascript

I am trying to delete clicked id to remove input value. For example i have this input <input type='hidden' id='uploadvalues' value="8,9"/> you can see the values 8,9 and the button is <div class="delete" id="9"></div> .
When i click the id="9" then the input value 9 should be remove . After clicked id="9" ==> <input type='hidden' id='uploadvalues' value="8"/>
How can i do that anyone can teach me?
Demo from CodeCanyon
<div class="container">
<div class="area">
<div class="image"><img src="https://s-media-cache-ak0.pinimg.com/736x/05/2f/1b/052f1b3a2361eb4f3c1385c1fd4f75ed.jpg"></div>
<div class="delete" id="8"></div>
</div>
<div class="area">
<div class="image"><img src="http://www.wallpapermade.com/images/wallpapers/originals/tip-and-oh-laugh-together-home-2015-movie-wallpaper-4612.jpg"></div>
<div class="delete" id="9"></div>
</div>
<input type='hidden' id='uploadvalues' value="8,9"/>
</div>
JS
$(document).ready(function(){
$("body").on("click", ".delete", function(){
// Remove clicked id from the input value
});
});

One way on the approach you want is
$("body").on("click", ".delete", function(){
var id = this.id, //extract the id from the clicked element
values = $('#uploadvalues').val().split(','), // get the existing values in the #uploadvalues element
remaining = values.filter(function(val){ // filter out the ones equal to the id of the clicked element
return val !== id;
});
$('#uploadvalues').val(remaining.join()); // update the changed values
});

make it
$(document).ready(function(){
$("body").on("click", ".delete", function(){
var val = $(this).attr("id");
var values = $( "#uploadvalues" ).val().split(",");
var valIndex = values.indexOf(val);
if (valIndex > -1)
{
values.splice(valIndex,1);
}
$( "#uploadvalues" ).val( values.join(",") )
});
});

Try to make use of regular expression at this context,
$(document).ready(function() {
$("body").on("click", ".delete", function(){
var id = this.id;
$("#uploadvalues").val(function(val){
return val.replace(new RegExp(id + "\,|\,"+ id +"$"),"")
});
});
});

when you click the delete button, in the callback function grab the id:
var valueToRemove = this.id;
// now you need to look to see if that value is inside the hidden input
var valueToRemove = this.id;
console.log(valueToRemove);
var values = $("#uploadvalues").val();
if(values.indexOf(valueToRemove) >= 0){
$("#uploadvalues").val(values.replace(valueToRemove,""));
}
also its best practice to cache the dom so you dont have to constantly query it.
Is this what you wanted? and this method does not get rid of the comma within the values.

Related

Get the <div> outside of this <div>

I would like to get the second div (total-price), instead of the first div.
Additionally I would like to add a $ sign to the div, yet when it tries to convert the data into an Int, obviously "$" will cause an error.
I have a work around method for this, but is there anyway to concatenate the $?
Many thanks.
<!-- Product #1 -->
<div class="item">
<div class="quantity">
<button class="plus-btn" type="button" name="button">
</button>
<div class="total-price">22</div> <!--I dont want this one -->
</div>
<div class="total-price">22</div> <!--I want to access this div -->
</div>
JQuery
$('.plus-btn').on('click', function(e) {
e.preventDefault();
//Increase cost
var $this = $(this);
var $cost = $this.closest('div').find('div');
var costValue = parseInt($cost.html());
costValue += costValue;
$cost.html(costValue);
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $cost = $this.closest('.quantity').siblings('.total-price');
var costValue = parseInt($cost.html());
costValue += costValue;
$cost.html(costValue);
});
The closest('div') to the button is the div you don't want.
You can simply traverse one level up the DOM tree and to the parent div and find '.total_price' in its sibling.
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $cost = $this.parent().siblings('.total-price');
var costValue = parseInt($cost.html());
costValue += costValue;
$cost.html(costValue);
});

I am trying to remove Items from a list with an on-click, what am I missing?

I am trying to remove an item every time it is clicked on but only a single item at a time (the item that was clicked on) when trying to make a 'to-do' list. I can easily remove all simultaneously but I am having a lot of issues trying to do it at an individual level. I thought this would work but hoping to get a second set of eyes on it.
var toDoCount = 0;
var todoarray = [];
window.onload = function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("#to-dos").prepend(linebreak);
$("#to-dos").prepend(value);
$("#to-dos").prepend(todoclose);
toDoCount++;
todoarray.push(value);
console.log(todoarray);
//to remove item from checklist
$(document.body).on("click", ".checkbox", function() {
var toDoNumber = $(this).attr("data-to-do");
$("#item-" + toDoNumber).remove();
});
});
}
HTML is below
<div class ="col-4">
<!-- To Do List -->
<form onsubmit= "return false;">
<span id = "todo-item" type = "text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
don't need the number, just the element.
change...
$("#item-" + toDoNumber).remove();
to...
$(this).remove();
e.g.
$(document.body).on("click", ".checkbox", function() {
$(this).remove();
});

Adding input forms and removing them again get all id's

I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>

Button Group Click Handler - How to get text content of clicked button?

I am trying to set up two button groups. A click on any button in the second group should add a new button to the first group. The new button shall get the same label as the clicked button.
var name = this.textContent works if the click handler is attached to a single button. How do you get the text content of the clicked button when the click handler is instead attached to a group of buttons?
HTML:
<body>
<div id="group1">
<button> nameA </button>
<button> nameB </button>
</div>
<hr>
<div id="group2">
<button> nameC </button>
<button> nameD </button>
</div>
</body>
Javascript:
$('#group2').on('click', function(event) {
var name = this.textContent // wrong!
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
JSFiddle Demo
Use event delegation:
$('#group2').on('click', 'button', function(event) {
var name = this.textContent
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
Second parameter in 'on' method can be selector string to filter the descendants of the selected elements that trigger the event.
Check this https://jsfiddle.net/q6b6g3xm/
In your case, this should be enought:
$('#group2 button').click(function(event) {
var name = this.textContent
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
Prefer the RobHil solution if you other buttons will be created in #group2 after the execution of the jQuery code.
Else, I see two other possibilities:
$('#group2 button').each(function () {
var $button = $(this).click(function(event) {
var r = $('<input type="button" value="' + $button.text() + '">');
$("div#group1").append(r);
});
});
or:
$('#group2').click(function(event) {
var $button = $(event.target);
var r = $('<input type="button" value="' + $button.text() + '">');
$("div#group1").append(r);
});
But keep in mind the target depend on where you click if you have nested blocks in the clicked zone: https://api.jquery.com/event.target/
Here is my own approach to the problem. I modified HTML code a little by adding individual id to the buttons.
HTML:
<div id="group1" >
<button id="btn-A">nameA</button>
<button id="btn-B">nameB</button>
<button id="btn-C">nameC</button>
</div>
<hr />
<div id="group2">
<button id="btn-D">nameD</button>
<button id="btn-E">nameE</button>
<button id="btn-F">nameF</button>
</div>
JavaScript:
// click on the button
$(document).on('click','button', function(){
//store the value of the id and
// split it # '-' into array ['btn','A']
$id = $(this).attr('id').split('-');
// store the value at index 1 into $id
$id = $id[1];
//get the Id of the current div group
$divId = $(this).closest('div').attr('id');
//check which div group is current and
//Assign the reversed value as appropriate
if($divId === "group1"){
$addId = "#group2";
}else {
$addId = "#group1";
}
//Remove the button from the group
$(this).remove();
//Add the button to the second div group
$($addId).append('<button id="btn-'+$id+'">'+$(this).text()+'</button>');
});

Jquery: Get the ids of all the check values in a list

I'm using a jquery to add a new checkbox when I click an option from an existing checkbox.
Next I add an id in this checkbox and I get it's value through a new jquery. I want to create a new jquery to get the ids of ALL the extended checked ids.
My current html code is:
<div id="div_id_diag-diagnosis_option" class="form-group">
<label for="id_diag-diagnosis_option_0" class="control-label col-md-3 requiredField">Option<span class="asteriskField">*</span> </label>
<div class="controls col-md-8">
<label class="checkbox">
<input type="checkbox" name="diag-diagnosis_option" id="id_diag-diagnosis_option_1" value="b">b</label>
<label class="checkbox">
<input type="checkbox" name="diag-diagnosis_option" id="id_diag-diagnosis_option_2" value="a">a</label>
<label class="checkbox">
<input type="checkbox" name="diag-diagnosis_option" id="id_diag-diagnosis_option_3" value="c">c</label>
</div>
</div>
The jquery to add the checkbox is:
$("input[name='diag-diagnosis_option']").change(function() {
var $this = $(this);
if ($this.prop('checked')) {
var option = $(this).val();
alert(option);
$(this).parent().append("<a href='#'>here</a>");
} else if ($this.siblings('a').length) {
$this.siblings('a').remove();
}
});
The jquery to get the value of the new checkbox is the one below:
$(document).on('change', '#extended', function () {
var option = $(this).val();
//alert(option);
});
The jquery to get the ids of all the extended checked checkboxes is the one below but it's not working.
var selected = [];
$(document).on('each', '#extended input:checked', function () {
selected.push($(this).attr('id'));
alert(selected);
});
You can test it here.
Can you help me please?
You have incorrect syntax for iterating over checkboxes. You are trying to use each as an event. However each is jquery method and not even associated to element. and correct syntax to use it is:
var selected = [];
$('#extended input:checked').each(function () {
selected.push($(this).attr('name'));
alert(selected);
});
However you can achieve this in cleaner way using .map() along with .get() to achieve this:
var selected = $('#extended input:checked').map(function(){
return $(this).attr('name');
}).get();
EDIT
As you append checkboxes dynamically , you should add values at there change event .. also you have dynamic checkboxes with same id .. you should use class instead of id that is not permitted
Do it as-
var selected = [];
$("input[name='diag-diagnosis_option']").change(function () {
var $this = $(this)
if ($(this).prop('checked')) {
var option = $(this).val();
$(this).parent().append('<label><input type="checkbox" class="extended"
name="extended" value=' + escape($(this).attr('value')) + '>
Extended</label>');
} else if ($this.siblings('label').length) {
$this.siblings('label').remove();
}
});
$(document).on('change', '.extended', function () {
var option = $(this).val(); // or attr('name');
selected.push(option);
alert(selected);
});
LIVE https://jsfiddle.net/mailmerohit5/wt9btcb0/

Categories