Subtract 1 from unique concatenated variables - javascript

So I've wrote a script that gives the user the option to add more than one image to a form. If the user chooses to add more than one image, they click the 'Add another image' button, and another file field is added.
When the new file field is added, the id given to that field is unique. The first field is statically set to "1". If the user clicks 'Add another image', the second field is given the id of "2", then another would be "3" etc etc. This has been working successfully.
Note:
I'm not giving them the option to remove the first file field at all.
The issue:
Due to the fact that I want to check that each file field has actually got a file ready for upload, I've decided to add a 'Remove this image' next to each field when the 'Add another image' button is selected.
Ideally, when the user clicks the 'Remove this image' button, the id of the fields after that field are all changed by -1.
EG: The user has inserted five additional file fields using the 'Add another image' button, and they have clicked on the 'Remove this image' button next to the file field with the id of '3', meaning that '4', '5' and '6' should become '3', '4' and '5'.
Edit:
Current functionality:
The id's are being subtracted accordingly, however when a new field is added, it is continuing from the previous count. EG: If file fields '5' and '6' are removed, then another one is added, it is given the id of '7'.
If any of you can help me with this dilemma it'd be much appreciated. It's frying my head a little.
Thanks in advance, Rich
Here are my efforts thus far:
$(document).ready(function() {
var count = 2;
$('#addImage').click(function(){
var countNew = count++;
$('#newsFormContainer #addImage').before( $('<div id="added"><br /><label for="' + countNew + '">Image ' + countNew + '</label class="strong" ><br /><input type="file" class="file" name="' + countNew + '" id="' + countNew + '" accept=".png"></div>'));
$('#newsFormContainer #addImage').before( $('<button id="' + countNew + '" class="file" onclick="return false;">Remove this image</button>'));
$('button.file').click(function(){
var grabClass = document.querySelectorAll('[class^=file]');
console.log(grabClass)
$(grabClass).attr('id', function(index){
return index + 1;
});
$(this).prev('#added').remove();
$(this).remove();
});
var inputs = document.querySelectorAll('[file^=file]').length;
document.getElementById('cnt').value = inputs;
});
});

