I'm sorry I can't be any more specific - I have no idea where the problem is. I'm a total beginner, and I've added everything I know to add to the coding, but nothing happens when I push the button. I don't know at this point if it's an error in the coding, or a syntax error that makes it not work.
Basically I am trying to get this function "Rip It" to go through the list of Dewey decimal numbers, change some of them, and return the new number and a message saying it's been changed. There is also one labeled "no number" that has to return an error (not necessarily an alert box, a message in the same space is okay.)
I am a total beginner and not particularly good at this stuff, so please be gentle! Many thanks!
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function RipIt()
{
for (var i = l; i <=10 i=i+l)
{
var dewey=document.getElementById(i);
dewey=parseFloat(dewey);
if (dewey >= 100 && 200 >= dewey)
{
document.getElementById('dewey'+ 100)
}
else if (dewey >= 400 && 500 >= dewey)
{
document.getElementById('dewey'+ 200)
}
else if (dewey >= 850 && 900 >= dewey)
{
document.getElementById('dewey'-100)
}
else if (dewey >= 600 && 650 >= dewey)
{
document.getElementById('dewey'+17)
}
}
}
</script>
</head>
<body>
<h4>Records to Change</h4>
<ul id="myList">
<li id ="1">101.33</li>
<li id = "2">600.01</li>
<li id = "3">001.11</li>
<li id = "4">050.02</li>
<li id = "5">199.52</li>
<li id = "6">400.27</li>
<li id = "7">401.73</li>
<li id = "8">404.98</li>
<li id = "9">no number</li>
<li id = "10">850.68</li>
<li id = "11">853.88</li>
<li id = "12">407.8</li>
<li id = "13">878.22</li>
<li id = "14">175.93</li>
<li id = "15">175.9</li>
<li id = "16">176.11</li>
<li id = "17">190.97</li>
<li id = "18">90.01</li>
<li id = "19">191.001</li>
<li id = "20">600.95</li>
<li id = "21">602.81</li>
<li id = "22">604.14</li>
<li id = "23">701.31</li>
<li id = "24">606.44</li>
<li id = "25">141.77</li>
</ul>
<b> </b>
<input type="button" value="Click To Run" onclick="RipIt()">
<!-- <input type="button" value="Click Here" onClick="showAlert();"> -->
</body>
</html>
I see a few issues:
You need to ensure that the id values in the HTML match what you actually feed into getElementById. For instance, you have document.getElementById('dewey'+ 100) which will look for an element with the id value "dewey100", but I don't see any element in your markup with that id value.
You seem to have typed the lower-case letter l where you meant to type the digit 1 (in your for loop).
This code:
var dewey=document.getElementById(i);
dewey=parseFloat(dewey);
...retrieves the element with the id from i (so far so good), but then tries to parse the element as a floating-point number. DOM elements are objects, passing them into parseFloat won't do anything useful. :-) In this case, if you're trying to parse the content of the element, you can get that via the innerHTML property or (on most browers) innerText for just the text. So perhaps:
var dewey=document.getElementById(i);
dewey=parseFloat(dewey.innerHTML);
The line
document.getElementById('dewey'+ 100)
...by itself is a "do nothing" line: It looks up the element, but then doesn't do anything with it. I'd suggest a change, but I have no idea what you're trying to do with that element. :-)
You may not be aware of it (being new), but your browser almost certainly has quite a powerful tool in it called a "debugger". Look on the menus, but in most browsers you can access the "Dev Tools" using the F12 key. Then you go to the "Source" or "Code" tab in the resulting window, which will show you your code. If you click to the left of a line, in most debuggers that sets a breakpoint which will stop the code in its tracks at that point so you can see what's going on. It's worth spending some time learning to use that tool so you can actually watch your code run.
Editing my old answer...
For your HTML, I removed the id's in the list items since you can find a better way to iterate through them. This way you don't have to add a new id when you want to add an li. See below:
<h4>Records to Change</h4>
<ul id="myList">
<li>101.33</li>
<li>600.01</li>
<li>001.11</li>
<li>050.02</li>
<li>199.52</li>
<li>400.27</li>
<li>401.73</li>
<li>404.98</li>
<li>no number</li>
<li>850.68</li>
<li>853.88</li>
<li>407.8</li>
<li>878.22</li>
<li>175.93</li>
<li>175.9</li>
<li>176.11</li>
<li>190.97</li>
<li>90.01</li>
<li>191.001</li>
<li>600.95</li>
<li>602.81</li>
<li>604.14</li>
<li>701.31</li>
<li>606.44</li>
<li>141.77</li>
</ul>
<input type="button" value="Click To Run" onclick="RipIt()">
For your javascript, I found the number of li's and stored in children. Then found the length of this array and set to 'length'. Then I pulled the innerHTML from each child item in the children array and parseFloat'ed it. Then I ran your conditional and created a new value based on the child's value.
Finally that value is stored in the children li item in question.
the JavaScript:
function RipIt() {
var children = document.getElementById("myList").getElementsByTagName("li"),
length = children.length;
for (var i = 0; i < length; i++) {
var child = children[i].innerHTML,
newValue;
child = parseFloat(child);
if (child >= 100 && 200 >= child) {
newValue = child + 100;
} else if (child >= 400 && 500 >= child) {
newValue = child + 200;
} else if (child >= 850 && 900 >= child) {
newValue = child - 100;
} else if (child >= 600 && 650 >= child) {
newValue = child + 17;
}
children[i].innerHTML = newValue;
}
}
You will probably need to work on your conditionals (if/else) to get exactly what you want. You didn't really specify what each condition needed to do in your answer so I just used your original code.
Related
Im trying to achieve this piece of code but in my console it says thing is null which is weird because when I look in the console, sessionStorage isn't empty...
$(".btn-alert").click(function(){
var identifierOfSpan = $(this > "span").text();
for(var prop in sessionStorage){
var thing = JSON.parse(sessionStorage.getItem(prop))
if(thing.id == identifierOfSpan){
sessionStorage.removeItem(prop);
}
}
$(this).closest(".voyages").remove();
if(sessionStorage.length == 0){
alert("Message!");
location.href="reservation.html"
}
});
the button is supposed to delete the div and the sessionStorage item which looks like this
Html :
<div class="voyages">
<button class="btn btn-alert btn-md mr-2" tabindex="-1">delete the flight</button>
<span>ID : 4224762</span>
<div class="infos">
<img src="img/angleterre.jpg" alt="maroc">
<div>
<ul>
<li><h5>Angleterre, Londres (LON)</h5></li>
<li><h5>2 adulte(s)</h5></li>
<li><h5> Aucun enfants </h5></li>
<li><h5>Type : Couple</h5></li>
</ul>
</div>
</div>
<hr>
<h3>Options</h3>
<ul>
<li>voiture : 0</li>
<li>Hotel : 0 </li>
</ul>
<hr>
<h3>Prix :3713$</h3>
If I'm reading your question correctly, you want to...
Click on a button
Find the first sibling <span> element and parse a number out of its text content
Remove all sessionStorage items (JSON serialized objects) with matching id properties
For the ID, I highly recommend adding some data directly to the <button> to help you identify the right record. If you can, try something like
<button class="btn btn-alert btn-md mr-2" data-voyage="4224762"...
Try something like this
$('.btn-alert').on('click', function() {
const btn = $(this)
const id = btn.data('voyage')
// or, if you cannot add the "data-voyage" attribute
const id = btn.next('span').text().match(/\d+$/)[0]
// for index-based removal, start at the end and work backwards
for (let i = sessionStorage.length -1; i >= 0; i--) {
let key = sessionStorage.key(i)
let thing = JSON.parse(sessionStorage.getItem(key))
if (thing.id == id) {
sessionStorage.removeItem(key)
}
}
// and the rest of your code
btn.closest(".voyages").remove();
if(sessionStorage.length === 0) {
alert("Message!");
location.href = 'reservation.html'
}
})
The problem with using a for..in loop on sessionStorage is that you not only get any item keys added but also
length
key
getItem
setItem
removeItem
clear
I have a function that adds game results to a schedule.
I want to have the score of a winning team in yellow - add ".winner" class to (<%=score1%> or <%=score2%>).
I wonder what is the correct way to specify needed element, using jQuery.
My current code isn't working. All elements get ".winner" class, regardless of whether a team won or not.
addGame: function(gameInfo) {
var sHtml = window.JST["schedule/gamelist/inner_row"](gameInfo);
var tableRow = $("<tr>").append(sHtml);
tableRow.data("id", gameInfo.id);
return tableRow;
}
addNewTable: function(date, gameInfos, number) {
...
...
for (var ind = 0; ind < gameInfos.length; ++ind) {
gameInfo = gameInfos[ind].attributes;
var element = this.addGame(gameInfo);
$("#schedule_mytable_tbody" + number).append(element);
if (gameInfo.score1 > gameInfo.score2)
$("li:nth-child(5)").find("p:first-child").addClass("winner");
else
$("li:nth-child(5)").find("p:last-child").addClass("winner");
}
My template looks like this.
window.JST["schedule/gamelist/inner_row"] = _.template(
'<td width="668px">\
<ul>\
<li class="schedule_..."></li>\
<li class="schedule_..."></li>\
<li class="schedule_...."></li>\
<li class="schedule_..."></li>\
<li class="schedule_boxscore">\
<p><%=score1%></p>\
<p><%=score2%></p>\
</li>\
...
Rendered HTML part:
<li style="font-size:16px" class="schedule_boxscore">
<p class="winner">2</p>
<p class="winner">10</p>
</li>
So, because of the "for" loop, all paragraphs get the ".winner" class, not just <p class="winner">10</p>...
I have the following HTML with a value of "1-99" visible:
<ul class="controls-buttons question-controls">
<li>
</li>
<li>
<a id="orderRange">1 - 99</a>
</li>
<li>
<img src="/Images/control-double.png">
</li>
</ul>
Is there a way that I can have the orderRange change so it changes like this when the previous and next links are clicked? Ideally I would like some way that doesn't mean I have to hardcode a lot of if and else statements.
1-99 > 100-199
1-99 < 100-199 > 200-299
100-199 < 200-299 > 300-399
200-299 < 300-399
etc ..
Once changed I would like to store the value using local storage like below:
var store = window.localStorage;
store.setItem('Range', xxx)
I hope someone can help me.
Here's a solution :
function change(d) {
var $field = $('#orderRange');
var nums = $field.text().split('-').map(function(a){return parseInt(a,10)+d*100});
if (nums[0]<0) return;
else if (nums[0]==101) nums[0]=100;
else if (nums[0]==0) nums[0]=1;
$field.html(nums.join(" - "));
}
$('#orderPrevious').click(function(){change(-1)});
$('#orderNext').click(function(){change(+1)});
Demonstration
function changeRange(delta){
var orderRange=document.getElementById('orderRange'),
range=orderRange.innerHTML.split(' - ')
range=[parseInt(range[0])+delta,parseInt(range[1])+delta]
if(range[0]<0) return
orderRange.innerHTML=range.join(' - ')
var store = window.localStorage;
store.setItem('Range', orderRange.innerHTML)
}
document.getElementById('orderNext').onclick=function(){changeRange(100);}
document.getElementById('orderPrevious').onclick=function(){changeRange(-100);}
I have the following code (also up and running on JSFIDDLE: http://jsfiddle.net/DSuua/12/)
It sorts products based on price matches. I want to hide a filter option from the left panel list altogether on page load if there are no products within that price range (versus showing the price range no matter what, like I do now).
So, as an example, if there are no products within the price range of 10 - 20, then hide the "$10 - $20" on the left panel since it's irrelevant and it just shows an annoying "no matches found" message to user.
Right now the filtering is performed on the click event. Before the filtering is done, it needs to first check the list attribute values (name, title) agains the product price values (lowest & highest price) and if no matching ranges are found, then hide those filter items from the list.
I'm limited to this solution on the client-side only.
Also, any overall tips for improving this code are welcome.
HTML:
<ul id="filterByPrice">
<li><span class="section-header">PRICE</span></li>
<li>Any Price</li>
<li>Under $10</li>
<li>$10 - $20</li>
<li>$20 - $30</li>
<li>$30 - $40</li>
<li>$40 - $50</li>
<li>Over $50</li>
</ul>
<ul id="products">
<li>
Product One<br>
<span id="lowestPriceRange">0</span>
<span id="highestPriceRange">9</span>
</li>
<li>
Product Two<br>
<span id="lowestPriceRange">20</span>
<span id="highestPriceRange">29</span>
</li>
<li>
Product Three<br>
<span id="lowestPriceRange">30</span>
<span id="highestPriceRange">39</span>
</li>
<div id="nothingFound" style="display:none;">
Nothing found
</div>
</ul>
CSS:
#filterByPrice, #products {
border:1px solid #ccc;
padding:10px;
width:100px;
margin:10px;
float:left;
position:relative;
}
JS:
var noProductMatches = $('#nothingFound');
$('#filterByPrice li a').click(function()
{
noProductMatches.hide();
var priceRangeSelectedItem = $(this).html().toLowerCase();
var minSelectedPrice = parseInt( $(this).attr("name") );
var maxSelectedPrice = parseInt( $(this).attr("title") );
var productContainer = $('#products li');
if (priceRangeSelectedItem == 'any price')
{
productContainer.fadeOut("slow");
productContainer.delay(100).fadeIn("slow");
}
else
{
var results = productContainer
.fadeOut(100)
.delay(100)
.filter(function()
{
var minProductPrice = parseInt( $(this).find("#lowestPriceRange").html().toLowerCase() );
var maxProductPrice = parseInt( $(this).find("#highestPriceRange").html().toLowerCase() );
return (minProductPrice >= minSelectedPrice && maxProductPrice <= maxSelectedPrice);
})
.each(function(index, item)
{
$(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
First, you should only have one HTML element of a given id on a page, so the highestPriceRange and lowestPriceRange should be classes. Second, this sounds like something that would be easier to do server side, but if you have to do it client side this should do the trick:
var hidePrices = {};
hidePrices[0] = true;
hidePrices[10] = true;
hidePrices[20] = true;
hidePrices[30] = true;
hidePrices[40] = true;
hidePrices[50] = true;
$('#products').find('span').each(function(i, el){
// round price down to nearest 10s
var key = parseInt(Math.floor($(this).html() / 10) * 10, 10);
hidePrices[key] = false;
});
$('#filterByPrice').find('li').each(function(i, el){
if (hidePrices[Number($(this).find('a').attr('name'))]) {
$(this).hide();
}
});
See demo
This question is similar to this one (but not exact):
Count immediate child div elements using jQuery
I have a bunch of lists that represent christmas presents for different people.
As an example, this is a list of presents for one person. Note that new people can be added
<ul id = "presents">
<li id = "person1" >
<ul id = "presentsforperson1">
<li id = "present1" >
<ul id = "present1info">
<li> Present 1 </li>
<li> A New Pair of Shoes </li>
<li> $19.99 </li>
</ul>
</li>
<!-- More presents for person 1 can be added here dynamically-->
</ul>
</li>
<!-- More people can be added here -->
</ul>
Unlike the question posted, I have the object presentsforperson1 in a variable called drop (droppable). I was wondering what the correct syntax is for finding the number of presents person 1 has (in this case 1) with this variable?
This is what I have tried so far:
var numberofPresents = $(drop + "ul > li").length; //drop holds li#presentsforperson1 .droppable
var numberofPresents = $(dropid + "ul > li").length; //dropID is $(drop).attr("id");
If the person id is the id of the ul containing their presents then simply:
$('#personId > li').length
will do it.
Update
Or if the id is in a variable:
$('#' + personId).children('ul').length
You obviously could append the child selector to the selector string eg:
$('#' + personId + ' > ul').length
But personally I find the version with the .children call more readable.
Assuming your drop variable references a jQuery object:
var quantity = drop.children().length;
If it has the raw DOM element:
var quantity = $(drop).children().length;
If it is merely a string with the ID, with no ID selector syntax:
var quantity = $('#' + dropid).children().length;
Or you can do concatenation like you were:
var quantity = $('#' + dropid + " > li").length;
You can do something as follows (give your lis that represent a present a css class):
var presents = $('ul[id="person1"]').children('li.presentClass');
alert(presents.length);