Background change not working in javascript. whats wrong? - javascript

I am using jquery slider, i have a single layout and a center div for content..i need to change the color of the layout while i slide on a different page. This is What i am doing using asp.net mvc3.
HTML:
<div id="iPhone_Product">
<div class="slides_containeriphone" >
#if (Model == null)
{
<div class="animateriphone" id="1" title="iphone">
#Html.Partial("`enter code here`_iPhone_Main")
</div>
<div class="animateriphone" id="2" title="salah">
#Html.Partial("Salah")
</div>
<div class="animateriphone" id="3" title="tasbeeh">
#Html.Partial("_Tasbeeh")
</div>
}
else
{
foreach (string s in Model)
{
<div class="animateriphone">
#Html.Partial(s);
</div>
}
}
</div>
</div>
Javascript:
function color_change() {
var ids = new Array();
ids[0] = '1';
ids[1] = '2';
ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
}
if (x.id == '1' && x.title=='iphone') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
else
if (x.id == '2' && x.title == 'salah') {
$(".st_tabs_container").css({ "background-color": "yellow" });
}
else
if (x.id == '3' && x.title == 'tasbeeh') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
}
$(document).ready(function () {
color_change();
});
i have used this javascript to change the background but its not working, any help would be appericiated.

I think the issue is that you are using numbers for ids. Try starting your id values with letters. I think you should consider prefixing your ids, i.e. id1, id2, or something like that.
And you are closing the for loop too early, Nest all your if/else logic inside it as well.

Isn't x always going to be 3 since you are reseting x inside a loop.

You are looping over all your elements without doing anything to them, so depending on what you are trying to do, you might need to move the if-statements into the for-loop as well, or make use of the x in a proper way from within the for-loop.
Not entirely sure what you want to accomplish, but I've put together what I believe you are trying to do: http://jsfiddle.net/ZuzTU/1/
function color_change() {
var ids = new Array(); ids[0] = '1'; ids[1] = '2'; ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
if (x.id == '1' && x.title=='iphone') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
else if (x.id == '2' && x.title == 'salah') {
$("#" + x.id).css({ "background-color": "yellow" });
}
else if (x.id == '3' && x.title == 'tasbeeh') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
}
}
$(document).ready(function () {
color_change();
});​

Pretty sure you're not calling the ids right, try this:
<div class="animateriphone" id="id2" title="salah">
var x = document.getElementById('id'+ ids[item]);

Related

Price filter (min and max price) with a dropdown menu asp.net core

