I'm trying to make some buttons CSS change onload depending on the textbox value using jQuery 1.9.1 but I'm unable to do that. Suppose, after the page loads, if the value of a textbox is YES then button color should be green and if the value of another textbox is NO then the button color should be blue. In HTML, only "blue" class is assigned as default but jQuery has to change that onload. Here's my code:
$(document).ready(function () {
$('.btn').load(function () {
var isYes = $(this).next('.assignCheck').val('Y');
if (isYes) {
$(this).toggleClass('color-blue color-green');
}
});
});
JSFiddle Demo
How can I change the CSS style depending on a value given after the page loads?
UPDATE
Working Solution,
$('.btn').each(function () {
if ($(this).next('.assignCheck').val() == 'y') {
$(this).toggleClass('color-blue color-green');
}
});
JSFiddle Demo
Your first problem is this line:
var isYes = $(this).next('.assignCheck').val('Y');
What that is doing isn't testing it, it's assigning 'y' to the value of .assignCheck. What you need is something like:
var isYes = ($(this).next('.assignCheck').val() == 'y');
or just
if ($(this).next('.assignCheck').val() == 'y') {
$(this).toggleClass('color-blue color-green');
}
More info # http://api.jquery.com/val/.
Secondly, .load() has been deprecated, use each() instead since the code will run on document load anyway.
$('.btn').each(function() { ...
Related
This question already has answers here:
jQuery Data vs Attr?
(3 answers)
Closed 4 years ago.
I'm trying to change the value of a data attribute and the background colour whenever the button is clicked, so it needs to account for multiple clicks as it makes an ajax call on the event click on the element.
What happens so far is that the background colour gets changed and the data-attribute changes, but when clicked for a second time the original data-status value is picked up in the if statement even though it was changed in the original click.
$(document).ready(function () {
$('.button-create').click(function () {
// assign data from data attributes to variables
var check = $(this).data("value");
var checkID = $(this).data("checkid");
var legend = $(this).data("legend");
var area = $(this).data("area");
var status = $(this).data("status");
// ajaxCall(check, checkID, legend, area, $status)
//change colour when clicked based on status
if($(this).data("status") == 0) {
console.log("Element has been clicked to green");
$(this).css('background', 'green !important');
$(this).attr('data-status','1')
} else if ($(this).data("status") == 1) {
console.log("Element has been clicked to change to red");
$(this).css('background', 'red !important');
$(this).attr('data-status','0')
};
})
})
<html>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<body>
<button class='check-box button-create' data-value='AUDIT' data-checkid='86' data-legend='3' data-area='8' data-status='1' type='submit' name='submit' value='submit'></button>
</body>
</html>
Any help is most appreciated!
Thank you
You need to set property value using .data() instead of using .attr():
Use:
$(this).data('status','0')
Instead Of:
$(this).attr('data-status','0')
The title is a bit of a tongue twister. A brief description of the fiddle, is that it's a toggle style accordion where the toggle state changes color when one of the divs is toggled. I've got it working to where if another div is toggled it will close that previous div and open the new div while changing the toggle state.
The issue I am running into is if a user wants to close the current toggle without clicking a different div it will close the current toggle but not change the toggle state back to it's original state. I am currently using this and have tried multiple things including if the container 'is: visible' or hasClass then to remove the toggle class, but nothing seems to work. I've also tried a different slideToggle function, but of course that applied it to the toggled element I've found.
Fiddle: http://jsfiddle.net/NFTFw/1256/
What I am trying to do?
I want the current toggle class to change back to its original state if the user clicks the current toggled div or clicks another div. So essentially I want the user to have either option.
CODE:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
$(".toggle").removeClass("toggle-d");
$(this).addClass('toggle-d');
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
});
Check to see if the thing that you're clicking already has the class. If so, remove it, if not, add it. I suspect the problem you were having with hasClass() is that you were attempting to check the wrong this.
Oooh I did a bad thing and didn't remove the class when a new div was clicked. I've fixed that and updated the jsfiddle
jsfiddle
js:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
var width = $(window).width();
if (width <= 600) {
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
if($(this).hasClass('toggle-d')){
$(this).removeClass("toggle-d");
}
else{
$('.toggle').removeClass('toggle-d');
$(this).addClass('toggle-d');
}
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
}
});
What i would suggest is to pass the element itself in the function
in the index.html Do this
<a class = 'classname' onclick = toggle(this)>
Your Content Here
</a>
After that in the script.js
what i am saying is in javascript, i believe you can easily convert it to jquery
function toggle(value){
if(value.className == 'the predefined value'){
value.className = value.className + ' Your new class addition'
// remember there should be a space if you are adding an additional class to the present class, else directly change the classname
}
else{
value.className = 'the predefined value'
}}
this will toggle your classname whenever the element is clicked
Pretty new to javascript.
I've got a button, and I'd like to toggle its background color using if / else JS logic. My environment is ASP.net, c#, javascript, VS2013 express.
The 1st part of the statement works to change the button color to #198B07, however, the subsequent click does not seem to be firing the "else" property to set the color to "#2A303C". The initial state of the button is to have the standard "gray" color. Is that color getting "reset" on my second click, thus making the initial "if" true again? That appears to be the behavior, once the color changes to #198B07, it stays that color for all subsequent clicks.
Any idea what I'm doing wrong?
Here's my code:
script
<script>
function myFunction2() {
if (document.getElementById("test").style.background != '#198B07') {
document.getElementById("test").style.background = '#198B07';
} else {
document.getElementById("test").style.background = '#2A303C';
}
return false;
}
</script>
HTML
<button type="button" id="test" onclick="myFunction2()">Try it</button>
style.background doesn't equate to a hex colour, it returns rgb values. To properly compare these you need to change the if statement to compare the rgb Ie
if (document.getElementById("test").style.background != 'rgb(25, 139, 7)')
This will change the background as required. See jsfiddle as an example.
Try using jquery:
function myFunction2() {
if ($('#test').css('background-color') != '#198B07') {
$('#test').css('background-color', '#198B07');
}
else {
$('#test').css('background-color', '#2A303C');
}
return false;
}
The problem is that HTMLElement.style.background returns a string representing the color in the RGB format. In your case, the value of 'document.getElementById("test").style.background' will be 'rgb(25, 139, 7)' after you set the exadecimal color '#198B07' for the element style property.
I suggest to not directly style the element via js, you could for example add or remove a class and style the element via CSS which would be a better and more mantainable solution.
Try this:
function myFunction2() {
if (document.getElementById("test").style.background !== '#198B07') {
document.getElementById("test").style.background = '#198B07';
}
else {
document.getElementById("test").style.background = '#2A303C';
}
return false;
}
I have three buttons on a page I've set up as an array. I'm using $.each to iterate through them and inside that is the color picker function. I'm trying to have only the (last) clicked button change background color, but right now, if I click all 3 before using the color picker, they all change color. I need the button last clicked only to change color. JSFiddle
var test1 = $('#test1');
var test2 = $('#test2');
var test3 = $('#test3');
var elements = [test1, test2, test3]
$.each(elements, function(i) {
function handler() {
$('#color').change(function(){
$(elements[i]).unbind('click', handler);
elements[i].css('background-color', this.value);
});
}
$(elements[i]).bind('click', handler)
});
Your solution seems overly complex. A simpler solution might be this:
Add click handlers to the buttons. When a button is clicked, add an "active" class to that button and remove from others.
Bind a change handler to the color picker. When that happens, change the background color of the active button:
I'm also going to assume you can give a class of colorButton to the buttons:
$('.colorButton').click(function(e) {
e.preventDefault();
$('.colorButton').removeClass('active');
$(this).addClass('active');
})
$('#color').change(function() {
$('.colorButton.active').css('background-color', this.value);
});
Working fiddle: http://jsfiddle.net/wBsab/
Why don't you bind the click event with the color change?
$('.buttons_that_change_color_on_click').bind('click', function(){
this.style.backgroundcolor = the_value_you_want;
});
finally i did this by following javascript..
function extractPageName(hrefString)
{
var arr = hrefString.split('/');
return (arr.length<2) ? hrefString : arr[arr.length-2].toLowerCase() + arr[arr.length-1].toLowerCase();
}
function setActiveMenu(arr, crtPage)
{
for (var i=0; i<arr.length; i++)
{
if(extractPageName(arr[i].href) == crtPage)
{
if (arr[i].parentNode.tagName != "DIV")
{
arr[i].className = "selected";
arr[i].parentNode.className = "selected";
}
}
}
}
function setPage()
{
hrefString = document.location.href ? document.location.href : document.location;
if (document.getElementById("but_a")!=null)
setActiveMenu(document.getElementById("but_a").getElementsByTagName("a"), extractPageName(hrefString));
}
if i click the ul without clicking the link.. its working.. when i click the link. it works until the page loads. after the page load, the ul back groud going default class not "selected" class..am new to tis.. am struggling so hard.. need help..??
I've added a jdFiddle with an example here:
http://jsfiddle.net/Suren/u4szQ/1/
$(document).ready(function() {
$("a.button").click(function () {
$(this).toggleClass("selected");
});
});
You've got too much javascript there.
After your posted fiddle. Here is a working fiddle.
Note you have a great deal of malformed HTML. You can't place divs in between list items. You can't have multiple objects on a page with the same ID (use a class instead).
After clicking on anchor the page is going to navigate to the url set on anchor's href attribute so whatever javascript operation you do is going to be lost after the page is loaded.
If you want to highlight the selected link the you can probably send the link id or some identifier along with the url and then check for it on page load and set the appropriate link selected.
By the way toggleClass adds or removes one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.