I wrote a javascript function that change the style of a div (here a TR tag) when I select a radio button in form (called by onchange event).
function handleCheck(myRadio) {
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.style.backgroundColor = "black";
col.style.color = "white";
}
However, often when you select option X another option is deselected while you can select only one value at the time in the same. This option is not triggered by the onchange event. Is there a way to determine that a radio button is not checked any more?
You will have to clear previously assigned classes. Take a look at this example:
function handleCheck(myRadio) {
clear(myRadio.className);
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.className += ' selected';
}
function clear(className) {
var tr = document.querySelectorAll('tr.vak' + className);
for (var i = 0; i < tr.length; i++) {
tr[i].className = 'vak' + className;
}
}
Demo: http://jsfiddle.net/abh7guv5/
If I understood correctly what you are trying to achieve, simply read document.getElementById("myRadio").checked - it will be true or false
well, if I understand you correctly, you have a function that applies some styles whenever you check a radio button, but you also would like to remove styles from elements, that corresponds to already unchecked buttons. If yes, you can store your previous checked item in a variable, then you might want something like:
var previousElement = null;
function handleCheck(myRadio) {
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.style.backgroundColor = "black";
col.style.color = "white";
if(previousElement!==null&&previousElement!==col){
previousElement.style.color = ""; // or whatever you want
}
previousElement = col;
}
Related
I am new to Javascript. I want to create a 15x15 table full of buttons and change the color of the button to red when clicking each one. The table is fine but the color is not working.
function createTable(){
var table = document.createElement('table');
for(var x = 0; x < 15; x++) {
var row = table.insertRow();
for(var y = 0; y < 15; y++) {
var cell = row.insertCell();
var button = cell.appendChild(document.createElement('button'));
var buttID = String('butt' + '_' + x + '_' + y);
button.setAttribute('id', 'buttID');
button.setAttribute('onclick', 'mark()');
}
}
document.getElementById('puzzle').appendChild(table);
}
function mark(){
document.getElementById('buttID').style.color = "red";
}
I am not sure if the button.setAttribute is wrong. I also tried the following way, but the entire table just disappears this time. Any ideas about that?
button.onclick = mark();
Maybe the way I create id for every cell is wrong? I am not sure about that.
This line is wrong and will not work:
document.getElementById('buttID').style.color = "red";
That is attempting to access a button with id equal to the string "buttID", but there is no such button.
But you don't need ids on the buttons at all. Instead, you can set the button's onclick function like this:
button.onclick = mark;
Then, define your mark function like this:
function mark() {
let button = this; // 'this' is the button that was clicked
button.style.color = 'red';
}
function createTable() {
var table = document.createElement('table');
for (var x = 0; x < 15; x++) {
var row = table.insertRow();
for (var y = 0; y < 15; y++) {
var cell = row.insertCell();
var button = cell.appendChild(document.createElement('button'));
button.className = 'btn';
button.onclick = mark;
}
}
puzzle.innerHTML = '';
puzzle.appendChild(table);
}
function mark() {
let button = this;
button.style.backgroundColor = "red";
}
const puzzle = document.getElementById('puzzle');
.btn {
border: none;
margin: 0;
width: 1em;
height: 1em;
background-color: white;
}
body {
background-color: #eee;
}
<button onclick="createTable();">Create Table</button>
<div id="puzzle"></div>
Change this:
var cell = row.insertCell();
var button = cell.appendChild(document.createElement('button'));
var buttID = String('butt' + '_' + x + '_' + y);
button.setAttribute('id', 'buttID');
button.setAttribute('onclick', 'mark()');
To this:
var cell = row.insertCell();
// Store the reference to the actual button and not the cell that contains it
var button = document.createElement('button');
// Bind the onclick event of the button to your mark function
// Also remember that you only need the parenthesis if you are calling a function, here we are only passing it
button.onclick = mark;
// Add your button to your table cell
cell.appendChild(button);
You will also have to edit your mark function to look like this:
function mark(e){
e.target.style.background = 'red';
}
This may seem confusing and you are probably asking where that variable 'e' comes from. Basically events like 'onclick' will always pass an event object to their handling functions. By putting a variable in the handling functions parenthesis the event object will automatically be placed into that variable.
The event object has lots of information about the event. You can see all of the information it provides here.
The one we want is the 'target' - the element that triggered the event which will be whatever button that was clicked in this case.
The target is an HTML element so we can then set it's style.background to a value of 'red'.
Beginner here. I have a loop that creates 26 buttons with unique ID's and values. What I'm struggling with is figuring out the proper way to send the button's ID to a function so that I can store unique vars for each button independently without creating more than one function. I currently have an array with the 26 items I need for my buttons and the following loop:
function makeButtons() {
for (var i = 0; i < 26; i++) {
document.getElementById("whereButtonsGo").innerHTML += "<input type = 'button' value = '" + items[i] + "' id = 'button" + items[i] + "' onclick = doThing(button" + items[i] + ")'>";
}
}
I want the argument in the onclick function to be sent to a function such as:
function doThing(id) {
document.getElementById("'" + id.value + "'").style.color = "pink";
}
But so far I haven't been able to get this to work. Any help would be greatly appreciated!
Maybe this is what you are looking for:
makeButtons();
function makeButtons() {
for (var i = 0; i < 26; i++) {
document.getElementById("whereButtonsGo").innerHTML += "<input type = 'button' value = '" + i + "' onclick = doThing(this)>";
}
}
function doThing(currentButton) {
currentButton.style.color = "pink";
}
<div id="whereButtonsGo"/>
Try to keep the IDs as simple as possible
I recommend against using innerHTML for creating elements that you actually want to do something. Even if it works, your code will be amazingly unclear. Instead, write code that demonstrates that you're actually creating and adding elements:
var items = [1,2,3,4,5,6];
function makeButtons() {
var container = document.getElementById("whereButtonsGo");
for (var i = 0; i < items.length; i++) {
var button = document.createElement("button");
button.type = 'button';
button.value = items[i];
button.innerText = items[i];
button.id = 'button'+items[i];
button.onclick = doThing;
container.append(button)
}
}
function doThing() {
console.log('click of ' + this.id);
}
makeButtons();
Note that you don't need to pass the id in the function call for the event - the button that was clicked will be available as this.
Here is a fiddle.
I have a list with names, each name has a sublist with subitems.
I need to pass those subitems to the table when I click on the name.
Here is an example, try to expand the first name.
But if I click on it again, it will keep adding that value to different cells of the table. How may I add this only once ? Or always at the same place?
Also, I have some attributes of the disciplines:
data-time = The time the discipline start;
data-id = The ID of that discipline (all brought from database);
My Code:
/*JQuery*/
$(document).ready(function(){
$(".prof-list h3").click(function(event){
var obj = event.target;
var disciplina_id = $(this).next().find('li').data('id');
var disciplina_hora = $(this).next().find('li').data('time');
if(disciplina_hora == "14:30:00"){
var myRow = document.getElementById("prof-table").rows[3];
myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
}
else if(disciplina_hora == "08:30:00"){
var myRow = document.getElementById("prof-table").rows[1];
myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
}
if(obj.nodeName == "H3")
$(this).next().slideToggle();//Aplica efeito slide
//$("#list_prof").html("clicked: " + event.target.nodeName ); //Teste
})
})
use .cells[] to update cell content
if(disciplina_hora == "14:30:00"){
var myRow = document.getElementById("prof-table").rows[3];
// insert if `myRow` only has 1 cell
if(myRow.cells.length <= 1)
myRow.insertCell(1);
// use `cells[1]` to update the 2nd cell content
myRow.cells[1].innerHTML = $(this).next().find('li').text();
}
Edit Update
if(myRow.cells.length <= 1){
$(this).next().find('li').each(function(idx, elm) {
myRow.insertCell(idx + 1);
myRow.cells[idx + 1].innerHTML = $(elm).text();
});
} else {
while(myRow.cells.length > 1)
myRow.deleteCell(1);
}
I have a table with n number of rows with checkboxes and a what i want to do is if i select a checkbox the value should go to the text area, so i stored all elements in an array first, but it isnt happening, as you can see i added alerts as well to check it out. please help.
window.onload = function () {
var oRows = document.getElementById('rnatable').getElementsByTagName('tr');
var iRowCount = oRows.length;
alert('Your table has ' + iRowCount + ' rows.');
var i = 0;
cb = new Array(iRowCount);
while (i <= iRowCount) {
var id = 'check'+ i;
cb[i] = document.getElementById(id);
i++;
}
//alert('Your table has ' + cb[i].value + ' rows.');
for(var a=0; a < iRowCount; a++) {
var fasta = document.getElementById('fasta');
if(cb[a].checked) {
fasta.value = cb.value + ",";
};
};
}
Are you seeing an error in the console? I suspect that when while (i <= iRowCount) runs when i === iRowCount that document.getElementById(id) isn't yielding a result, and that then when you use that value, bad things happen.
Also, each lap through the fasta loop overwrites the previous value. You probably want something like fasta.value += cb.value + ","; instead.
I am trying to get the value from a checkbox using javascript.
I want only one checkbox value to be passed to the javascript function, and if multiple are selected, an alert box informing that only one box can be checked for the function.
I've tried this:
var publish_trigger = document.querySelector("#publish_trigger");
publish_trigger.onclick = function() {
var _posts = document.getElementsByName('post_id[]');
var check = _posts.checked;
var boxes = _posts.length;
var txt = "";
if(check.length > 1) {
alert("Only one at a time");
} else {
for (i = 0; i < boxes; i++) {
if (_posts[i].checked) {
txt = txt + _posts[i].value + " "
}
}
}
alert(txt);
return false;
}
This code is wrong:
var _posts = document.getElementsByName('post_id[]');
var check = _posts.checked;
getElementsByName() returns a NodeList (effectively an array) of elements, so your variable _posts doesn't have a checked property. You need to loop through _posts to count the checked property on the individual elements within _posts.
You already have a for loop so add the validation in there:
var count = 0;
for (var i = 0; i < boxes; i++) {
if (_posts[i].checked) {
if (++count > 1) {
alert("Only one checkbox may be checked at a time.");
return false;
}
// I don't know what you're trying to do with the following line
// but I've left it in.
txt = txt + _posts[i].value + " "
}
}
(Note: unrelated to your question, you should declare the loop counter i within your function otherwise it will be global and might lead to hard to debug problems if you are using it in other places too.)