change input button style using javascript on click - php

I wanted to change the style of the button I'm using every time I clicked that button and together change it's text. Problem is I wanted to do it using and external javascript which I'm not that familiar with it's syntax. To elaborate what I wanted to do is to have a button having a text displaying like: Very Good, Good, Moderate, Failed. Each of the text has it's own assigned gradient color using CSS let's say a gradient of Green for Very Good, Yellow for Good, Orange for Moderate and Red for failed. Tried searching for it but I only landed on an irrelevant posts. What I think is that I need to make a button with on click and everytime I click the javascript will add int values from 0 and reset back to 0 after it reaches 3. then I think I can use case for the css class assigning like this.style="failed" Well I don't know if this is possible.
UPDATE:
After doing some research I've managed to do something about the changing texts (using javascript alone) but not yet the class part since I think the class is a keyword in javascript. here's my script so far:
function buttonChange(){
var button = document.getElementById("stats");
switch (button.value)
{
case "Very Good":
button.value="Good";
break;
case "Good":
button.value="Moderate";
break;
case "Moderate":
button.value="Failed";
break;
default:
button.value="Very Good";
}
}
now the problem is the style. :)

Using jQuery your code could look something like this:
var values = new Array('Very Good', 'Good', 'Moderate', 'Failed');
var colors = new Array('lime', 'yellow', 'orange', 'red');
$('#rate').click(function() {
// current index is stored in data attribute
var idx = $(this).data('value') + 1;
// last value was selected -> go back to first one
if (idx >= values.length) {
idx = 0;
}
// update data attribute with current index
$(this).data('value', idx);
// update button text
$(this).val(values[idx]);
// update button background color
$(this).css('background-color', colors[idx]);
});​
See this FIDDLE.

have a look at this:
Change an element's class with JavaScript
I think that your CSS should have all the styles for gradients and stuff like this:
.VeryGood {//gradient for very good
}
.Good {//gradient for good
}
.Moderate {//gradient for moderate
}
.Failed { //gradient for failed
}
and then, use this javascript and html :
<script type="text/javascript">
var i = 1; //change to 0 if element dosen't need to have any class by default
var classArray = new Array();
classArray[0] = 'VeryGood';
classArray[1] = 'Good';
classArray[2] = 'Moderate';
classArray[3] = 'Failed';
function changeClass()
{
document.getElementById("MyElement").className = classArray[i];
i++;
if(i>=3){
i=0;
}
}
</script>
...
<button onclick="changeClass()">My Button</button>
now, the array key i increases every time the button is clicked, so by default, you can have your element's class as VeryGood, and every time the button is clicked, it advances to next class, so after VeryGood comes Good then Moderate then Failed, ithe it resets itself to VeryGood. hope this is what you are looking for :)

Here is a jQuery solution to cycle through the button text and the background colour for the four states:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var states = ['Very Good', 'Good', 'Moderate', 'Failed'];
var colors = ['green', 'Yellow', 'orange', 'red'];
var index = 0;
$('body').on('click', '#button', function(){
index = ++index%4;
$("#button").html(states[index]);
$("#button").css('background-color',colors[index]);
});
});
</script>
</head>
<body>
<button id="button" style="background-color:green"; type="button">Very Good</button>
</body>
</html>
Note the modulus (%) operator which simplifies the circular increment of 'index' from 0 to 3.

Related

Jquery Change Input background color if entry matches PHP Array?

I have a simple form that has 3 fields. user, id, email.
I have 2 PHP arrays $user & $id
When a user enters there name into the user or id fields I want the respective php arrays checking and if the name or id is in the array then change the background color of the input box they are currently in.
If they update there entry then the checking should continue and if no match is found then revert the background back to it's original white color.
If they empty the input field then the color should change back to white.
The page may be preloaded with values, so I may be changing the background color using php on the initial load..
I've found this, which sort of works for the specified characters in it's array:
$('input').bind("change keyup", function() {
var val = $(this).val();
var regex = /["<>&]/g;
if (val.match(regex)) {
$(this).css("background", "red");
val = val.replace(regex, "");
$(this).val(val);
}
$("p").html(val);
});
I've tried to update it to support a php array, but it doesn't work and I don't know how to make it check either array and revert the color back.
This is what I have so far :
JFIDDLE
Thanks :)
UPDATE
I've got this working using the following :
$(function(){
$('input').bind("change keyup", function() {
var val = $(this).val();
if ($(this).attr('id')=="user") {
var check = <?php echo json_encode($user)?>;
} else {
var check = <?php echo json_encode($id)?>;
}
if ($.inArray(val, check) != -1) {
$(this).css("background-color", "red");
} else {
$(this).css("background-color", "white");
}
});
});
But is there a neater way to write this ?
Thanks :)
if you want to use your php array in javascript, you can do this:
var myArray = <?php echo json_encode($myArray) ?>;
and do the javascript magic

