Multiple identical forms sharing same classes - javascript

I'm a total newbie to JS/jQuery, so please, be gentle with me :).
Here is the problem i encounter on jsfiddler.net :
http://jsfiddle.net/_Arn__/n3oakxhd/2/
I have several identical forms on the same page, which sharing the same classes and the same structure, but with different numerical values.
I've make a little script to do the math (a simple addition), but when i run the script, only the values of the first form are calculated, and results displayed on other forms are the one from the first one.
Is it possible to keep the same structure and to have specific results displayed for each form ?
$( 'form' ).each(function(){
var ligne_somme_1 = parseFloat($( ".ligne_somme_1" ).text());
var ligne_somme_2 = parseFloat($( ".ligne_somme_2" ).text());
var ligne_somme_3 = parseFloat($( ".ligne_somme_3" ).text());
var total= ligne_somme_1 + ligne_somme_2 + ligne_somme_3 ;
var afficheTotal = $( ".ligne_somme_4" );
$( afficheTotal ).text( total) ;
});
<form class="Aform">
<li class="total_ligne_01 lignes">
<div class="ligne_somme_1 lignes_somme">5$</div>
</li>
<li class="total_ligne_01b lignes">
+ <div class="ligne_somme_2 lignes_somme">5$</div>
</li>
<li class="total_ligne_03 lignes">
+ <div class="ligne_somme_3 lignes_somme">5.5$</div> =
</li>
<li class="total_ligne_04 lignes">
<div class="ligne_somme_4 lignes_somme"></div>
</li>
</form>
<hr />
<form class="Aform">
<li class="total_ligne_01 lignes">
<div class="ligne_somme_1 lignes_somme">10$</div>
</li>
<li class="total_ligne_01b lignes">
+ <div class="ligne_somme_2 lignes_somme">10$</div>
</li>
<li class="total_ligne_03 lignes">
+ <div class="ligne_somme_3 lignes_somme">10$</div> =
</li>
<li class="total_ligne_04 lignes">
<div class="ligne_somme_4 lignes_somme"></div>
</li>
</form>
Thank you for reading.
Arn

You should use $(this) reference inside each to reference current form:
$('form').each(function() {
var $this = $(this); // Caching
var ligne_somme_1 = parseFloat($this.find(".ligne_somme_1").text());
var ligne_somme_2 = parseFloat($this.find(".ligne_somme_2").text());
var ligne_somme_3 = parseFloat($this.find(".ligne_somme_3").text());
var total = ligne_somme_1 + ligne_somme_2 + ligne_somme_3;
$this.find(".ligne_somme_4").text(total);
});
Demo: https://jsfiddle.net/tusharj/n3oakxhd/3/
Thanks to #plalx:
$('form').each(function() {
var $lines = $(this).find('.lignes_somme'),
total = 0;
$lines.filter(':not(:last)').each(function() {
total += parseFloat(this.textContent);
});
$lines.last().html(total);
});
Demo: https://jsfiddle.net/tusharj/n3oakxhd/4/

Related

How to make jQuery sorting work with more characters?