Try Running this Code; may be this solves your problem
$('#add-item').on('click', function() {
var indexOfLastItem = parseInt($('ul>li:last').attr('data-index'));
if(!indexOfLastItem){
indexOfLastItem = 0;
}
indexOfLastItem += 1;
$('ul').append('<li data-index="' + indexOfLastItem + '">Item ' + indexOfLastItem + '<button>Remove Image</button></li>')
});
/**
* Dynamically assigning event handler
* Other wise it will not work for 'Remove' buttons added in runtime
*
*/
$(document).on('click', 'li> button', function() {
var indexOfLi = $(this).parent().attr('data-index');
var $currentLi = $(this).parents('li');
var $itemsAfterCurrent = $currentLi.nextAll();
console.log($itemsAfterCurrent);
rearrangeItems($itemsAfterCurrent);
$currentLi.hide('slow', function() {
$(this).remove();
})
})
function rearrangeItems($itemsAfterCurrent) {
$itemsAfterCurrent.each(function() {
var index = $(this).attr('data-index');
index = parseInt(index) - 1;
console.log(index);
$(this).attr('data-index', index);
$(this).html('Item ' + index + '<button>Remove Image</button>');
});
}
li{
margin: 5px;
}
li>button{
margin: 0 3px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-index="1">Item 1 <button>Remove Image</button></li>
<li data-index="2">Item 2<button>Remove Image</button></li>
<li data-index="3">Item 3<button>Remove Image</button></li>
<li data-index="4">Item 4<button>Remove Image</button></li>
<li data-index="5">Item 5<button>Remove Image</button></li>
<li data-index="6">Item 6<button>Remove Image</button></li>
</ul>
<button id="add-item">Add Image</button>

You need a loop that checks the id of the deleted picture and the for all pictures with an id greater then the picture being deleted subtract 1 from the value of their id.

Related

Vanilla JS category selector .removeAttribute problem

New on dev and JS following a (apparently) simple tutorial I got stacked in a silly problem, a function that has to select categories just adding or removing attributes.
It adds (and hides) but doesn't remove (and lets appear).
Function:
var showAndHideSongs = function(event, filter) {
// get all songs that match the genre of the filter
var songsByGenre = Array.from(
document.querySelectorAll('#playlist [data-genre="' + filter + '"]')
);
// if checkbox is checked, show songs
// otherwise, hide them
if (event.target.cheched) {
songsByGenre.forEach(function(song) {
song.removeAttribute("hidden");
});
} else {
songsByGenre.forEach(function(song) {
song.setAttribute("hidden", "true");
});
}
};
HTML:
<ol id="playlist">
<li data-genre="pop">
"Thank U, Next" by Arianna Grande
</li>
<li....
Checkboxes are dynamically created:
var renderCheckLists = function(genres) {
app.innerHTML =
"<h2>Filter Songs</h2><h3>By Genre</h3>" +
genres
.map(function(genre) {
var html =
"<label>" +
'<input type="checkbox" checked data-filter="' +
genre +
'" checked>' +
genre +
"</label>";
return html;
})
I tried literally everything but the solution
As I said it removes but looks like if "removeAttibute" doesn't work.
I tried the removeAttribute in a blank test project and actually works perfectly, so the problem is not there
Thanks in advance for the help

Outputting an element when a clicked element's id equals object element

I am trying to display the appropriate input for the correct icon displayed. I structured all of my elements as an object and created the key to match the id of the matching icon. I then created the element to the appropriate input to match.
My issue is, when I click on the icon, nothing outputs. I do not get any errors, my console.log is showing me the looped results.
Does anyone see what I am doing wrong? If you click on the blue Zillow icon, then the input with the placeholder "Zillow" should appear. The same thing with the Realtor one, except it be associated with the Realtor input/icon.
var reviewInputs = {
"zillow-review": '<input type="url" id="zillow-input" placeholder="Zillow">',
"realtor-review": '<input type="url" id="realtor-input" placeholder="Realtor">'
};
$('.review-icon-select').click(function() {
$('#review-site-edit-wrap').addClass('active');
var reviewIconClicked = $(this).attr('id');
$.each(reviewInputs, function(key, element) {
console.log('key: ' + key + '\n' + 'value: ' + element);
if (reviewIconClicked == reviewInputs) {
reviewInputs.forEach(function(site) {
$('#review-site-edit').append.reviewInputs[element];
});
}
});
//$(reviewIconClicked':contains("SomeText")').each(function () {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="review-icon-select" id="zillow-review"><img src="https://s3.amazonaws.com/retain-static/www/zillow.jpg" alt="Zillow"></li>
<li class="review-icon-select" id="realtor-review"><img src="https://s3.amazonaws.com/retain-static/www/realtor.com.png" alt="Realtor.com"></li>
<div id="review-site-edit"></div>
You just need to check if the id of the clicked element is a property of your object.
No loop needed.
var reviewInputs = {
"zillow-review": '<input type="url" id="zillow-input" placeholder="Zillow">',
"realtor-review": '<input type="url" id="realtor-input" placeholder="Realtor">'
};
$('.review-icon-select').click(function() {
//$('#review-site-edit-wrap').addClass('active'); // Maybe used...
var reviewIconClicked = $(this).attr('id');
if(reviewInputs.hasOwnProperty(reviewIconClicked)){
$('#review-site-edit').find("input[type='url']").remove();
$('#review-site-edit').append(reviewInputs[reviewIconClicked]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="review-icon-select" id="zillow-review"><img src="https://s3.amazonaws.com/retain-static/www/zillow.jpg" alt="Zillow"></li>
<li class="review-icon-select" id="realtor-review"><img src="https://s3.amazonaws.com/retain-static/www/realtor.com.png" alt="Realtor.com"></li>
<div id="review-site-edit"></div>
Instead of using
if (reviewIconClicked == reviewInputs) {
try
reviewInputs['reviewIconClicked']

How do i rearrange the number in java script loop?

I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful

Removing elements by id using event Javascript dynamically

I have list of phones thats displaying as ul li. When user clicking button "buy" it creates new li with in another div "ordersDiv" user can delete his purchase from cart by clicking "Remove" And this must remove li with matching id.
Code that creates purchase:
$("#list").delegate("button",'click',function(){
var purchase = {id: null,name: null,price: null };
var purchases = [];
for(var i = 0; i < phones.length; i++){
if(this.id === phones[i].id){
purchase.id = phones[i].id;
purchase.name = phones[i].name;
purchase.price = phones[i].price;
//break;
purchases.push(purchase);
console.log(purchases);
$.each( purchases, function(i, purchase){
purchases.push("<li id='"+ purchase.id +"'>" + purchase.id +
"<br>" + purchase.name + "<br>" + "Price:" +purchase.price + "<br><button id='"+purchase.id+"' type='button' class='btn-default'>remove</button>" +"</li>" );
});
$('#ordersUl').append(purchases);
}
}
});
Code that supposed to remove li:
$("#ordersCartDiv #ordersUl").delegate("button","click", function() {
var buttonId = $(this).attr('id');
console.log(buttonId);
//$("li[id=buttonId]").remove();
$("#ordersUl").remove(buttonId);
console.log("test"); // code indentation
});
Problem is that this code doesn't removes anything.
you must pass a selector in remove function, like this:
$("#ordersUl").remove('#'+buttonId);
Use remove on button id.
$("# " + buttonId).remove();
No need to use ordersUl since id is unique(?).
If you don't have id unique:
$("#ordersUl #" + buttonId).remove(); // Will remove button inside #ordersUl
Remove the set of matched elements from the DOM.
Docs: http://api.jquery.com/remove/
$("#ordersUl").remove("#"+buttonId);
You should call remove function on element
$("li#"+buttonId).remove();
But ID is supposed to be unique, so it is bad idea to use it in this way. Use data- attributes or classes.

how to show list items separately in output using javascript

I have created one html which contains search box. After searching, I'm getting the data in list. But when I click on that I'm getting the value of all list item by using this
var text = $(this).text(); method
In my app, if I click on one item only it should give me only that value of list item not other. I'm making a mistake somewhere, but I don't know where.
Here is my code:
HTML
<ul data-role="listview" class="ui-li-icon">
<li id="list"></li>
</ul>
And here is my JavaScript code:
function successCallback(responseObj)
{
// alert(JSON.stringify(responseObj));
form.reset();
dataj=JSON.stringify(responseObj);
len=dataj.length;
for(i=0;i<len;i++)
{
var output = "<ul>" + responseObj.merchants[i].imageFileName+ " " + "<font size=3 color=green>" + responseObj.merchants[i].merchantName + "</font>" +"</ul>";
$('#list').append(output);
}
$('#list').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
}
So when I'm searching for some a item. I'm getting list of:
ab
abc
But when I clicked on it. I get value of both ab and abc. I just want only one value where I have clicked.
//replace your click event by below code
$('.ui-li-icon li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
$('#list').append(output);
I believer list is the id you are giving to list items i.e.
Now, this will confuse the browser because id should be UNIQUE and here you are giving this id to all the list items.
If you fix this, your problem should be resolved!
Or you could simply attach click event using this
$('.ui-li-icon li').click //Your click event handler
It's very difficult to understand what you are asking. From what I can tell you're looking for something like this:
$('#list li').on('click', function(){
alert("index: "+$(this).index() + " value: "+ $(this).text());
});
Here's a fiddle http://jsfiddle.net/Jw8qz/

Categories

Resources