Cannot Modify/Manipulate Dynamic Content From Ajax/JSON Response for A Dynamic PHP Form

I need a dynamic form which is supposed to work like this:
When user press "ADD" button, appear a new ..<.div> DOM to select a package.
Depending on the package, the row must change color (by adding/removing some classes).
But I can't get it working. Here is my HTML:
<button onclick='addDay();'>
<div class='content'>
</div>
My Javascript:
//FUNCTION 1: LOAD AJAX CONTENT
function addDay()
{
baseUrl = $('input#helper-base-url').val();
//Set caching to false
$.ajaxSetup ({
cache: true
});
//Set loading image and input, show loading bar
var ajaxLoad = "<div class='loading'><img src='"+baseUrl+"assets/images/loading.gif' alt='Loading...' /></div>";
var jsonUrl = baseUrl+"car/add_day/"+count;
$("div#loading").html(ajaxLoad);
$("div#content").hide();
$.getJSON(
jsonUrl,
{},
function(json)
{
temp = "";
if(json.success==true)
{
temp = json.content;
}
//Display the result
$("div#content").show();
$("div#content").html($("div#content").html()+temp);
$("div#loading").hide();
});
}
//FUNCTION 2: MODIFY AJAX CONTENT
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
});
My PHP
function add_day($count)
{
$temp = "<div class='row".$count."'>
<select id='switch".$count."' class='switch'>
<option value='1'>Package 1</option>
<option value='2'>Package 2</option>
</select>
</div>";
$result = array(
'success' => true,
'content' => $temp,
);
$json = json_encode($result);
echo $json;
}
PS. The form is not as simple as this but to make the problem solving easier, I remove the details. But I can't seem to change the class on the fly. Do we have a solution or a good work around here?
Edit 1:
Sorry I didn't make myself clear before. I had no problem with getting the id or variable (it was okay, when I alert it the right value comes out - but after I add the class, no color changes is seen). I run it:
a. On button click, load Ajax content.
b. Ajax content (which results contains a ) loaded successfully.
c. FAIL: On change, add class "package1" to the div row. (So, I had no problem with getting the right id or class name. When I alert the variables it gives the right result, BUT the color doesn't change. I can't check whether class is successfully added or not.)
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
$('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});
Assuming that everything else is ok
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
This is the problem. To get the attibute id you have to do
var id = $(this).attr('id').substr(6);
You have to use $(this) and not this by the way to use all of jQuery functionalities.
Same below
$(row).addClass('package1');
So, full code:
//Get which row is to be changed in background's color
var id = $(this).attr('id').substr(6);
//Add class "package1" which change row's background color
$('.row'+id).addClass('package1');
Changing the class to id solved the problem (using #row0 instead of .row0). Sorry and thank you for your time :)

Change the background image of a div depending on which link is selected in the navigation

i'd like to change the background image of a div depending on wich link is selected in my navigation!
exemple :
let's say I have a menu item called :
#nav li.menu-item-59
when the link is selected it changes to
#nav li.menu-item-59.selected a
I'd like that whenever one of the menu item is selected the background image of the div footer change to a different file...
I've read some articles about sibling operators but can't seem to make it work and I'm not sure it is the best way to go ..
can anyone help?
thanks ! :D
It looks like you're using JS to add the class of selected to the menu. At the same time you're adding that, also add the the menu item name to the footer. something like:
var menuName = $(this).attr('id');
$('.footer').addClass(menuName);
Then in your css for the footer, add the class to the end of the element:
.footer.menu-item-59 {
// background goes here
}
based on your fiddle below, try:
$(window).scroll(function(){
for(var i = 0; i < sections.length; i++)
if($(window).scrollTop() +5 >= sections[i].top &&
$(window).scrollTop() <= sections[i].bottom){
sections[i].link.addClass('selected')
.siblings().removeClass('selected');
var selection = 'selected' + i; // new stuff starts here
$('footer #flag').removeAttr('class');
$('footer #flag').addClass(selection);
}
});
I don't know about sibling operators but this might work...
save all the images in one place.
give all links the same class. for this example ive used 'yourmenuclass'.
then query the document and listen for which one has been clicked.
then in the switch statement to assign a different image, depending on which one has been clicked.
function init() {
[].forEach.call(document.querySelectorAll('.yourmenuclass'), function (el) {
el.addEventListener('click', change);
});
function change() {
if (this.id == 'firstlink') {
var back = document.getElementById("footername");
back.style.backgroundImage =" url('http://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Ferns02.jpg/220px-Ferns02.jpg')";
}
if (this.id == 'secondlink') {
var back = document.getElementById("footername");
back.style.backgroundImage ="url('http://www.dailyshame.co.uk/wp-content/uploads/2012/09/badger.jpg')";
}
}
}
onload = init;
if you are using simple anchors then this may not work, but should be fine for buttons or image inputs.
js fiddle

PHP dynamically created checkboxes with JQuery .toggle()

I have dynamically created an array of checkboxes in PHP for a form, but I don't want the Submit button to appear unless at least one checkbox is checked. Scouring the Internet most people who want the Submit button to only appear after checking a checkbox only have one "I agree" checkbox. Is it the dynamic creation that is preventing my script working?
PHP↴
// Dynamically create checkboxes from database
function print_checkbox($db){
$i = 0;
foreach($db->query('SELECT * FROM hue_flag') as $row) {
if ($i == 0 || $i == 3 || $i== 6 || $i == 9){
echo '<br><br>';
}
$i++;
echo '<span class="'.$row['1'].'"><label for="'.$row['1'].'">'.ucfirst($row['1']).'</label><input type="checkbox" name="hue[]" id="hue" value="'.$row['0'].'"></span> ';
}
}
jQuery↴
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hue[]').click(function(){
$('#input_gown').toggle();
});
});
</script>
PHP function call↴
<?php print_checkbox($conn_normas_boudoir);?>
Admittedly I know nothing about jQuery or JavaScript and am still learning PHP. So, if there's a better way to implement this, let me know.
You're giving all your checkboxes the same ID. That's not allowed; IDs have to be unique.
An easy solution to both problems is to assign all the checkboxes a common class:
echo '<span class="'.$row['1'].'"><label for="'.$row['1'].'">'.ucfirst($row['1']).'</label><input type="checkbox" name="hue[]" class="hue" value="'.$row['0'].'"></span> ';
Then select the class in jQuery:
$('.hue').change(function(){
$('#input_gown').toggle();
});
But that may give unexpected results; what if two checkboxes are checked? The #input_gown element will toggle on and off again. Perhaps you only want it shown if at least one checkbox is checked:
$('.hue').change(function(){
var val = false;
$('.hue').each(function() {
val = val || $(this).is(':checked'); // any checked box will change val to true
});
$('#input_gown').toggle(val); // true=show, false=hide
});
http://jsfiddle.net/mblase75/AyY3Z/
Your jQuery selector is looking for elements with id hue[]. But your elements have the id of just hue.
Change this:↴
$(document).ready(function(){
$('#hue[]').click(function(){
$('#input_gown').toggle();
});
});
to this (IDs should really always be unique, and the square brackets will need to be escaped to work with the selector engine), (a demo)):↴
$(document).ready(function(){
$('input[name=hue\\[\\]]').click(function(){
$('#input_gown').toggle();
});
});

Imageslide with jQuery (Maybe with PHP)

Okay, so I have my div tag here and its css style 'background' is set to default.
For example
<div id="slideimage" style="background:url(01.jpg);width:xxpx;height:xxpx;"></div>
And I have my next button
Next
So I want to happen when I clicked on the Next button, the background style of #slideimage will change into 02.jpg. I tried searching with google but it seems it's not functioning properly.
That's all. Thanks in advance.
jsBin demo
var images = [
'01.jpg',
'02.jpg',
'03.jpg'
];
var iN = images.length;
var i = 0;
function changeImage(){
$('#slideimage').css({background: 'url('+images[++i % iN]+')'});
}
$('#next').click( changeImage );
Create an array of images, a var 'index counter' (i) and get the number of images in array (iN)
than you can easily toggle your images doing this math using Modulo: ++i % iN
Did you try this javascript:
function nextImage() {
$('#slideimage').css("background", "url(02.jpg)");
}
Here is a slightly more robust demo: http://jsfiddle.net/gQQBL/

Categories