Changing a label using JavaScript click event handler - javascript

I am trying to remove a 'Pending' label and want to add a new 'Done' label.
Please find below the code I have written so far. This code works but the Pending label is now along side the Done label. I thought the former can be removed.
$(document).on('click','.pending', function() {
var li_node = $(this).parent();
li_node.append('<span class="label success">Done!</span>');
li_node.remove('<span class="label pending">Pending</span>');
li_node.addClass('completed');
});
Screenshots of my work. Can I get rid of the Pending label and leave only the Done label?
This is the html code: I am following an online tutorial that seems to have been designed for you to have a seasoned JS coach with you;
<div id="container">
<h1>Wish List</h1>
<ol id="items">
<!-- Items will be added here -->
</ol>
<span class="total"></span>
<br/>
<input type="text" id="item"/>
<button id="add-to-list">Add to list</button>
</div>
Something tells me I should be starting a new topic for the addition to this question but that would mean duplicating all the previous code...let me know if I am breaking the rules please.
I don't have an idea how to write a jQuery selector that selects all the pending labels, using the .length property, in the JavaScript console. I am using all the previous codes and this is the screenshot of the list on my browser that I am working with. I need to get the number of pending labels and number of completed labels.

$(document).on('click','.pending', function() {
var li_node = $(this).parent();
li_node.append('<span class="label success">Done!</span>');
li_node.children(".label.pending").remove();
li_node.addClass('completed');
});

Instead of adding and removing things, just change the class and text of the label in place:
$(document).on('click','.pending', function() {
var li_node = $(this).parent();
li_node.children('.label.pending').removeClass("pending").addClass("success").text("Done!");
li_node.addClass('completed');
});

Here is a working solution, I use a $ before the variable
name when it is a jQuery object. If you remove the item after
you get the selector for its parent element. then call remove on $(this) it works.
$(document).on('click', '.pending', function () {
var $li_node = $(this).closest('li');
$(this).remove();
$li_node.append('<span class="label success">Done!</span>').addClass('completed');
});

Related

Can't get to the DOM element

I got voting script on my page (jQuery Raty), everything work's fine but I want to change rate number in my ajax after voting.
Have problem with getting to span class .glosy
My html:
<div class=\"movie__rate\">
<div class=\"score\" data-score=\"$czy_glosowal2[ocena]\" data-user=\"$stat[id]\" data-movie=\"$podobny_film[id]\"></div>
<span class=\"movie__rate-number\">
<span class=\"glosy\">170</span>
głosów</span>
</div>
My JS:
('.score').raty({
click: function(score) {
var licznik_komentarzy = $(this).find('.glosy').text();
var zapisanie_licznika = $(this).find('.glosy').val(licznik_komentarzy);
var dodanie_licznika = +$(this).find('.glosy').val() + 1;
$(this).find('.glosy').text(dodanie_licznika);
}
});
tried different methods (next(), nextAll(), find()) and still cant figure it out.
Assuming that this is actually the element (depends on how plugin is written) ... you are looking in the wrong direction in the DOM tree.
closest() looks up the tree for ancestors.
You would need to use find() to look for a descendant of .score

Getting HTML content using jQuery on click