I'm trying to filter through prices using javascript and asp.net core, and I've come up with a heap of javascript which doesn't really work.
There has to be an easier way, using jquery or with c#?
If anyone has any suggestions it would be greatly appreciated!
Price Filter
<p>Sort By Price: </p>
<select id="sort" onChange="OnSelectedIndexChange()">
<option value="all">All</option>
<option value="1">$0 - $50</option>
<option value="2">$51 - $100</option>
<option value="3">$101 - $150</option>
<option value="4">$151 + </option>
</select>
<div class="row">
#{
foreach (var item in Model.Products)
{
if (item.CategoryId == Model.CategoryId)
{
<div class="card h-100" id="hamper">
<p id="price">$#item.Price</p>
</div>
}
}
}
</div>
</div>
<!-- Javascript -->
<script type="text/javascript">
var prices = [];
#foreach(var item in Model.Products)
{
#:prices.push(#item.Price)
}
function OnSelectedIndexChange() {
if (document.getElementById('sort').value == "all") {
document.getElementById("hamper").style.display = "block";
} else if (document.getElementById('sort').value == "1") {
for (var i = 0; i < prices.length; i++) {
if (prices[i] >= 0 && prices[i] <= 50 ) {
document.getElementById("hamper").style.display = "block";
} else {
document.getElementById("hamper").style.display = "none";
}
}
} else if (document.getElementById('sort').value == "2") {
for (var i = 0; i < prices.length; i++) {
if (prices[i] >= 51 && prices[i] <= 100) {
document.getElementById("hamper").style.display = "block";
} else {
document.getElementById("hamper").style.display = "none";
}
}
} else if (document.getElementById('sort').value == "3") {
for (var i = 0; i < prices.length; i++) {
if (prices[i] >= 101 && prices[i] <= 150) {
document.getElementById("hamper").style.display = "block";
} else {
document.getElementById("hamper").style.display = "none";
}
}
} else if (document.getElementById('sort').value == "4") {
for (var i = 0; i < prices.length; i++) {
if (prices[i] >= 150) {
document.getElementById("hamper").style.display = "block";
} else {
document.getElementById("hamper").style.display = "none";
}
}
}
}
</script>
There are multiple ways to handle it, in both client side and server side.
Here is a quick sample to do the filtering on client side.
First, add a data attribute to each option in the select to represent the corresponding price range. You may keep the value in this format "lowerRange:upperRange"
<select id="sort">
<option data-price="0:#Int32.MaxValue" value="all">All</option>
<option data-price="0:50" value="1">$0 - $50</option>
<option data-price="51:100" value="2">$51 - $100</option>
<option data-price="101:1000" value="3">$101 - 1000</option>
<option data-price="1001:#Int32.MaxValue" value="4">1001 + </option>
</select>
Now when you render each, card, give it a data attribute for storing the price (data-productprice)
<div class="row" id="my-products">
#foreach (var item in Model.Products.Where(a=>CategoryId==Model.CategoryId))
{
<div class="card h-100" data-productprice="#item.Price">
<span>#item.Name</span>
<span>#item.Price</span>
</div>
}
</div>
Now when user make a selection in the sort dropdown, get the data attribute of the selected option, read the lower and upper range, filter the card div's which has a productprice data attribute value which is falling in that range.
$(function () {
var $cards = $("#my-products").find("[data-productprice]");
$("#sort").change(function () {
var t = $(this).find(':selected').data('price');
var a = t.split(':');
var l = parseFloat(a[0]);
var u = parseFloat(a[1]);
$.each($cards, function (a, b) {
var p = parseFloat($(b).data("productprice"));
if (p >= l && p <= u) {
$(b).show();
} else {
$(b).hide();
}
});
});
});
As i mentioned, this is just one way of doing it, you can do the filtering on server side as well (which is something i might prefer).In that approach, you make an ajax call in the change event where you will send the lower and upper range (l and u) and let the server do a filtering based on the price range and return the partial view markup for only those items. When the ajax response comes back, you will replace the HTML of the my-products div.
$(function () {
$("#sort").change(function () {
var t = $(this).find(':selected').data('price');
var a = t.split(':');
var l = parseFloat(a[0]);
var u = parseFloat(a[1]);
var urlForFilteredResults = "/Products/List?priceFrom="+l+"&priceTo="+r;
// Add other filter criteria as needed
$("#my-products").load(urlForFilteredResults);
});
});
Assuming your List action method accepts the params and return a partial view result
I see in your code you are setting the same id value ( id="hamper") for all the cards inside the loop. That is invalid HTML. Your Id's should be unique in a document.

Jquery "for" loop to find how many children

I am trying to alert how many children are in a div with the class ".child". Ex: There are five ".child" inside of a div. I am not sure why my for loop to do this doesn't work, and I realize there are better ways but I am practicing for loops. Thanks. The problem can be found here http://jqexercise.droppages.com/#page_0013_
for (var i = 1; i < 100; i++){
if($(".child:nth-child(i)") == true){
}
else {
alert(i);
break;
}
}
You can get number of .child in a div like following.
var num = $('div').find('.child').length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
</div>
Update: If you want to use for loop then you can do it like below using jquery eq() function.
for (var i = 0; i < 100; i++) {
if ($('.child').eq(i).length) {
}
else {
alert(i);
break;
}
}
You used i as string. Using nth-child() do it like below.
for (var i = 1; i < 100; i++) {
if ($(".child:nth-child(" + i + ")").length) {
}
else {
alert(i-1);
break;
}
}
Another way:
alert($('div .child').length);
i inside if condition is a string, not a variable, do this :
if ( $( ".child:nth-child(" + i + ")" ) == true )
var intChildrenCount = $("div .child").length;
var arrChildren = $("div .child");
$.each(arrChildren,function(){
// Here you will get child's HTML one by one
console.log($(this).html());
});

Looking for a javascript solution to reorder divs

