Replacing/reloading input list with jQuery and leaving first element - javascript

I created jQuery function that gets bunch of simple objects that contains id and title.
Then I run simple loop to create list:
$.each(data['results'], function(key, val) {
items.push('<label for="radio_show_' + val['id'] + '" >'
+ '<input type="checkbox" name="radio_show" class="checkbox" id="radio_show_' + val['id'] + '" value="'+ val['id'] + '" >'
+ val['title']
+ '</label>');
});
But now I don't know how to do the cleaning part.
I want to append this list to certain <ul>, I could do that with .appendTo(), but each time i would call this, it would add more and more lists. So before appending I would need to delete <ul> contains with .empty(). But the main problem is that I want to keep first element that would be same input just with no value and title of "Select all" (You get the idea).

Could you use something like this to 'clear' the ul -
$("ul > li:not(:first)").remove()
That should remove all the items in the ul aprt from the first one.
Working demo - http://jsfiddle.net/zUuE9/

You could clear your ul with:
$('#my_ul input[value!=""]').parent('li').remove();
This would leave your Select All Checkbox (value="") in the ul.

To remove all li's except for the first one, try this:
$('#my-ul li').slice(1).remove();

Related

dynamically edit row using jquery

I am perform add ,edit and delete operation using jquery.
i have create product.html file and jsproduct.js file.
My Question is i am click edit button and change selectbox value and press edit
product button
but select box value can not display table
<script async src="//jsfiddle.net/kishankakadiya/m6sn39hp/1/embed/"></script>
Check Demo
The problem is that you are using the same id for the <td>elements on your table. You are using the counter with this and the result is having more than one <td id="1"> and jQuery will not handle it correctly.
I changed your td's to use a class instead of id and added a class prefix to your td's like this:
'<td class="category-' + this.counter + ' ">' + product_category +'</td>'
'<td class="name-' + this.counter + '">' + product_name + '</td>'
And in your edit function I used the class as a selector:
$(".category-" + this.id).text(product_category);
$('.name-' + this.id).text(product_name);
Then it works correctly. You still have some trouble in setting your mode etc but hopefully you can get those fixed by yourself.
Fiddle: https://jsfiddle.net/ye6mugxe/1/

Check if a HTML element exists before append

I need a way to check if a dynamically created hidden input element exists in the document before appending it.
I know there are similar questions, but my questions differs from them because the other questions seem to be for basic appending of elements with selectors e.g.
if ($('#button').length)
checks if an element with a #button id already exists.
However in my code, as I am dynamically creating input elements, their name value attributes will be different. So I need to if the whole element exists one by one in the loop before I append it. Is there a way to do this in jQuery?
$('input[type=radio]:checked').each(function(){
//Something like this
if($('<input type="hidden" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />').length)
{
$('#addCharacters').append('<input type="hidden" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
}
});
With jQuery, you can use the .is() function to test whether an element/sequence of elements match conditions you specify. This is especially helpful so you don't have to worry about escaping strings. For instance:
$('input:radio:checked').each(function(){
var cur = $(this).val();
if(!$('#addCharacters input:hidden')
.is(function(i,e){ return e.value==cur && e.name=='data['+cur+']'; }))
{
// Append new element
}
});
If you have a lot of radio elements to check, you'll probably want to move the anonymous function somewhere else so it's not created for each radio element that you're checking.
See an expansive example in a mini-guessing game here: https://jsfiddle.net/bv6abj7L/2/
You need to use the multiple and attribute equals selectors:
if($('input[type="hidden"][name="data[' + $(this).val() + '"][value="' + $(this).val() + '"]').length)

Sorting consistency of dynamically created IDs on DOM Elements

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.

Removing checkboxes dynamically added to a div

I am using the following code to dynamically create a set of checkboxes based on user input from dropdown list. It does not delete the previous selections when the user select another option from the dropdown list.
It only deletes the checkboxes but not the description attached to the check box. I am unable to find the error with the code. Appreciate your help.
$(document).ready(function() {
$('#sel_LearnA').change(function(event) {
var $learnA=$("select#sel_LearnA").val();
$.get('actionDataSelect',{LAreaID:$learnA},function(responseJson) {
// remove existing checkboxes
$('#somediv').children().remove();
// add checkboxes to the div
$.each(responseJson, function(index, item) { // Iterate over the JSON array.
$('#somediv').append("<input type='checkbox' value='"+ item.keyCode + "' />" + item.keyCode + "</br>");
});
});
});
});
And my jsp looks like,
<div id="somediv"></div>
.children() gets only the element nodes of the parent, not the text nodes
Try empty()
$('#somediv').empty();
or just .html('')
$('#somediv').html('');
Empty function resets div.
$( "#yourDivId" ).empty();
This is not the error in your code.
The description is not attached to the checkbox.
$('#somediv').append("<input type='checkbox' value='"+ item.keyCode + "' />" + item.keyCode + "</br>");
You are closing the checkbox and the description is given after. So .remove will remove the checkbox, not the description.
Put the checkbox and description inside a label and remove the label.
This will definitely work.
$('#somediv').append("<label><input type='checkbox' value='"+ item.keyCode + "' />" + item.keyCode + "</label></br>");

Self written toc jQuery function: jump to link target and show corresponding element

I generate dynamically a toc for elements of class=faqQuestion.
The answer resides in a class=faqAnswer element which is hidden by default.
By clicking on class=faqQuestion entry it will show up with
$(this).next(".faqAnswer").slideToggle(300);
Everything works as expected.
What I want: by clicking on a toc link i will jump to the target faqQuestion element and show the corresponding faqAnweser element.
The way I generate the toc:
$(document).ready(function(){
var url = window.location.pathname;
$('<ol />').prependTo('#toc')
$(".faqQuestion").each(function(i) {
var current = $(this);
current.attr("id", "entry" + i);
$("#toc ol").append("<li class=\"faqToc\"><a id='link" + i + "' href='" + url + "#entry" +
i + "' entry='" + current.attr("tagName") + "'>" +
current.html() + "</a></li>");
});
This is what I tried, which will jump to the selected faqQuestion but the faqAnswer element is still hidden.
$(".faqToc").click(function(event){
$(this).next(".faqAnswer").slideToggle(300);
});
My problem is this - at least I think so - so I tried something like - which results in "undefined"
var url = $(this).prop("href");
alert(url);
Trying attr instead of prop returns also "undefined".
Can you point out my problem?
I'm trying to improve my Javascript and jQuery know how, so I don't want to use a toc-plugin.
Update: HTML looks like this:
<div id="toc">
<ol>
<li class="faqToc">
...
</li>
<li class="faqToc">
...
</li>
</div>
<p id="entry0" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
<p id="entry1" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
A very simple way would be to use the index() method since relationship between the TOC elements and the question/answer elements is 1 to 1.
$(".faqToc").click(function(event){
var index=$(this).index(); /* zero based index position of element within it's siblings*/
/* toggle answer element with same index */
$(".faqAnswer").eq(index).slideToggle(300);
});
jQuery API Reference : index()

Categories

Resources