I am looking to add/remove input items from a hidden div that have a matching value from an array. The array by default is empty, but a value is added to it when an li item is clicked. I would like to be able to remove the input item that corresponds to the value that is currently in the array.
Currently my code works, if you delete the items in the same order you've added them. I am looking to have this function where you can remove and add any input in any order. Can someone help me out?
Below is my js:
var downloadArray = [];
var addToArray = function addToArray(src){
downloadArray.push(src);
//If the input value matches the download Array, remove it
if (downloadArray == $('.result input').attr("value")) {
$('input[value="' + downloadArray + '"]').remove();
console.log(downloadArray);
//Empties array
downloadArray = [];
} else {
//Attaches value to array
var result = '<input type="hidden" class="hiddenValue" name="asset[]" value="' + downloadArray + '" />';
$('.result').append(result);
console.log(downloadArray);
//Empties array
downloadArray = [];
}
};
and below is my html:
<form action="compare_arrays_in_dir.php" method="post">
<ul>
<li class="add" onclick="addToArray('file1.psd');"><span>Add File 1</span></li>
<li class="add" onclick="addToArray('file2.psd');"><span>Add File 2</span></li>
<li class="add" onclick="addToArray('file3.psd');"><span>Add File 3</span></li>
</ul>
<div class="result" id="result"></div>
<input type="submit" name="submit" value="Submit" />
</form>
UPDATE: Here is a working JSFiddle
first your code and naming is very confusing, so I changed it a little.
Here is the JS code:
var resultsArray = [];
function toogleInResults(src) {
// Try to find src in array
var idx = resultsArray.indexOf(src);
//If it is already there, remove it
if (idx >= 0) {
$('input[value="' + src + '"]').remove();
resultsArray.splice(idx, 1);
} else {
// Add the corresponding html for this src
var result = '<input class="hiddenValue" name="asset[]" value="' + src + '" />';
$('.result').append(result);
// Add src to the array
resultsArray.push(src);
}
};
And the modified HTML:
<form action="compare_arrays_in_dir.php" method="post">
<ul>
<li class="add" onclick="toogleInResults('file1.psd');"><span>Add File 1</span></li>
<li class="add" onclick="toogleInResults('file2.psd');"><span>Add File 2</span></li>
<li class="add" onclick="toogleInResults('file3.psd');"><span>Add File 3</span></li>
</ul>
<div class="result" id="result"></div>
</form>
This is very basic so I suggest you to study more about js/html/jQuery (if this is not for study purposes already). Have a nice day!!
And here is a working JSFiddle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.