Good morning Stack Overflow,
This will be my first question and I am still learning coding, so please forgive me if I'm ever being naive.
I am currently working on a modal that the user is shown when they're trying to pick quantities of a certain product from a warehouse that has been stored in multiple locations.
The user is given a requested quantity and the drop down menu shows each of the possible locations that they can retrieve an item from. The user will then select the location using the select menu and then adjust the slider with the amount they want to take from that location.
If the user wants to split the requested amount across multiple locations however, they will click the "Pick Another Location" button and another row containing the select menu will appear directly underneath. The user will be able to do this until the total picked has reached the Quantity Requested or until they run out of locations to pick from. My problem is, I am trying to remove the location the user selected prior to clicking the "Pick Another Location" button.
As you can see the same location appears again in the appended menu. I would like to have it so it doesn't. Its turning out to be quite difficult for me because each location picker has a unique ID that is created with a variable and I find it difficult to implement that into any types of condition usually.
I had a similar issue with the Quantity slider, as I was trying to treat each slider individually, but also contribute as a collective. Anyway, starting to get off topic and ramble.
I will show below the code which I feel may help...
Initial creation and variables declared:
//Multiple Location PopUp Function
jQuery.LocPick = function LocPick(id){
//Function Post
$.post(base_url+"ts/TestedQtyMultiLoc/", {
ID: id,
BatchID: $("#BatchID").val()},
//Calling variables to be displayed within the PopUp
function(data){
QtyReq = data.item.QtyRequested;
var code= data.item.ItemCode;
rowCount = $('#AddLocationPicker tr').length;
loc='';
$.each(data.Locations, function(i, value) {loc +='<option value="'+ value.Location + '">' + value.Location + ' -- Qty: ' +value.Qty +'</option>';
})
Picker=0;
This is the code for the HTML contents of my modal:
//PopUp Contents
$("#dialog-ProcessConfirm").html('<p>'+code+' has multiple locations<br><br>Please confirm which locations the item is to be picked from before continuing.</p><p><table id="AddLocationPicker"><tr><td></td><td>Location</td><td>Qty Picked</td></tr><tr id="' + Picker +'"><td></td><td><select class="selectbox" id="LocationPickerSelect'+ Picker +'"><option value="0">Please select a location'+loc+'</option></select></td><td><input class= "QtyPicker" id="AddLocQtyPick'+ Picker +'"type="number" min="1" max='+QtyReq+' value="1" onkeydown="return false"></td></tr></table><table><td></td><td>Quantity Requested:</td><td>'+QtyReq+'</td></table><table><td></td><td><input type="text" name="LocErr" id="LocErr" maxlength="50" size="50" tabstop="false" readonly="true" style="border:0px;color:#FF0000;" value=""><input type="text" name="QtyErr" id="QtyErr" maxlength="50" size="50" tabstop="false" readonly="true" style="border:0px;color:#FF0000;" value=""></td></table></p>');
}, "json");
The "Pick Another Location Button":
//Buttons for the PopUp
buttons: {
'Pick Another Location': function() { //Button to allow user to add another location to pick from
$('#AddLocQtyPick'+Picker).prop ('disabled', true); //Disables the current selection, so that it cannot be edited
$('#LocationPickerSelect'+ Picker).prop ('disabled', true); //Disables the current selection, so that it cannot be edited
Picker++; //Adds Unique Number to the ID of the input fields
//For Loop that helps to total up the quantities being selected in each picker
total=0;
for (i = 0; i<Picker; i++) {
total= total + $('#AddLocQtyPick'+i).val() * 1.0;
}
QtyReqTot= QtyReq - total; //Variable decides max value of pick on appends using previous selection
What gets appended:
//The Location/Quantity Picker that gets appended
var appendTxt = '<tr id="' + Picker + '"><td></td><td><select class= "selectbox" id="LocationPickerSelect'+ Picker +'"><option value="0">Please select a location'+loc+'</option></select></td><td><input class= "QtyPicker" id="AddLocQtyPick'+ Picker +'" type="number" min="1" max='+QtyReqTot+' value="1" onkeydown="return false"></td></tr>';
I didn't know if I could use the same sort of technique in using For Loops to use with the incrementing IDS that the Location Picker has, like I did with the Quantity slider as I've seen some examples that suggest this whilst others have said to never use loops in this situation.
My main issue boils down to how I can select an option in one unique menu and remove that option from another unique menu that has the same options.
I'll thank you now for any input/advice received and for patience in my abilities!
EDIT: Problem Solved
The problem I was having did involve trying to take the unique ID's into consideration when writing my syntax. Confirmation for the use of a for loop allowed me to compare with my previous loop I created when totalling the picker quantities.
//For Loop that removes previously selected locations from the append
for (i = 0; i<Picker; i++) {
LocSelect= $('#LocationPickerSelect'+i).val();
$('#LocationPickerSelect'+Picker+' option[value="'+LocSelect+'"]').remove();
}
I will suggest to go with following approach:
Instead of simply adding all the <option> to each select box like below:
$.each(data.Locations, function(i, value) {loc +='<option value="'+ value.Location + '">' + value.Location + ' -- Qty: ' +value.Qty +'</option>';
})
Go for following code which check; which all <option> are already been selected by end user. And adds only those which are unused previously.
var prevSelectedLoc = [];
if(Picker > 0)
{
for(i=0;i<Picker;i++)
{
prevSelectedLoc.push($("select#LocationPickerSelect"+i).val());
}
}
$.each(data.Locations, function(i, value) {
if($.inArray(value.Location,prevSelectedLoc) == -1)
{
//if current option has not been previously selected then only add it to current select box
loc +='<option value="'+ value.Location + '">' + value.Location + ' -- Qty: ' +value.Qty +'</option>';
}
});
The problem I was having did involve trying to take the unique ID's into consideration when writing my syntax. Confirmation for the use of a for loop allowed me to compare with my previous loop I created when totalling the picker quantities.
//For Loop that removes previously selected locations from the append
for (i = 0; i<Picker; i++) {
LocSelect= $('#LocationPickerSelect'+i).val();
$('#LocationPickerSelect'+Picker+' option[value="'+LocSelect+'"]').remove();
}
Related
I have a list of products, each individual product has a checkbox value with the products id e.g. "321". When the products checkbox is checked (can be more than 1 selected) i require the value to be collected. Each product will also have a input text field for defining the Qty e.g "23" and i also require this Qty value to be collected. The Qty text input should only be collected if the checkbox is checked and the qty text value is greater than 1. The plan is to collect all these objects, put them in to a loop and finally turn them in to a string where i can then display the results.
So far i have managed to collect the checkbox values and put these into a string but i'm not sure how to collect the additional text Qty input values without breaking it. My understanding is that document.getElementsByTagName('input') is capable of collecting both input types as its basically looking for input tags, so i just need to work out how to collect and loop through both the checkboxes and the text inputs.
It was suggested that i use 2 if statements to accomplish this but i'm new to learning javascript so i'm not entirely sure how to go about it. I did try adding the if statement directly below the first (like you would in php) but this just seemed to break it completely so i assume that is wrong.
Here is my working code so far that collects the checkbox values and puts them in a string. If you select the checkbox and press the button the values are returned as a string. Please note nothing is currently appended to qty= because i dont know how to collect and loop the text input (this is what i need help with).
How can i collect the additional qty input value and append this number to qty=
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '/urlcheckout/add?product=', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + input_obj[i].value + '&qty=' + '|';
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
}
else {
alert('There is no checked checkbox');
}
}
<ul>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="311">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="321">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="98">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="javascript:checkbox_test()">Add selected to cart</button>
My answer has two parts: Part 1 is a fairly direct answer to your question, and Part 2 is a recommendation for a better way to do this that's maybe more robust and reliable.
Part 1 - Fairly Direct Answer
Instead of a second if to check for the text inputs, you can use a switch, like so:
var boxWasChecked = false;
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
switch(input_obj[i].type) {
case 'checkbox':
if (input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
boxWasChecked = true;
url = url + input_obj[i].value + ',qty=';
} else {
boxWasChecked = false;
}
break;
case 'text':
if (boxWasChecked) {
url = url + input_obj[i].value + '|';
boxWasChecked = false;
}
break;
}
}
Here's a fiddle showing it working that way.
Note that I added variable boxWasChecked so you know whether a Qty textbox's corresponding checkbox has been checked.
Also, I wasn't sure exactly how you wanted the final query string formatted, so I set it up as one parameter named product whose value is a pipe- and comma-separated string that you can parse to extract the values. So the url will look like this:
urlcheckout/add?product=321,qty=10|98,qty=5
That seemed better than having a bunch of parameters with the same names, although you can tweak the string building code as you see fit, obviously.
Part 2 - Recommendation for Better Way
All of that isn't a great way to do this, though, as it's highly dependent on the element positions in the DOM, so adding elements or moving them around could break things. A more robust way would be to establish a definitive link between each checkbox and its corresponding Qty textbox--for example, adding an attribute like data-product-id to each Qty textbox and setting its value to the corresponding checkbox's value.
Here's a fiddle showing that more robust way.
You'll see in there that I used getElementsByName() rather than getElementsByTagName(), using the name attributes that you had already included on the inputs:
checkboxes = document.getElementsByName('checked-product'),
qtyBoxes = document.getElementsByName('qty'),
First, I gather the checkboxes and use an object to keep track of which ones have been checked:
var checkedBoxes = {};
// loop through the checkboxes and find the checked ones
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
counter++;
checkedBoxes[checkboxes[i].value] = 1; // update later w/ real qty
}
}
Then I gather the Qty textboxes and, using the value of each one's data-product-id attribute (which I had to add to the markup), determine if its checkbox is checked:
// now get the entered Qtys for each checked box
for (i = 0; i < qtyBoxes.length; i++) {
pid = qtyBoxes[i].getAttribute('data-product-id');
if (checkedBoxes.hasOwnProperty(pid)) {
checkedBoxes[pid] = qtyBoxes[i].value;
}
}
Finally, I build the url using the checkedBoxes object:
// now build our url
Object.keys(checkedBoxes).forEach(function(k) {
url += [
k,
',qty=',
checkedBoxes[k],
'|'
].join('');
});
(Note that this way does not preserve the order of the items, though, so if your query string needs to list the items in the order in which they're displayed on the page, you'll need to use an array rather than an object.)
There are lots of ways to achieve what you're trying to do. Your original way will work, but hopefully this alternative way gives you an idea of how you might be able to achieve it more cleanly and reliably.
Check the below simplified version.
document.querySelector("#submitOrder").addEventListener('click', function(){
var checkStatus = document.querySelectorAll('#basket li'),
urls = [];
Array.prototype.forEach.call(checkStatus, function(item){
var details = item.childNodes,
urlTemplate = '/urlcheckout/add?product=',
url = urlTemplate += details[0].value + '&qty=' + details[1].value;
urls.push(url)
});
console.log(urls);
})
ul{ margin:0; padding:0}
<ul id="basket">
<li class="products"><input type="checkbox" value = "311" name="item"><input type="text"></li>
<li><input type="checkbox" value = "312" name="item"><input type="text"></li>
<li><input type="checkbox" value = "313" name="item"><input type="text"></li>
</ul>
<button id="submitOrder">Submit</button>
Objective: I have a list of checkboxes that are loaded onto the HTML DOM via JSON and javascript. The checkbox buttons will load onto the page fine but if I use my other function uncheckAllCities(), all of the buttons will disappear from the display, not uncheck them. I am not sure why. It happens for several other actions such as when I ask it to do the calculations the check buttons go missing. Perhaps it has to do with how I added the checkboxes from the JSON to begin with.
Any ideas why the buttons disappear from view?
The following functions generate the checkboxes...
function buildCheckBoxes() {
JSONCities = [ //Build checkbox controls to choose which cities get APIs
{
"CityName": "Bellaire",
"LatLong": "47.1200,-88.4600",
"index": "a",
"checked": "checked"
}, ...(more JSON code)...
},
];
//Form a list of checkboxes from JSON
for (j = 0; j < JSONCities.length; j++) //Need to learn if value may be set in checkbox to return, not just true and false checked
{
loadChk = '<input class="checkboxes_class" type="checkbox" name="checkbox-v-2' + JSONCities[j].index + '" value="' + JSONCities[j].LatLong + '" id="checkbox-v-2' + JSONCities[j].index + '"' + JSONCities[j].checked + '>' + " " + '<label for="checkbox-v-2' + JSONCities[j].index + '">' + JSONCities[j].CityName + '</label>';
locCheckBtn += loadChk;
}
$('#loc1').html(locCheckBtn); // update HTML DOM
}
$(document).ready(function() {
//prepare checkbox buttons on page load.
buildCheckBoxes();
});
function uncheckAllCities() { //stackoverflow.com/questions/14110169/check-uncheck-the-array-of-checkboxes
document.getElementsByClassName("checkboxes_class").checked = false;
}
Playing around with your code I found two problems:
I already mentioned this in a comment: getElementsByClassName returns a collection, not an element, so you should loop over it and set checked = false to each individual element.
By default all html buttons are submit-buttons. Therefore as soon as you click any button the form will be submitted, resulting in the page being refreshed. If you add the type="button" attribute to each button the form won't be submitted when you click on them (e.g. <button type="button">click here!</button>). (Small sidenote: I'm not really sure why the checkboxes don't load after the form has been submitted, but setting the type to button should at least solve your problem so I didn't investigate that any further)
Alright, So basically I got a website that recieves a number of inputs, like lets say name, age, weight...
After all the inputs, the text appears in a text area on the same website.
I need the website to offer the function to add more levels,
for example you click 'add level' and a dynamic new inputs appear that allow you to add more info.
Im facing a problem that when i create a new dynamic div with those inputs, they all have the same id, which wont allow me to print each one individually.
I have this function that prints out the results :
<form id="form" action="#">
<script>
$("#form").submit(function(event) {
event.preventDefault();
$("#template").val()...
</form>
Shortly : I need a way to make a button, that adds a new div with unique id.Inside there will be label inputs, the label will print out on submit.
Hope this is clear enough :)
If I understand your question correctly, this might be a way to do it :
HTML
<button id="addLevelBtn">Add a level</button>
<button id="getResultsBtn">Get results</button>
JS
//on click, add a level
$('#addLevelBtn').on('click',addLevel);
//on click, get results
$('#getResultsBtn').on('click',getResults);
//add the first level on load
addLevel();
function addLevel(){
var nbOfSets = $('.setOfInputs').length;
$('#addLevelBtn').before(
'<div class="setOfInputs" id="set-'+nbOfSets+'">'
+'<p>#set-'+nbOfSets+'</p>'
+'<label for="age">Age: </label>'
+'<input type="text" name="age">'
+'<label for="weight">Weight: </label>'
+'<input type="text" name="weight">'
+'</div>');
}
function getResults(){
var result="";
$.each($('.setOfInputs'),function(){
var id = $(this).attr('id');
var age = $(this).find('[name=age]').val();
var weight = $(this).find('[name=weight]').val();
result += id + ' : age = ' + age + ' , weight = ' + weight + '\n';
});
alert(result);
}
JS Fiddle Demo
I want to implement a search box same as this, at first, just first dropdown list is active once user selects an option from the first dropbox, the second dropdown box will be activated and its list will be populated.
<s:select id="country" name="country" label="Country" list="%{country} onchange="findCities(this.value)"/>
<s:select id="city" name="city" label="Location" list=""/>
Jquery chained plugin will serve your purpose,
https://plugins.jquery.com/chained/
usage link - http://www.appelsiini.net/projects/chained
this plugin will chain your textboxes.
Try this code where based on your needs you have to populate it with your options:
var x;
$('#pu-country').on('change', function () {
if (this.value != '0') {
$('#pu-city').prop('disabled', false);
$('#pu-city').find("option").not(":first").remove();
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
switch (this.value) {
case 'A':
x = '<option value="A.1">A.1</option><option value="A.2">A.2</option><option value="A.3">A.3</option>'
}
$('#pu-city').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
$('#pu-city').prop('disabled', true);
$('#pu-city').val("Choose");
}
});
$('#pu-city').on('change', function () {
if (this.value != '0') {
$('#pu-location').prop('disabled', false);
$('#pu-location').find("option").not(":first").remove();
switch (this.value) {
case 'A.1':
x = '<option value="A.1.1">A.1.1</option><option value="A.1.2">A.1.2</option><option value="A.1.3">A.1.3</option>'
break;
case 'A.2':
x = '<option value="A.2.1">A.2.1</option><option value="A.2.2">A.2.2</option><option value="A.2.3">A.2.3</option>'
break;
case 'A.3':
x = '<option value="A.3.1">A.3.1</option><option value="A.3.2">A.3.2</option><option value="A.3.3">A.3.3</option>'
break;
}
$('#pu-location').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
}
});
I have also set up and a demo to see the functionallity with more options.
FIDDLE
Your code should be something like this:
$(country).change(function(){
var l=Document.getElementByID("country");
for(i=0;i<=l.length;i++)
{
if(l.options[i].selected?)
{
text_array=[HERE YOU NEED TO ADD THE CITIES OF l.options[i].text];
val_array=[HERE YOU NEED TO ADD THE VALUES OF THECITIES OF l.options[i].text];
}
}
var c=Document.getElementByID("city");
c.options.text=[];
c.options.value=[];
//You now should have an empty select.
c.options.text=text_array ;
c.options.value=val_array ;
});
As I don't know, what kind of DB you use, to have the cities connected to their countrys, I can't tell you, what to put into the uppercase text...
Ciao j888, in this fiddle i tried to reconstruct the same system as the site you provided the link
the number of states cityes and locality is less but the concept remains the same
If you want to add a new state you must enter a new html options in select#paese with an id.
Then you have add in obj.citta a property with this id name and an array of cityes for a value.
The same thing for obj.localita where you will create an array of arrays.
The jQuery code you need is
<script type="text/javascript">
$(document).ready(function(){
var obj={
citta:{ //value is the same of option id
albania:['Durres','Tirana'],
austria:['Vienna','innsbruck','Graz'],
},
localita:{//for every city create a sub array of places
albania:[['località Durres1','località Durres 2'],['località Tirana','località Tirana 2']],
austria:[['località Vienna','località Vienna 2'],['località innsbruck','località innsbruck 2'],['località Graz','località Graz 2','località Graz 3']],
}
}
$('#paese').on('change',function(){
$('#località').attr('disabled','disabled').find('option').remove()
var quale=$(this).find('option:selected').attr('id')
var arr=obj.citta[quale]
if(arr){
$('#citta').removeAttr('disabled')
$('#citta option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#citta')
}
}
})
$('#citta').on('change',function(){
var ind=($(this).find('option:selected').index())-1
var quale=$('#paese').find('option:selected').attr('id')
var arr=obj.localita[quale][ind]
if(arr){
$('#località').removeAttr('disabled')
$('#località option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#località')
}
}
})
})
</script>
If this solution does not suit your needs, i apologize for making you lose time.
Hi i have done this for license and its dependent subject in yii 1.
The license dropdown
//php code
foreach($subject as $v) {
$subj .= $v['licenseId'] . ":" . $v['subjectId'] . ":" . $v['displayName'] . ";";
}
Yii::app()->clientScript->registerScript('variables', 'var subj = "' . $subj . '";', CClientScript::POS_HEAD);
?>
//javascript code
jQuery(document).ready(function($) {
//subject. dependent dropdown list based on licnse
var ty, subjs = subj.split(';'), subjSel = []; //subj register this varible from php it is
for(var i=0; i<subjs.length -1; i++) { //-1 caters for the last ";"
ty = subjs[i].split(":");
subjSel[i] = {licId:ty[0], subjId:ty[1], subjName:ty[2]};
}
//dropdown license
jQuery('#license#').change(function() {
$('#add').html(''); //clear the radios if any
val = $('input[name="license"]:checked').val();
var selectVals = "";
selectVals += '<select>';
for(var i=0; i<subjSel.length; i++) {
if(subjSel[i].licId == val) {
if(subjSel[i].subjId *1 == 9) continue;
selectVals += '<option value="'+subjSel[i].subjId+'">'+subjSel[i].subjName+'</option>';
}
}
selectVals += '</select>';
$("#subject").html(selectVals);
});
});
You seem to be asking two questions:
QUESTION 1. How to have a disabled select box (the second and third select boxes in the case of your example) which is activated upon the selection of an option from the first select box.
ANSWER 1:
simply use the disabled=true/false as below...
<select id="country" name="country" label="Country" onchange="document.getElementById('city').disabled=false; findCities(this.value)"/>
<select id="city" name="city" label="Location" disabled=true/>
NOTE: I changed "s:select" to "select" on the basis that your question does not make reference or tag the Struts framework that uses this syntax.
QUESTION 2: How to populate the second select box when a selection is made in the first.
ANSWER 2: There are many ways to do this, and the choice depends on where you have the data to populate the lists with. In the case of your Rentalcars example, if you chose Barbados, the browser sends an ajax GET request to "http://www.rentalcars.com/AjaxDroplists.do;jsessionid=5DCBF81333A88F37BC7AE15D21E10C41.node012a?country=Barbados&wrapNonAirports=true" -try clicking on this link and you will see what that request is sending back. This '.do' address is a server side file of a type used with the Struts framework I mentioned above.
A more conventional approach, which would be included in your function findCities(country)would be to send an AJAX request to a PHP script which queries a database and sends back an array of place names to the browser. The AJAX javascript code includes instructions as to what to do with the response. Without knowing more about where you want to store your list, giving an example of this would most likely not be useful.
Alternatively, the whole list of places could be included in the javascript script as an array (as demonstarated by Devima, above), in a text document on the server as comma separated values, or you could save it to a browser database like WebSQL or IndexedDB if offline use would be useful.
When you have got your list, probably as an array of values, you could save the array as a variable eg. var cities=result (in the case of a simple ajax request). You will then need to iterate through cities, for example
for (var i = 0; i < cities.length; i++){
var place=cities[i];//an individual city name
document.getElementById("city").innerHTML+="<option value='" + place + "'>" + place + "</option>";//adds an 'option' with the value being the city name and the text you see being the city name
}
IMO this is the base case AngularJS was designed to completely alleviate. Check it out!
My application successfully creates elements and assigns them different (increasing) IDs.
Now my issue relies when the user deletes these elements (because they have the option to delete as well as create), the consistency of these IDs get broken therefore my application doesn't run well.
This Fiddle represents what I have so far. Just a textbox that appends its value and a few other elements inside a collapsible as many times as the user wants (For some reason my fiddle doesn't increment the alert value, but it works fine on my platform).
SCRIPT (Sorry the txt variable is too long)
$('#Add').click(function () {
if ($("#MedNameStren").val() != "") {
var value = $("#MedNameStren").val();
var noOfMeds = $('#NoOfMedicines').val();
//to check current value
alert(noOfMeds);
var text = '<div data-role="collapsible" data-collapsed="true" data-iconpos="left" data-content-theme="e">' + '<h2>' + desc + '</h2>' + '<div class="ui-grid-a">' + '<div class="ui-block-a" style="width:25%; margin-right:3%;">' + '<input id="quantity' + noOfMeds + '" class="quantity" type="text" placeholder="Quantity" />' + '</div>' + '<div class="ui-block-b" style="width:70%; margin-right:2%;"">' + '<textarea id="directions' + noOfMeds + '" class="directions" cols="40" rows="4" placeholder="Directions given by your GP." ></textarea>' + '</div>' + '</div>' + '<button key="' + vpid + '">Remove</button>' + '</div>';
$("#medListLi").append(text);
$('button').button();
$('#medListLi').find('div[data-role=collapsible]').collapsible();
$('#medListLi li').listview("refresh");
$('#medListLi').trigger("create");
document.getElementById("manuallyName").value = "";
noOfMeds++
$("#NoOfMedicines").val(noOfMeds);
}
else {
alert('Please Provide Medicine Name')
}
});
I am using a counter that neatly increments the ids of quantity and description like:
quantity0
quantity1
quantity2
..and so on, but once the following script is called...
//Deletes colapsible sets (Medicines) from the selected List
$('#medListLi').on('click', 'button', function (el) {
$(this).closest('div[data-role=collapsible]').remove();
var key = $(this).attr('key');
localStorage.removeItem(key);
var noOfMeds = $('#NoOfMedicines').val();
noOfMeds--
$("#NoOfMedicines").val(noOfMeds);
//location.reload();
});
depending on which element (collapsible) is deleted, the IDs stop being consistent. For example if the collapsible with id="quantity1" is deleted then the counter will go back to 1 (currently 2) and on the next addition the respective collapsible will get an id that's already taken, and unfortunately I don't need this to happen.
Maybe I'm making this sound more complicated that it is, but will appreciate any suggestions or ideas to solve this issue (if possible).
If more information is needed, please let me know.
Was brought to my attention that creating and deleting dynamic IDs can be done but keeping up with consistency of these IDs can be very tricky to work around it.
I've solved my own problem by simply creating a function that would keep count of the IDs from the amount of collapsibles inside my list and "renewing" the ID numbers on each Add and Delete.