I have some divs in the page that show different things of the same kind, for example offers, now offers have ending time, and also posted time, if the user wants to order by ending time, or posted time, they should be re ordered.
I'm looking for a javascript solution that could do that, any particular libraries under Ext JS , or JQuery would work
Here is how these divs look like
<div data-sortunit="1" data-sort1="40" data-sort2="156" data-sort3="1"
data-sort4="1317620220" class="item">
</div>
<div data-sortunit="2" data-sort1="30" data-sort2="116" data-sort3="5"
data-sort4="1317620220" class="item">
</div>
<div data-sortunit="3" data-sort1="10" data-sort2="157" data-sort3="2"
data-sort4="1317620220" class="item">
</div>
So I wanna be able to sort these divs based on data-sortN, N being an integer
Edit: OK, now that you've supplied some HTML, here's javascript code that will sort that specific HTML by the desired column number:
function sortByDataItem(containerID, dataNum) {
var values = [];
$("#" + containerID + " .item").each(function(index) {
var item = {};
item.index = index;
item.obj = this;
item.value = $(this).data("sort" + dataNum);
values.push(item);
});
values.sort(function(a, b) {return(b.value - a.value);});
var container = $("#" + containerID);
for (var i = 0; i < values.length; i++) {
var self = $(values[i].obj);
self.detach();
container.prepend(self);
}
return;
}
$("#sort").click(function() {
var sortValue = $("#sortColumn").val();
if (sortValue) {
sortValue = parseInt(sortValue, 10);
if (sortValue && sortValue > 0 && sortValue <= 3) {
sortByDataItem("container", sortValue);
return;
}
}
$("#msg").show(1).delay(5000).fadeOut('slow');
});
You can see it work here in a jsFiddle: http://jsfiddle.net/jfriend00/JG32X/
Since you've given us no HTML to go on, I've made my own HTML and shown you how you can use jQuery to sort:
HTML:
<button id="sort">Sort</button><br>
<div id="productList">
<div class="row"><div class="productName">Popcorn</div><div class="price">$5.00</div></div>
<div class="row"><div class="productName">Peanuts</div><div class="price">$4.00</div></div>
<div class="row"><div class="productName">Cookie</div><div class="price">$3.00</div></div>
<div class="row"><div class="productName">Beer</div><div class="price">$5.50</div></div>
<div class="row"><div class="productName">Soda</div><div class="price">$4.50</div></div>
</div>
Javascript (run after page is loaded):
$("#sort").click(function() {
var prices = [];
// find all prices
$("#productList .price").each(function(index) {
var str = $(this).text();
var item = {};
var matches = str.match(/\d+\.\d+/);
if (matches && matches.length > 0) {
// parse price and add it to the prices array
item.price = parseFloat(matches[0]);
item.row = $(this).closest(".row").get(0);
item.index = index;
prices.push(item);
}
});
// now the prices array has all the prices in it
// sort it using a custom sort function
prices.sort(function(a, b) {
return(a.price - b.price);
});
// now pull each row out and put it at the beginning
// starting from the end of the prices list
var productList = $("#productList");
for (var i = prices.length - 1; i >= 0; i--) {
var self = $(prices[i].row);
self.detach();
productList.prepend(self);
}
});
And, a jsFiddle that shows it in action: http://jsfiddle.net/jfriend00/vRdrA/.
I made a tiny jqueryPlugin out of jfriend00's answer:
(function($){
$.fn.sortChildrenByDataKey = function(key, desc){
    var i, els = this.children().sort(function(a, b) {return (desc?1:-1)*($(a).data(key) - $(b).data(key));});
    for (i = 0; i < els.length; i++) {
        this.prepend($(els[i]).detach());
    }
return this;
};
})(jQuery);
Your HTML:
<div id="myContainer">
<div data-myKey="4"> ... </div>
<div data-myKey="2"> ... </div>
...
</div>
Usage:
$('div#myContainer').sortChildrenByDataKey('myKey', true_or_false);
The children of the container can be any Elements. Its only important, that they are immediate children and have data-X key.
Thank you, jfriend00!!

Bug in javascript function