I have the following script to sort with data attribute
HTML:
<ul id="list">
<div>
<button id="sort" type="button">Sort</button>
</div>
<li class="items" data-sort="1111111111.1111145000">2</li>
<li class="items" data-sort="1111111111.1111144000">1</li>
</ul>
JS:
$( document ).ready(function() {
var $wrapper = $('#list');
$( "#sort" ).click(function() {
$wrapper.find('.items').sort(function (a, b) {
return +a.getAttribute('data-sort') - +b.getAttribute('data-sort');
})
.appendTo( $wrapper );
});
});
Fiddle: https://jsfiddle.net/vnk91or8/1/
The problem is that it seems that the maximum number of characters that can be sorted is 21. As soon as I remove one of the digits from data-sort attribute in this example, everything works.
My script sometimes generates more than that, 22-25 characters and that's something I can't change. Is there a way to make this work with more characters?
I would suggest you split numbers and than compare, this way:
var $wrapper = $('#list');
$("#sort").click(function() {
$wrapper.find('.items').sort(function(a, b) {
var splitA = $(a).data('sort').split('.');
var splitB = $(b).data('sort').split('.');
return splitA[0] == splitB[0] ? splitA[1] - splitB[1] : splitA[0] - splitB[0];
}).appendTo($wrapper);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li class="items" data-sort="1111111111.1111145000">2</li>
<li class="items" data-sort="1111111111.1111144000">1</li>
</ul>
<div>
<button id="sort" type="button">Sort</button>
</div>
Also on JSFiddle

How to select phone number and contact from html element using jQuery?

I want to select phone number and contact name from html form and not able to select it with my code. I don't know what is wrong?
<ul class="contact-list">
<li>
<div class="phone">0128685665</div>
(Mike Lau)
</li>
<li>
<div class="phone">0242342354</div>
(John Son)
</li>
<li>
<div class="phone">012343534</div>
(Sam)
</li>
</ul>
and here is my code
var contact=[];
$('.contact-list').eq(0).find('li').find('.phone').each(function (i,elem){
contact.push($(elem).text().replace(/[A-Za-z\s]+/,'').trim());
});
for(var i=1;i<contact.length;i++){
console.log(contact[i]);
}
How can I select all phone numbers and contact names? Thanks in advace
$(".phone").each(function(){
var name = $(this).parent().clone().children().remove().end().text();
var phonenumber = $(this).text();
contact.push({name: name, phoneNumber: phonenumber});
});
console.log(contact);
created this fiddle for you
var contact=[];
$('.contact-list li ').each(function (i,elem){
contact.push( {
phone : $( this ).find('.phone').html(),
contact : $.trim( $( this ).clone().children().remove().end().text() ),
} );
});
for(var i=0;i<contact.length;i++){
console.log(contact[i]);
}
or simply just
$('.contact-list li ').each(function (i,elem){
contact.push( $.trim( $( this ).clone().children().remove().end().text() );
});
i think this is work fine for you.
var contact=[];
$('.contact-list li').each(function (i,item){
contact.push($(item).find(".phone").text().replace(/[A-Za-z\s]+/,'').trim());
});
for(var i=1;i<contact.length;i++){
alert(contact[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<ul class="contact-list">
<li>
<div class="phone">0128685665</div>
(Mike Lau)
</li>
<li>
<div class="phone">0242342354</div>
(John Son)
</li>
<li>
<div class="phone">012343534</div>
(Sam)
</li>
</ul>
You can easily add span or div to names and fetch them into object, later which adds into array.
Please see code for html
var contact=[];
$('.contact-list').eq(0).find('li').each(function (key,value){
var phone = $(value).find('.phone').text().replace(/[A-Za-z\s]+/,'').trim();
var name = $(value).find('.name').text().trim();
contact.push({"name":name,"phone":phone});
});
for(var i=0;i<contact.length;i++){
alert(("name " + contact[i].name) + " and " + "phone " + contact[i].phone);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="contact-list">
<li>
<div class="phone">0128685665</div>
<span class="name"> (Mike Lau)</span>
</li>
<li>
<div class="phone">0242342354</div>
<span class="name">(John Son)</span>
</li>
<li>
<div class="phone">012343534</div>
<span class="name">(Sam)</span>
</li>
</ul>
You can also will need onload function or ondocumentready so your code runs as soon as page loads, or when you perform some action it will be triggered.
You should include the names in a separate tab as well. Some thing like this:
<ul class="contact-list">
<li>
<div class="phone">0128685665</div>
<div class="name">(Mike Lau)</div>
</li>
<li>
<div class="phone">0242342354</div>
<div class="name">(John Son)</div>
</li>
<li>
<div class="phone">012343534</div>
<div class="name">(Sam)</div>
</li>
</ul>
Then you can easily fetch names and phones using jQuery.
This should work, here is a demo jsFiddle.
jQuery
// array list of contacts:
var contacts = [];
// contact class:
function contact(name, phone) {
this.name = name,
this.phone = phone
}
// retrieve contact info from the DOM:
$('.contact-list li ').each(function(index, element) {
var phone = $(this).find('.phone').text();
var name = $.trim($(this).children().remove().end().text());
var person = new contact(name, phone);
contacts.push(person);
});
// view all contacts in array list:
for (var i = 0; i < contacts.length; i++) {
console.log(contacts[i].name, contacts[i].phone);
}

Add data-attribute to appended object src

I would like to append a link to multiple list-items that passes the data-attribute to the end of the URL. However I don't understand how to make the variable "storyId" hold a different value for each instance of .Story
<div id="InnerPage">
<ol>
<li class="Story" data-id="35213">Text for Link 1 </li>
<li class="Story" data-id="35204">Text for Link 2 </li>
</ol>
</div>
<script>
var storyId = this.getAttribute('data-id');
var sidebarURL = "'index.html?storyid=' + storyId"
var newA = document.createElement('a');
newA.setAttribute('href',sidebarURL);
newA.innerHTML = "Split View";
$('.Story').append([newA]);
</script>
Should result in:
<div id="InnerPage">
<ol>
<li class="Story" data-id="35213">Text for Link 1 Split View</li>
<li class="Story" data-id="35204">Text for Link 2 Split View</li>
</ol>
</div>
http://jsfiddle.net/s3wtsxw5/
You can do:
$("#InnerPage ol li").each(function() {
var id = $(this).data("id");
var link = "index.html?storyid=" + id;
$(this).append("<a href='" + link + "'>Split View</a>");
});

How to get width of first level list elements with jQuery

I have this markup:
<div class="cntr">
<ul>
<li class="frst_lvl" style="width: 125px;">
<ul>
<li class="scnd_lvl" style="width: 25px;"></li>
<li class="scnd_lvl" style="width: 25px;"></li>
<li class="scnd_lvl" style="width: 25px;"></li>
</ul>
</li>
<li class="frst_lvl" style="width: 125px;"></li>
<li class="frst_lvl" style="width: 125px;"></li>
<li class="frst_lvl" style="width: 125px;"></li>
</ul>
</div>
I need to get combine width of all elements with class frst_lvl. I use this function but .each() method gets the width of all elements, even those of the second degree - scnd_lvl. How to write this correctly?
var t = 0,
$cntr = $('.cntr'),
$list = $cntr.find('> ul'),
$list_el = $list.find('> li');
function listWidth() {
var total = t;
$list_el.each(function() {
total += parseInt($(this).width());
});
return total;
}
$list.width(listWidth());
Thx, for help.
This will give you the combined width of all elements with class frst_lvl
$( document ).ready(function() {
$width = 0;
$( ".frst_lvl").each(function( index ) {
$width += parseFloat($(this).width());
}); alert($width);
});
$.find will give you back every descendant that match. In your example $list contains two list and $list_el contains 7 items.
Use $.children method instead. That travels only a single level down in the DOM
$list = $cntr.children('> ul'),
$list_el = $list.children('> li');
see the docs here: http://api.jquery.com/children/

jQuery append() and data()

I have unknown number of divs with increasing ID's:
<div id="source-1" data-grab="someURL"/>Content</div>
<div id="source-2" data-grab="anotherURL"/>Content</div>
<div id="source-3" data-grab="anddifferentURL"/>Content</div>
<div id="source-4" data-grab="andthelastoneURL"/>Content</div>
And I have another list:
<ul>
<li id="target-1" class="target"> </li>
<li id="target-2" class="target"> </li>
<li id="target-3" class="target"> </li>
<li id="target-4" class="target"> </li>
</ul>
Now, what I want to achive is grabbing data-grab URL from source-1 and append it to target-1 as a image and so forth. So finally the output list will look just like:
<ul>
<li id="target-1"><img src="someURL" /> </li>
<li id="target-2"><img src="anotherURL" /> </li>
<li id="target-3"><img src="anddifferentURL" /> </li>
<li id="target-4"><img src="andthelastoneURL" /> </li>
</ul>
I'm grabbing all the data from the first list, but I'm not sure how to append right source element to right target element?
$(document).ready(function(){
$('.target').each(function(){
var URL = jQuery(this).data('grab');
});
});
$(document).ready(function(){
$('.target').each(function(){
var $this = $(this);
var divID = "source-" + ($this.id()).split("-")[1];
$("a", $this).append('<img src="' + $(divID).data("grab") + '" />');
});
});
You can use indices to select the right elements, if you add a class to your source elements (like .source):
$(document).ready(function(){
var targets = $( '.target' );
$('.source').each(function(index, value){
$(target[index]).children("a").first().append($("<img src=" + value.data('grab') + " />"));
});
});

Categories