Push multiple values into an array in Javascript not working - javascript

I'm trying to push multiple values into an array based on the elements ID.
I expect the outcome to be 3 and 4 but instead I get 1 2 3 4. Why is that the case in the following example?
var myArray = [];
$( '#bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>1</div>
<div>2</div>
<div id="bla">3</div>
<div id="bla">4</div>
</div>

You are seeing the content of the your HTML, and not the console.log.
This is what you need to fix:
Include jQuery
Use class instead of id - there can be only one id in a document, so you'll get only one result
Look at the console
var myArray = [];
$( '.bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>1</div>
<div>2</div>
<div class="bla">3</div>
<div class="bla">4</div>
</div>

First id has to be unique
replace id with class and use your snippet
var myArray = [];
$( '.bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>1</div>
<div>2</div>
<div class="bla">3</div>
<div class="bla">4</div>
</div>

First of all, you can't have two HTML elements with same id attribute. It is unique indeficator, it should be only one on page.
And second, if you are using your js script from external (not inluded between <scritp></script>) you should use (document.ready or in jQuery $(docuemnt).ready(function(){}) [in my case it is short way to do this]), because you don't want to read HTML values before your is not loaded.
(function () {
var myArray = [];
$( '.bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
}());
<div>
<div>1</div>
<div>2</div>
<div class="bla">3</div>
<div class="bla">4</div>
</div>

Related

sum of two changing variables not totally correctly using Jquery

It is easier to see my codepen link: https://codepen.io/ScottFSchmidt/pen/GPWvQP Everything works, but the total of the total of the two variables are not adding up.
Failed attempts. There were 4 major failed attempts that I had (I tried other stuff too). I am wondering if I need to use eval.
$total.text(pizzaPrice.innerHTML+sodaPrice.innerHTML); //returns NAN
$total.text( $sodaTotal + $pizzaTotal); //returns 6 at ALL times, adding one pizza and one soda.
$total.text( $sodaTotal.val + $pizzaTotal.val ); //function (e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&
function sum($pizzaTotal, $sodaTotal) {
$sodaTotal+$pizzaTotal.html($total);
} //won't trigger with sum() but probably not the easiest way.
`
Full Code:
commented stuff out is stuff that did not work:
<script text=type/javascript>
$(document).ready(function(){
var $pizzaOptions = $( '.pizza-options' );
var pizzaPrice = $pizzaOptions.data( 'price' );
var $sodaOptions = $( '.soda-options' );
var sodaPrice = $sodaOptions.data( 'price' );
var $pizzaTotal = $( '.pizza-total' );
var $sodaTotal = $( '.soda-total' );
var $total = $( '.total' );
$total.text(pizzaPrice+sodaPrice);
// $total.text( $sodaTotal.val + $pizzaTotal.val );
function sum($pizzaTotal, $sodaTotal) {
$sodaTotal+$pizzaTotal.html($total);
}
function calculator( $totalEl, price, $options ) {
return function ( e ) {
$totalEl.text( price * $options.find( '[type="checkbox"]:checked' ).length );
};
//$sum=$sum+$totalEl;
//$total.text($sum)
//sum();
}
$pizzaOptions.on( 'click', calculator( $pizzaTotal, pizzaPrice, $pizzaOptions ) );
//$pizzaOptions.on( 'click', sum($pizzaTotal, $sodaTotal);
//// $pizzaOptions.on( 'click', sum();
$sodaOptions.on( 'click', calculator( $sodaTotal, sodaPrice, $sodaOptions ) );
}); //end ready
</script>
Almost every suggested article is using SQL not Jquery. Most of the failed attempt ideas were from suggested articles. Thanks in advance.
Your sum function was never called, and it isn't completely correct.
Change sum to:
function sum() {
$total.text(Number($pizzaTotal.text())+Number($sodaTotal.text()));
}
Here we set the text of $total to $pizzaTotal + $sodaTotal. It would be a lot better to use variable instead of doing it this way.
Change calculator to:
function calculator( $totalEl, price, $options ) {
$totalEl.text( price * $options.find( '[type="checkbox"]:checked' ).length );
}
Now the function will set the text instead of just returning another function.
Lastly change your click listeners to use an anonymous function, calling both calculator and sum:
$pizzaOptions.on( 'click', function() {
calculator( $pizzaTotal, pizzaPrice, $pizzaOptions );
sum();
});
$sodaOptions.on( 'click', function() {
calculator( $sodaTotal, sodaPrice, $sodaOptions );
sum();
});
Now they will also call sum when they're executed.
Here it is all together https://codepen.io/anon/pen/ZVexyP
codepen.io/ScottFSchmidt/pen/GPWvQP?editors=1010
Here is the full length solution:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="order-form">
<div class="pizza-options" data-price="5">
<h2>Pizza</h2>
<label>
<input type="checkbox" value="sausage"> Sausage
</label>
<label>
<input type="checkbox" value="pepperoni" data-price=".5"> Pepperoni
</label>
<label>
<input type="checkbox" value="mushrooms"> Mushrooms
</label>
</div>
<div class="soda-options" data-price="2">
<h2>Soda</h2>
<label>
<input type="checkbox" value="coke"> Coke
</label>
<label>
<input type="checkbox" value="pepsi"> Pepsi
</label>
</div>
<div class="totals">
<p>
<strong>Pizza Total:</strong> <span class="pizza-total"></span>
</p>
<p>
<strong>Soda Total:</strong> <span class="soda-total"></span>
</p>
<p>
<strong>Sub Total:</strong> <span class="subtotal"></span>
</p>
</div>
</form>
Javascript:
var $pizzaOptions = $( '.pizza-options' );
var pizzaPrice = +$pizzaOptions.data( 'price' );
var $sodaOptions = $( '.soda-options' );
var sodaPrice = +$sodaOptions.data( 'price' );
var $pizzaTotal = $( '.pizza-total' );
var $sodaTotal = $( '.soda-total' );
var $total = $( '.subtotal' );
function calculator( $totalEl, price, $options ) {
$totalEl.text( price * $options.find( '[type="checkbox"]:checked' ).length);
}
function sum() {
$total.text(Number($pizzaTotal.text())+Number($sodaTotal.text()));
}
$pizzaOptions.on( 'click', function() {
calculator( $pizzaTotal, pizzaPrice, $pizzaOptions );
sum();
});
$sodaOptions.on( 'click', function() {
calculator( $sodaTotal, sodaPrice, $sodaOptions );
sum();
});

Get child element attribute using Jquery

I have a html structure. I want to get all controltypeid value in a function. I just try like
$('#firstDiv > a.[controltypeid]').each(function (i, val) {
$Control = $(val);
});
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>
but I can't get the value.Can any one help. Thanks in advance for help.
Done using jquery children selector.
Description :Get the children of each element in the set of matched elements.
Code :
$(document).ready(function(){
$("#firstDiv").children('a[controltypeid]').each(function(){
alert($(this).attr('controltypeid'))
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>
You could also use simply like this
$('#firstDiv a').each(function () {
alert($(this).attr('controltypeid'));
});
Try this if you need your controltypeid in a array:
var controltypeid = [];
$('#firstDiv > a[controltypeid]').each(function (i, v) {
controltypeid.push($(v).attr( "controltypeid" ));
});
console.log(controltypeid);
Did everyone forget about .map?
Example:
var controlTypeIds = $('#firstDiv').children().map(function() {
return $(this).attr('controltypeid');
}); // ['1', '2', '3']
Or, if you want to continue using your selector, remove the extra .. The . selector selects class, but having a attribute selector right after it .[...] makes no sense and is not syntactically correct.
var controlTypeIds = $('#firstDiv>a[controltypeid]').map(function() {
return $(this).attr('controltypeid');
}); // ['1', '2', '3']
a.[controltypeid] is wrong and is replaced by a[controltypeid]
secondly, use attr() to get the attribute value.
$('#firstDiv > a[controltypeid]').each(function () {
console.log( $( this ).attr( "controltypeid" ) );
});
if you just want to get all the values in a string
var controltypeids = [];
$('#firstDiv > a[controltypeid]').each(function () {
controltypeids.push( $( this ).attr( "controltypeid" ) );
console.log( $( this ).attr( "controltypeid" ) );
});
alert( controltypeids.join( "," ) );
You can get following way using JQuery. using attr
Make following changes in Jquery.
$('#firstDiv > a').each(function () {
alert($(this).attr('controltypeid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>

jQuery selectable serialize into an array

I have a selectable:
<ol id="selectable">
<li class="ui-widget-content">1</li>
<li class="ui-widget-content">2</li>
<li class="ui-widget-content">3</li>
</ol>
I want to capture every selected item body into a hidden input separated by a comma, so after selecting some items it would look for example like this:
<input type="hidden" id="bad_times" name="bad_times" value="1,3" />
where 1,3 are bodies of the items selected. Any examples from the web I tried failed to work. Please note that only selected items have to be captured, if I select some item, then unselect, then select again it should appear only once. How to achieve it?
Following assumes that jQuery UI selectable plugin is being used
If so you can try something like this and build on it
$(function() {
$("#selectable").selectable({
filter: "li" ,
unselected:mapSelected,
selected:mapSelected
});
});
function mapSelected(event,ui){
var $selected = $(this).children('.ui-selected');
var text = $.map($selected, function(el){
return $(el).text()
}).join();
$('#bad_times').val(text)
}
DEMO
What have you tried so far and where were you running into issues?
Based on the docs the selected items have the class 'ui-selected'
So you should just be able to iterate over the selected items something like:
var str = "";
$( ".ui-selected").each(function(i) {
if (i > 0)
str += ",";
str += $(this).text();
});
$('#bad_times').val(str);
I would be in favor of using a data attribute, say, data-value and using an array, [1,3], instead of a list 1,3.
Special Note: The demo and code below simply help to verify the concept and do not use the selectable plugin.
HTML:
<input type="hidden" id="bad_times" name="bad_times" data-value="[]" />
JS:
$(function() {
var hidden = $('#bad_times');
$('#selectable li').on('click', function() {
var val = +$(this).text();
hidden.data()['value'].indexOf(val) > -1 || hidden.data()['value'].push(val);
console.log( hidden.data()['value'] );
});
});
$(function() {
var hidden = $('#bad_times');
$('#selectable li').on('click', function() {
var val = +$(this).text();
hidden.data()['value'].indexOf(val) > -1 || hidden.data()['value'].push(val);
$('pre.out').text( JSON.stringify( hidden.data()['value'] ) );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="selectable">
<li class="ui-widget-content">1</li>
<li class="ui-widget-content">2</li>
<li class="ui-widget-content">3</li>
</ol>
<input type="hidden" id="bad_times" name="bad_times" data-value="[]" />
<pre class="out"></pre>

exclude the first string from being appended to a character

FIDDLE Example
I'm learning how to append all the data attributes from div.query elements to a url string: http://web.com?get=
With the script I can get this result:
"http://web.com?get=|Africa|Asia|Europe"
But is there any way not to have the first one coupled with "|" so that the url should be
"http://web.com?get=Africa|Asia|Europe"
I want to get that result because either http://web.com?get=|Africa|Asia|Europe
or http://web.com?get=Africa|Asia|Europe| would be invalid. Any suggestions?
JS:
$( document ).ready(function() {
$(".query").each(function() {
var div_terms = $(this).data('term'),
source = $('#main').data('source');
var x = source+'|'+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
HTML:
<div id="main" data-source="http://web.com?get="></div>
<div class="query" data-term="Africa"></div>
<div class="query" data-term="Asia"></div>
<div class="query" data-term="Europe"></div>
<div class="result"></div>
The easiest way is to pull all the countries to an array and join them using the pipe character.
var terms = $('.query').map( function() {
return $(this).data('term');
}).get().join('|');
var source = $('#main').data('source');
$('.result').html( source + terms );
Demo
http://jsfiddle.net/cHtT6/3/
You just need to replace the first '|' in the resulting url with an empty character ''.
Make it simple use javascript join function
$( document ).ready(function() {
var terms=[];
$(".query").each(function() {
var div_terms = $(this).data('term');
terms.push(div_terms);
});
var x = $('#main').data('source')+terms.join("|");
$('.result').html(x);
});
Fiddle here
Use an if statement to check if it's the first 'data-term'. If it is then don't use the | character. Then in the else statement you just do as you've already done
DEMO
Just Check whether end is reached like this:
$( document ).ready(function() {
var i=0;
$(".query").each(function() {
i++;
var div_terms = i==$(".query").length? $(this).data('term')+"":$(this).data('term')+"|",
source = $('#main').data('source');
var x = source+''+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
Here when last term is reached. Automatically only "" is appended in all other cases "|" is appended.

How to find the deepest child of a div with jquery

I'm trying to find the deepest element in the specified divwith jquery. But the code which used is producing the error TypeError: parent.children is not a function.
I found this code from this link
the code is :
function findDeepestChild(parent) {
var result = {depth: 0, element: parent};
parent.children().each( //Here I getting the error TypeError: parent.children is not a function
function(idx) {
var child = $(this);
var childResult = findDeepestChild(child);
if (childResult.depth + 1 > result.depth) {
result = {
depth: 1 + childResult.depth,
element: childResult.element};
}
}
);
return result;
}
---------------------------------------------------------------------------------------
$(document).on('keypress','#sendComment', function(e) {
if(e.keyCode==13){
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
alert(item);
}
});
And my divs are :
<div id="S04" class="snew" style="display: block;">
<div class="author-image"></div>
<span>xyz shared the image xyz</span>
<div class="s-content">
<div class="s-message"></div>
<div class="shpicture">
<img class="SharedImage" width="100%" height="100%" data-shareid="1" data-alid="1" data-id="1" alt="xyz" src="data:image/jpeg;base64,">
</div>
</div>
</div>
<div class="SPcommentbox">
<div class="comment">
<div class="commenter-image"></div>
<div class="addcomment">
<input class="commentbox" type="text" placeholder="Write a comment...">
</div>
</div>
</div>
I need to find the img from these.
please anyone help me .... Thanks ...
To get the deepest nested elements, use
$("#" + parent).find("*").last().siblings().addBack()
http://jsfiddle.net/6ymUY/1/
you can then get the id data attribute with
item.data("id")
http://jsfiddle.net/6ymUY/2/
full code:
function findDeepestChild(parent) {
return $("#" + parent).find("*").last().siblings().addBack();
}
var item=findDeepestChild("S04");
console.log(item)
console.log(item.data("id"));
You're calling it with a string, but it's expecting a jQuery instance.
Instead of
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
you probably want
var item=findDeepestChild($('#findbefore').prev('.snew'));
You are passing in itemId, which is the ID attribute of a given element. I think what you meant to pass was the element itself. Just remove the attr call, leaving this:
var item = findDeepestChild($("#findbefore").prev(".snew"));

Categories

Resources