I've got a bug when I'm using a javascript function : my function displays the content of a div element but when I uncomment some code it doesn't work anymore.
Someone has any idea why ?
function traverse(){
var root=document.getElementById('tree0').childNodes;
for(var i=0;i<root.length;i++) {
var lis = root[i];
var number =0;
for (var member in lis) {
output.innerHTML+=lis[member];
/*var assertion = lis[member];
var result = assertion.indexOf("Bookmarks menu");
if(result != -1) {
output.innerHTML+='Test';
}*/
}
}
}
thanks,
Bruno
You may get more that you expect when you do for ... in ...
Is THIS what you want? http://jsfiddle.net/bM9Bn/
<div id="tree0">
<div id="bla">
bla
</div>
<div id="Bookmarks menu">
Bookmarks Menu
</div>
</div>
<hr />
<div id="output"></div>
<script>
var output = document.getElementById("output")
function traverse(){
var root=document.getElementById('tree0').childNodes;
for(var i=0;i<root.length;i++) {
var lis = root[i];
var number =0;
for (var member in lis) {
// output.innerHTML+="["+member+":"+lis[member]+"]";
if (member == "id" || member == "textContent") {
output.innerHTML+="["+member+":"+lis[member]+"]";
var assertion = lis[member];
// the typeof test not needed if we only process textContent and ID
if (typeof assertion == "string") {
var result = assertion.indexOf("Bookmarks menu");
if(result != -1) {
output.innerHTML+='<span style="color:red">Test</span>';
}
}
}
}
}
}
traverse()
</script>
Just looking quickly- var and if statement should both us resultat?
var resultat = assertion.indexOf("Bookmarks menu");
if(result*at* != -1) {
You are checking the 'result' variable, but setting the 'resultat' variable. Try using resultAt in the conditional, and I think it will work for you.

HTML + javascript mouse over, mouseout, onclick not working in firefox

My question is to get onMouseover,onMouseout,onMousedown,onClick on a table row. For which i am calling javascript userdefined functions.
onMouseover --- Background color should change.
onMouseout --- Reset to original color
onClick --- First column checkbox/radio button should be set and background color should change
onMousedown --- background color should change.
My code in html is:-
<tr onMouseOver="hover(this)" onMouseOut="hover_out(this)" onMouseDown="get_first_state(this)" onClick="checkit(this)" >
and the methods in javascripts are:-
var first_state = false;
var oldcol = '#ffffff';
var oldcol_cellarray = new Array();
function hover(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
oldcol_cellarray[i] = element.cells[i].style.backgroundColor;
element.cells[i].style.backgroundColor='#e6f6f6';
}
}
}
}
// -----------------------------------------------------------------------------------------------
function hover_out(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
if (typeof oldcol_cellarray != undefined) {
element.cells[i].style.backgroundColor=oldcol_cellarray[i];
} else {
element.cells[i].style.backgroundColor='#ffffff';
}
//var oldcol_cellarray = new Array();
}
}
}
}
// -----------------------------------------------------------------------------------------------
function get_first_state(element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
first_state = element.cells[0].firstChild.checked;
}
// -----------------------------------------------------------------------------------------------
function checkit (element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.cells[0].firstChild.type == 'radio') {
var typ = 0;
} else if (element.cells[0].firstChild.type == 'checkbox') {
typ = 1;
}
if (element.cells[0].firstChild.checked == true && typ == 1) {
if (element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = false;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
} else {
if (typ == 0 || element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = true;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
}
if (typ == 0) {
var table = element.parentNode;
if (table.tagName != "TABLE") {
table = table.parentNode;
}
if (table.tagName == "TABLE") {
table=table.tBodies[0].rows;
//var table = document.getElementById("js_tb").tBodies[0].rows;
for (var i = 1; i< table.length; i++) {
if (table[i].cells[0].firstChild.checked == true && table[i] != element) {
table[i].cells[0].firstChild.checked = false;
}
if (table[i].cells[0].firstChild.checked == false) {
set_rowstyle(table[i], false);
}
}
}
}
}
function set_rowstyle(r, on) {
if (on == true) {
for (var i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'bold';
r.cells[i].style.backgroundColor = '#f2f2c2';
}
} else {
for ( i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'normal';
r.cells[i].style.backgroundColor = '#ffffff';
}
}
}
It is working as expected in IE.
But coming to firefox i am surprised on seeing the output after so much of coding.
In Firefox:--
onMouseOver is working as expected. color change of that particular row.
onClick -- Setting the background color permenantly..eventhough i do onmouseover on different rows. the clicked previous row color is not reset to white. -- not as expected
onclick on 2 rows..the background of both the rows is set..Only the latest row color should be set. other rows that are selected before should be set back..not as expected i.e if i click on all the rows..background color of everything is changed...
Eventhough i click on the row. First column i.e radio button or checkbox is not set..
Please help me to solve this issue in firefox. Do let me know where my code needs to be changed...
Thanks in advance!!
Sorry for making everything inline, but this should work in all browsers:
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
Here is a complete page you can test out:
<html>
<head>
<style type="text/css">
tr.click{
background:yellow;
}
tr.hover{
background:green;
}
</style>
</head>
<body>
<table border="1">
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
</table>
</body>
</html>
I would strongly advise moving everything to an external JS file and using some sort of initialization function to assign the event listeners, instead of writing them all inline like me.
I hope this helps in some way.
There may be a particular reason you haven't, but have you considered using a library such as JQuery to tackle this? What you're trying to achieve here could be done very easily and simply with JQuery's CSS-like selectors and .parent/.parents.
As MartyIX says, I would start by using console.log and/or breakpoints in Firebug / Chrome to check exactly which code blocks are being executed. Using the javascript debugging tools can be a little daunting at first until you get how each of the options (step into, step over) work, but they do allow you to check that the code is working as you think it is very easily.
One thing I notice in checkit() - be careful with where you declare variables. I'm not an expert with javascripts variable scoping, but to me it looks like the typ variable only exists within the if block. I would declare "var typ" before the if block and use a third value or second variable to check whether any checkbox or radio is found (what happens if no checkbox and no radio is found?)

Categories

Resources