onclick variable is not passing to a form - javascript

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;
}
}

Related

Check multiple buttons with same id with 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;
}
});

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.

For every textarea i create, i want it to have its 'personal word count' on it.

The code below is to appear additional 2 textbox and 1 textarea everytime i click a button.
var x=1;
var count=0;
$('body').on('click','#add',function()
{
if(count < 6)
{
$('#div').append("<div class='line'><input type='text' name = 'txta"+x+ "' id='txta"+ x +"'><span class =wordtab></span> <textarea rows='9' onkeyup='countChar2(this)' cols='50' name = 'txtc"+x+ "' id='txtc"+ x +"'></textarea> <span class =wordtab></span><input style = 'width:50px' type='text' name = 'txtb"+x+"' id='txtb"+ x +"'><span class =wordtab></span><button class='delete' value ='Delete Row'>Delete Row</button></div><div style='margin-left: 750px' id='charNum" + x + "'></div>");
count++;
x++;
}
else
alert("Maximum 6 Skills");
});
$('body').on('click','.delete',function()
{
$(this).closest('.line').remove();
count--;
});
The below function is the code that i currently have (which i know its wrong) to put in a counter for every textarea that i added in.
function countChar2(val)
{
var len = val.value.length;
if (len >= 200)
{
val.value = val.value.substring(0, 500);
}
else
{
var id = "charNum" + x;
$(id).text((200 - len)+" words left");
}
};
So my goal is that everytime i click on the add row and start typing on the textarea, it will show the word count for that particular texarea just right below the textarea box.
To get a unique counter added to each textarea, you could append another div to the textarea with a specific class e.g.
Set the HTML structure to something such as:
<textarea></textarea><div class='text-count-area'>Word Count: 0</div>
Add the following JS at the point where each textarea is added e.g. just before 'count++' in your original code (note: this is not the most efficient way of doing this, but this will work easily with your current code):
// Bind the text area to the keyup event
$("textarea").on('keyup', function(val) {
// Simple word count
var words = this.value.match(/\S+/g).length;
// Write the word count to the immediate text-count-area div afterwards
$(this).next(".text-count-area").text("Text count" + words);
});
The word count is kept simple here for readability, but the logic from other answers (highlighted in the comments) could be implemented at this stage.
A JS Fiddle demo of this working is here.
Let see your example:
You add each div by .append method, it's correct
You count input symbols by onkeyup event, it's correct too
All you need is update your countChar2 function because this function has wrong body in that lines:
var id = "charNum" + x;
$(id).text((200 - len)+" words left");
First of all: try to debug your code via developer tools in your favorite browser with breaks in that lines. This step can give your much more and quickly info than posting question in stackoverflow :)
For onkeyup event you should use link to this object instead of id inside your function:
$(val).parent().find('.words-left').val((200 - len));
This line uses val as a link to textarea object in just appended line. .parent() gives you access to wrapper and find() finds input for words left field. (I've added '.words-left' class to your input, see my fiddler bellow). And this code works in stage of your just added line.
Your code of $('body').click() should be executed, when document is fully loaded and DOM ready. But all your ids that you will create in future doesn't appends that DOM. That's why your delete function works properly - that function uses class selector instead of id.
Proposed by me code doesn't uses id selector because it is not needed. All that needs to me - link to current object in new line, val - what I need for that operation.
BTW: When you implement function that works with objects, such as onkeyup='countChar2(this)', better way to use object as passed variable - var countChar = function(obj) {. Because val is using for scalar values in common way.
You can check my code here https://jsfiddle.net/jo0cd3yr/1/

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.

How do I create the html for the following enable/disable javascript to create a button to change the localstorage value?

I have the following javascript that cannot be changed.
Basically I need to make the UI for this, which is probably really basic html.
if(!localStorage.status) localStorage['status'] = 1;
toggle(2);
enable.onclick = function(){toggle(0)};
disable.onclick = function(){toggle(1)};
function toggle(n){
if((n == 0) && (enable.parentNode == list)){
list.removeChild(enable);
list.appendChild(disable);
localStorage.status = 1;
}else if((n == 1) && (disable.parentNode == list)){
list.removeChild(disable);
list.appendChild(enable);
localStorage.status = 0;
}else if((n == 2) && (!list.hasChildNodes())){
list.appendChild((localStorage.status == 1) ? disable : enable);
chrome.browserAction.setIcon({path: (localStorage.status == 1) ? "1.png" : "2.png"});
}else{
return;
}
}
I think what it's doing is creating and enable/disable button. But I'm not sure.
Basically I need the html to display enable or disable, and on click it changes and updates the localstorage value for 'status'.
Remember we can't change the javascript, I just need the html.
_
The quoted code requires variables enable and disable to be HTMLElement objects (so they can be appended to list, which I assume is a DIV) that accept click events. So pretty much any kind of element will do.
However, it looks like BUTTONs would make the most sense, so I'd suggest creating the elements in javascript as
var enable = document.createElement("button"); //create a <BUTTON>
enable.id = "enable";
enable.type = "button";
enable.textContent = "Enable"; //the displayed text
and similarly for disable. If you'd prefer not to add additional scripts to the page, the equivalent HTML markup to use is
<button id="enable" type="button">Enable</button>

Categories

Resources