I've got a simple application that requires a DIV to be clicked, and in turn it shows another DIV which needs to have its content updated.
There are around 40 items that will need to be clickable and show the correct label for each.
Here is what I need to happen...
User clicks a DIV (drag_me)
Information box DIV is then shown (flavour_box)
the default word 'Ingredients' is swapped out with the content from the "flavour_descrip" div
Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
The data comes from a database, so I'm unable to set individual ID's.
I had a similar issue with draggable's, but that was fixed, and I've tried doign somethign similar to no avail.
Here is the clickable DIV (flavour_descrip is set as hidden in the CSS)
<li class="drag_me">
<div>
<img src="RASPBERRY.png" />
</div>
<div class="choc_label">
Raspberries
</div>
<div class="flavour_descrip">
Our description will appear here for the DB
</div>
</li>
Here is the HTML for the popup box...
<div id="flavour_box">
<p class"flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
Here is the jQuery snippet for the click (i've commented out the code I had started to rejig, but essentially I need to change the draggable.find to something that will work!)
$(".drag_me").click(function () {
//var htmlString = ui.draggable.find('.choc_label').html();
//$('.choc2_flavour').text(htmlString);
// update the description of the item
//var htmlString = ui.draggable.find('.flavour_descrip').html();
//$('.flavour_description').text(htmlString);
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
Any ideas how I can achieve this?
Added extra question
Now I've had my problem resolved, I need to perform one more task.
Inside the div that gets the details passed using "this", I need to be able to pass one more items to a different piece of script.
The DIV 'flavour_add' is clickable and will need to grab the flavour name to use to update some bits on screen and update a URL on the fly.
<div id="flavour_box">
<p class="flavour_name_label">Label</p>
<p class="flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
This is the jQuery I have, but using "this" doesn't seem to work
$(".flavour_add").click(function () {
// hide the ingredient box
$("#flavour_box").toggleClass("hidden");
// show the continue box
$("#added_box").toggleClass("visible");
// get the flavour name
var flavourLabel = $(this).find('.flavour_name_label').text();
// update flavour URL
var _href = $("a.to_step_3").attr("href");
$("a.to_step_3").attr("href", _href + '&flavour=' + flavourLabel);
//$("a.to_step_3").attr("href", _href + '&flavour=TestFromAdd');
// update the mixing bowl list with the ingredient
$('.choc2_flavour').text(flavourLabel);
});
Use $(this) to get the reference to the clicked element:
$(".drag_me").click(function () {
var txt = $(this).find('.choc_label').text();
$("#flavour_box > .flavour_descrip").text(txt);
$("#flavour_box").toggleClass("visible");
});
Besides, there was a "typo" in your html code, replace:
<p class"flavour_description">Ingredients</p>
By:
<p class="flavour_description">Ingredients</p>
You can easily achieve this using jQuery.
$(".drag_me").click(function () {
$('.flavour_description').text($('.flavour_descrip').html());
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
I cannot seem to be able to find the divs for step: 4. Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
I will assume that you mean 'flavour_add' in which case the code should look like this:
$('.flavour_add').text($('.choc_label').html());
Try this:
$(document).ready(function() {
var $flavourBox = $('#flavour_box');
var $flavourDesc = $flavourBox.children('.flavour_description');
var $chocFlavour = $flavourBox.children('.choc_flavour');
$('.drag_me').on('click', function() {
var $this = $(this);
$flavourDesc.html($this.children('.flavour_descrip').html());
$chocFlavour.html($this.children('.choc_label').html());
$flavourBox.addClass('visible'); //toggleClass will remove the class if it is there
});
});
get the text by using "this" (the actual clicked element) and then get the child flavour_descrip div
$(".drag_me").click(function () {
$("#flavour_box").show();
$('.flavour_description').text($(this).find('.flavour_descrip').text());
});
then show the flavour_box div and set the value of the div with the flavour_description class

How to remove elements once it was created by jquery

I am new to JQuery, I was wondering why my script is not working. I have been reading through the API and I did exactly what it says but I am still not getting what I was expecting. Please find the script below:
//To infinitely add images
$('.add_upload_image').on('click', function(){
$('.upload_image').append('<input type="file" name="userfile[]"/><br/>');
});
//To remove the last child of the .upload_image
$('.remove_upload_image').on('click', function(){
$('.upload_image input:last-child').remove();
});
So I am sure you understand what I am trying to achieve. But basically, i have a text that says 'click to add more uploads' which is wrapped around with the .add_upload_image then when the user clicks on it, it adds the input element to the div class .upload_image. Works fine. However, when the user clicks on the 'click to remove' which is wrapped in .remove_upload_image and I am aiming at the last child of the .upload_image that is input and it is not removing.
What am I doing wrong here?
Many thanks in advance.
You have to use :last, not :last-child ( the <br> element is the last child ):
$('.remove_upload_image').on('click', function(){
$('.upload_image input:last').remove();
});
You should probably remove the <br> element as well:
$('.remove_upload_image').on('click', function(){
var el = $('.upload_image input:last');
el.add(el.next('br')).remove();
});
FIDDLE
$('.upload_image').last().remove()
This should work.

independently working div in Jquery

I am trying to make an independently working div which has a form inside of it.
I use jquery to calculate the price of a product depending of the user's selections in the form. However the user is able to add multiple items in his 'cart' so the form is duplicated to another div. The problem is that the calculation pattern can't separate these two divs and the calculation will be incorrect. The form is also interactive so it will be generated by the user's input. This is really complex set and renaming every variable by the 'product number' doesn't sound really efficient to me.
I'm kind of stuck here and i don't really know how to solve this problem. I had an idea that what if I put an iframe inside of the div and load my form and its calculation script inside of it, and then use post command to transfer the price of the product to the 'main page' to calculate the total price of all of the products the user wanted.
However it seems that jQuery scripts doesn't work independently inside of these iframes, they still have connection so they broke each other.
i will appreciate any kind of suggestions and help to solve this matter, thank you!
here's the code so far
Heres the body
var productNumber = 1;
<div id="div_structure">
</div>
<button id="newProduct" >Add new product</button><br \>
add new item
<!-- language: lang-javascript -->
$('#newProduct').click(function ()
{
$('<div id="productNo'+productNumber+'">')
.appendTo('#div_structure')
.html('<label onclick="$(\'#div_productNo'+productNumber+'\').slideToggle()">Product '+productNumber +' </label>'+
'<button onclick="$(\'#product'+productNumber+'\').remove()">Remove</button>');
$('<div id="div_product'+productNumber+'" style="display: none;">').appendTo('#product'+productNumber+'');
$('<iframe src="productform.html" seamless frameborder="0" crolling="no" height="600" width="1000">').appendTo('#div_product'+productNumber+'');
productNumber++;
});
it also has a function that allows the user to remove the inserted div.
Here's just few lines from the productform
$(document).ready(function()
{
$('#productCalculation').change(function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
<form id="productCalculation">
<div id="div_productShape" class="product1">
<h1>Select the shape of the product</h1>
<input type="radio" name="productShape" value="r1">R1</input><br \>
<input type="radio" name="productShape" value="r2">R2</input><br \>
<input type="radio" name="productShape" value="r3">R3</input><br \>
</div>
.
.
.
</form>
I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable
There are two problems with this code: You say somewhere "I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable". This is because event handlers are attached to elements that are in the DOM at that specific moment. To get it to work for all elements, use event delegation:
$(document).ready(function()
{
$(document).on( 'change', '#productCalculation', function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
Your other question is "My question in a nutshell: Is there a way to restrict jquery to function only in certain div even though i use the same variable names in the second div ". You can use the this variable to access the element the click was invoked on. From this element you can traverse the DOM if needed, for example with .parent().
$('div').on( 'change', function( e ) {
console.log( $(this).val() );
} );

Autodividers listview with collapsable option

I am working on a listview which has auto dividers based on date it is a very long list & data-autodividers='true' works fine but I want to further improve it by making the listview collapsible on date.
This can be done from back-end using c# (I am working on an asp.net webform mobile website) where I group my list based on Month-Year and make each group collapsible.
But I would love to do it with jQuery as I do for autodivider. I have set up same on jsFiddle.
http://jsfiddle.net/5PnBT/10/
How can I make these auto-divider collapsible using jQuery without doing it from code-behind file (c#)?
I did not see where jquerymobile has this as a build in option.
$(document).on("pageinit", "#page-wrapper", function () {
$("#hp-latest-articles").listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.attr('date');
return out;
}
}).listview('refresh');
});
If I have understood your problem, I think you just have to use the $.mobile.listview.prototype.options.autodividersSelector option. I had a similar problem, so if you need to list them according to the date attribute on the single element, do:
$( document ).on( "mobileinit", function() {
$.mobile.listview.prototype.options.autodividersSelector = function( element ) {
return (element.attr('date'))
};
});
I prepared a jsbin for that: http://jsbin.com/enuwoj/1/edit
There are two solutions to your problem.
Either you use the collapsible list sets on the jQuery Mobile side, then you will be able to reach exactly what you are looking for. You might nee to edit the looks of the element using CSS to make it look like a listview.
http://jsfiddle.net/rc9Gk/
<div data-role="collapsible">
<h3>Title</h3>
<ul><li>Item1</li><li>Item2</li></ul>
</div>
Second solution would be to apply custom event handlers on click event of the listview control. Whenever a click event occurs on a list divider you can hide the following list elements till the next auto-divider. This solution needs a bit of coding. If this solution fits you, I can write that code for you do let me know.
I believe your problem is solved by adding the following to the bottom of your original fiddle
$('.ui-li-divider').click( function(ev ){
var li = $(ev.target).next(':not(.ui-li-divider)');
while ( li.length > 0 ) {
li.toggle();
li = li.next(':not(.ui-li-divider)');
}
});
Here is the updated jsFiddle
Basically, everytime you click a divider, it looks for all following LIs until the next divider and toggles their visibility.
You'll need either <div data-role="collapsible"> or <div data-role="collapsible-set">, depending on if you wanted to group them or not.
If you want them pre-collapsed by default, include the data-collapsed="true" attribute as well.

Categories

Resources