Check multiple buttons with same id with JavaScript - javascript

I'm trying to build a website where people can make a reservation, I'm using a database to collect the times and php to display it. It displays all times within 5 days, including the ones that aren't available. They are displayed as buttons, all sharing the same id. I got stuck at the last step, disabling the buttons with unavailable times.
Since the only difference between these buttons is their background color (grey for unavailable and green for available) I figured I'd use a javascript function in which it checks the background colors of the boxes in a condition and then the grey ones get disabled and the green ones give a form. However: it'll only check the color of the first button and all buttons give the same result as that one.
My page will always display 50 buttons, so I thought I could just use a while loop with an auto-decrement at the end, however I can't seem to find out how to check the next button, it will now only check the same button again and again. Here's a part of the php-code to show the buttons with the right color (I've take some irrelevant parts out):
while($row = $results->fetch_assoc()){
$color = "##8fd6a5";
if (!empty($row['unavailable'])){
$color = "##9b9393";
}
$time= new DateTime($row['time']);
if ($time->format('H') == '08'){
echo '<button id="myBtn" onload="disablebuttons()" class="buttonstyle"
style="background-color: '.$color.'">'.$time>format('m/d H:i').'</button>';
}
}
This works entirely, but since all buttons have id="myBtn" when disablebuttons() executes, it only looks at the first button, following this code:
function disablebuttons() {
var amountButton = 50;
while (amountButton > 0){
var buttondisable = document.getElementById("myBtn");
if (buttondisable.style.backgroundColor == "rgb(155, 147, 147)"){
document.getElementById("myBtn").disabled = true;
amountButton--;
}
}
}
I've tried to delete the variable at the end of the while loop and place the "var buttondisable = document.getElementById("myBtn");" inside the loop, however this did not work.

IDs need to be unique so you need to use different ids for each button. To group them, give then same class say available if they are available unavailable if its not available. Something like this:
while($row = $results->fetch_assoc())
{
$color = "##8fd6a5";
$class= 'available'
if (!empty($row['unavailable']))
{
$color = "##9b9393";
$class= 'unavailable'
}
$time= new DateTime($row['time']);
if ($time->format('H') == '08')
{
echo '<button id="myBtn" onload="disablebuttons()" class="buttonstyle '.$class.'" style="background-color: '.$color.'">'.$time>format('m/d H:i').'</button>';
}
}
Now on javascript you can target specific buttons only like this:
var buttondAvailable = document.getElementByClassName("available");
OR
var buttondUnavailable = document.getElementByClassName("unavailable");

The id attribute should be unique in the same document, so use common classes instead of id's for your buttons like :
if ($time->format('H') == '08'){
echo '<button onload="disablebuttons()" class="buttonstyle myBtn"
style="background-color: '.$color.'">'.$time>format('m/d H:i').'</button>';
}
Then in your JS code loop through all the buttons using getElementsByClassName() :
var buttons = document.getElementsByClassName('myBtn');
for(var i = 0; i < buttons.length; i++)
{
//Your logic here
var button = buttons[i];
if (button.style.backgroundColor == "rgb(155, 147, 147)")
{
button.disabled = true;
}
}
Hope this helps.

if you get the parent element and loop their childrens, you can check each element and his background and disable it.
$('#mydiv').children('button').each(function () {
// "this" is the current element in the loop
if($(this).css("background-color") == "rgb(155, 147, 147)"){
$(this).disabled = true;
}
});

Related

onclick variable is not passing to a form

I'm a newbie to Javascript and from what I've read I assume there is a much better way to my approach, but here it goes.
I have a form with onclick such that when a clear image is clicked on in a table cell, the background pic of the cell changes (showing that it has been selected, or unselected if clicked again). That all works, now I want to define some variable so that when the form's Submit button is pressed, a form variable is passed showing whether or not the user selected that option.
The functional javascript I found on the internet:
var curPic1 = 0;
window.onload=function() {
document.getElementById('clear-kayangan').onclick=function() {
curPic1 = (curPic1 == 0)? 1 : 0;
document.getElementById('td_kayangan').style.backgroundImage = (curPic1 == 1)? 'url("pics/map-kayangan-lake-selected.png")' : 'url("pics/map-kayangan-lake.png")';
}
}
My plan was to write an IF statement stating if curPic1 == 1 (the background image chosen shows that the user has selected), I would create a Global variable which I could then pass on to php in the form:
$spot1 = "<script>document.write(spot1);</script>";
if ($spot1 == 1) echo "<input name='spot1' type='hidden' value='1' />";
For testing purposes I tried:
$spot1=$_POST['spot1'];
if ($spot1=="1") echo "<b>This really works</b><br>";
and it works if I use If $spot1==0, whereby at the top of my javascript function I tried the following:
int spot1;
spot1=0;
var spot1=0;
and within the javascript function itself I tried:
int spot1 = 1;
spot1 = 1;
window.spot1 = 1;
I haven't yet tried the IF statement because I'm just trying to test things if they work. I read that I was supposed to be able to establish a Global variable from within a function. I added the various options above one at a time. It works with spot=0, so I assume the problem is that it is not being set as a Global variable within the function? Or perhaps there is a better approach to all this?
On Submit the hidden form variables will eventually be passed to another page and used there.
Declare hidden variable in the form, and set it's value to 0 or 1 in onclick fuction of image. When form is submitted, this value will also be passed to server
as #santosh-sawant said, you should add an id to the hidden input and change the value in the same click handler you already have, like:
<?php
$spot1 = $_POST['spot1']=='1' ? 1 : 0;
?>
<input name="spot1" id="spot1" type="hidden" value="<?=$spot1?>">
and then in your JS:
var curPic1 = 0;
window.onload = function() {
document.getElementById('clear-kayangan').onclick = function() {
curPic1 = (curPic1 == 0) ? 1 : 0;
document.getElementById('td_kayangan').style.backgroundImage = curPic1 ? 'url("pics/map-kayangan-lake-selected.png")' : 'url("pics/map-kayangan-lake.png")';
document.getElementById('spot1').value = curPic1;
}
}

change rows depending on the ordernumber in database

I'm creating for my education-project a pizza-ordering website. With the help of the stackoverflow-community I've achieved already a lot - so thank you! But now I'm stuck and can't find any working solution to my problem.
Question
How can I change the row color alternating (white / grey / white / grey ...) depending on the ordernumber in the database(mysqli)? The ordernumber can be in more than one row, so I can not simple change the color row by row.
I've tried with jquery, but this works only if the ordering numbers remain always in the list (even/odd) ... if an order is cancelled, then it doesn't works anymore (see image with missing ordernumber 7)
Here is the code in jquery:
$(document).ready(function() {
var check = 0;
for(var i =0; i<= $("tr").length;i++){
$("tr").each(function(){
if(parseInt($(this).find("#bestnr").text())==check){
if(check%2 == 0){
$(this).css("background-color","white");
}else{
$(this).css("background-color","#DCDCDC");
}
}
});
check +=1;
}
});
Any ideas? Thanks for your help!
Since you're working with JQuery, something like this ought to do the trick - explanations in code comments.
$(document).ready(function() {
// define the initial "previous order id" as 0 assuming
// there will never be an order with id 0
var previousOrderId = 0;
var previousBgColour = '#dcdcdc';
var thisBgColour;
// loop the table rows
$("tr").each(function() {
// determine "this" row id (assuming bestnr is short for bestelnummer)
// and that the text in that table cell *is* the order number
// I've changed this to a class as an id HAS to be unique
// you'll need to update your code to accommodate
var thisOrderId = parseInt($(this).find(".bestnr").text());
// define the background colour based on whether the order id has changed
// if it has change it
if(thisOrderId != previousOrderId) {
thisBgColour = previousBgColour == '#dcdcdc' ? '#ffffff' : '#dcdcdc';
previousBgColour = thisBgColour;
}
else {
thisBgColour = previousBgColour;
}
$(this).css({'background-color' : thisBgColour});
//update the previousOrderId to this id
previousOrderId = thisOrderId;
});
});
You're basically storing the previous order id and comparing it to the current order id - if the order id hasn't changed it'll use the previous background colour, if it has it'll flipflop it to the alternate colour.
If it is just alternating colors, you can use CSS directly and not worry about anything else:
tr:nth-child(odd) {
background-color:white;
}
tr:nth-child(even) {
background-color:#DCDCDC;
}
If this is somehow dependent on logic from the backend, we can look at adding a class in jQuery and adding colors to this class via CSS

Multiple input and multiple output with onclick eventlistener in javascript

Want to ask :
For example , i have multiple button and when i click on anyone, the value will be shown at the result textbox and the input textbox will back to 0 , need help on check my code :
document.getElementById("plusthevalue").addEventListener('click',function plus()
{
var inputvalue = document.getElementById("Input");
var resultvalue = document.getElementById("Result");
document.write("Result").value = inputvalue + resultvalue;
document.write("Input").value ="0";
});
and, if i want to write a single statement that can include all the button and will display the output depend on the button, how would the code will be?
p/s: i know i can hardwork until i code function for every button but that would be very messy , i want to include all :(
You can assign all your buttons a certain class, then use document.querySelectorAll('.myclass') to grab all of them. Then you can loop through the results to add the event listener to each of them.
Example:
var myButtons = document.querySelectorAll('.myclass');
for (i = 0; i < myButtons.length; ++i) {
myButtons[i].addEventListener('click', function(e) {
// Do stuff
}
}
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for more info about querySelectorAll.

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

making text boxes visible

I have a drop down if i click it will retrieve values from db.If thre are 4 values that has to pass into text box and make it visible.If 5 values then 5 values has to get visible.There will be a count if 4 boxes count has to get into 5th box.if 5 values then count has to get int0 6th box.
How do i do it?
If the text boxes are in the markup and you've just hidden them (e.g., style="display: none"), you can show them again by setting their style.display property to "":
textBoxElement.style.display = "";
For example, here's a button click handler that looks for a text field to show and shows it; if there aren't any more to show, it hides the button:
var myForm = document.getElementById('myForm');
document.getElementById('btnShowField').onclick = function() {
var index, field, foundOne, foundMore;
foundOne = foundMore = false;
for (index = 0; index < myForm.elements.length; ++index) {
field = myForm.elements[index];
if (field.type === "text" && field.style.display === "none") {
if (!foundOne) {
// Found one, show it
field.style.display = "";
foundOne = true;
}
else {
// Found more, so we don't need to hide the button
foundMore = true;
break;
}
}
}
if (!foundMore) {
// No more hidden fields, hide the button
this.style.display = "none";
}
};
Live example
If you want to add more text boxes to a form at runtime when they aren't in the markup, you can easily do that:
var textBox = document.createElement('input');
textBox.type = "text";
textBox.name = "somename";
formElement.appendChild(textBox);
Live example
Usually the structure will be a bit more complex than that, but that's the general idea.
Off-topic: A lot of these things can be made dramatically easier by leveraging a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser differences and provide a lot of value-add functionality, so you can focus on what you're actually trying to do rather than browser quirks and such.

Categories

Resources