Appending Html Classes To Elements - javascript

I asked a question yesterday (Button That When Clicked Will Display Hidden Column in HTML Table). The Name is self-explanatory however, after hours of trying new things and failing I decided to research a different approach. Here is what came up with:
A button that when clicked will append a new class to an element
By doing this, we will toggle a column's visibility by using the 'display' function in css
I have the following HTML element:
echo "<td class =\"development\" id = 'tag$i'>test1</th>";
echo "<td class =\"development\" id = 'tag$i'>test2</th>";
echo "<td class =\"development\" id = 'tag$i'>test3</th>";
$i is the row number so picture each of these <td> being wrapped inside a forloop to create a column.
With Css:
.development{
text-align:center;
padding-left:10px;
display:block;
}
.hide{
display:none;
}
So this is where I will need your help. I propose a button that when clicked will run a JavaScript function that can append the '.hide' class to the td tags.
<button onclick="addCss()">Click me</button>
I am not sure how to write the JavaScript and if I need to pass any parameters such as the id's for the <td> tags.

document.getElementById('yourId').className += ' ClassName'
//To select elements by class name.
document.getElementsByClassName('yourId')
Note: the space after the first ' for the appended class name is important.
Why? : If you have the class name "class1" and append "class2" - It will result in "class1class2"
By adding the space, it will result in "class1 class2" and be recognized as two separate classes.
<button onclick="document.getElementById('yourId').className += ' ClassName';">Click me</button>
If you want to make a better solution.
<script>
function addCss(element) {
document.getElementById(element).className += ' ClassName';
}
</script>
Then just call the function like you originally had. You could even add a parameter for the class name itself.

to override a class document.getElementById("id").className = "newclass";
to add a new class document.getElementById("id").className += " anotherclass";
function addCss(){
document.getElementById("b").className = "hide";
}
function newCss(){
document.getElementById("b").className = "show";
}
body {
font-size: 3em;
background: honeydew;
}
.hide {
display: none;
}
.show {
display: table-cell;
}
<table>
<tr>
<td id=a style="background:skyblue">A</td>
<td id=b style="background:yellowgreen">B</td>
<td id=c style="background:gold">C</td>
<td id=d style="background:orangered">D</td>
</tr>
</table>
<button onclick="addCss()">hide B cell</button>
<button onclick="newCss()">show B cell</button>

Using jQuery, you can add this in the addCss function:
$('td').addClass('hide');

Related

Increment var in td

I am trying to increment a var when I add a new tr
Table
<table id='myTable'>
<tr>
<td id="count"></td>
<td><select><option value="1">1</option></select></td>
<!--obviously some more options-->
</tr>
</table>
<button onclick="addfield()">Add</button>
Script
<script>
var row = 1;
function addfield() {
document.getElementById("count").innerHTML = row;
$("#myTable").find('tbody').append($('<tr>').append($('<td id="count">')).append($('<td><select><option value="1">1</option></select>')));
row++;
}
</script>
What's happening is, that the script is incrementing the first 'td id="count"'-Tag when adding a new 'tr'-Tag instead of incrementing the next 'td'-Tag. Additionally it doesn't show the count in the new generated 'td'-Tag.
What am I missing?
Okay, so first off let me go ahead and say that I blew up your HTML structure because it looks to me like you are using a table to do something that is not tabular, so I changed the structure to be divs. I also took the incrementing out of your script and used CSS counters to get the same effect. if using a table to hold your data is critical after all, then I guess you won't choose this answer.
HTML
<div id="myTable">
<div class="row">
<div class="cellish"><select><option value="1">1</option></select>
</div>
</div>
</div>
<button onclick="addfield()">Add</button>
CSS
body {
counter-reset: count;
}
.cellish {
display: inline-block;
}
.cellish::before {
content: counter(count) " ";
counter-increment: count;
}
JS
function addfield() {
$("#myTable").append($('<div class="row">')).append($('<div class="cellish"><select><option value="1">1</option></select>'));
}
You should not use the same id multiple times in html elements.
Change like this:
$("#myTable").find('tbody').append($('<tr>').append($('<td><select><option value="1">1</option></select>')));

detecting class changes in Bootstrap Switch Jquery (converting working checkbox JS to button js)

I am trying to convert a piece of JQuery that changes the class of a tr when checked to a piece of JQuery that changes the class of a tr when a button gets a class called "active". I am a JQuery/Javascript newbie and I am at a loss.
For those who have suggested it's a duplicate, I have tried to detect class and failed (updated code below).
ORIGINAL CODE (THAT WORKS)
javascript:
var $input_class = $('.addCheckbox');
function setClass() {
var tr = $(this).closest( "tr" );
if ($(this).prop('checked') == true){
tr.addClass( "highlight" );
}
else{
tr.removeClass( "highlight" );
}
}
for(var i=0; i<$input_class.length; i++) {
$input_class[i].onclick = setClass;
}
MY HORRIBLE TRY (UPDATED BELOW...NO LONGER THIS)
javascript:
var $input_class = $('.btn-group .btn-toggle .btn');
function setClass() {
var tr = $(this).closest( "tr" );
if ($(this).prop('.btn-success .active')){
tr.addClass( "highlight" );
}
else{
tr.removeClass( "highlight" );
}
}
for(var i=0; i<$input_class.length; i++) {
$input_class[i].onclick = setClass;
}
I am using the Bootstrap Switch Plugin which converts checkboxes to toggles
http://www.bootstrap-switch.org/
The converted html looks like this:
<tr>
<td width="15px"><input class="addCheckbox" type="checkbox" value="true" style="display: none;">
<div class="btn-group btn-toggle" style="white-space: nowrap;">
<button class="btn active btn-success btn-md" style="float: none; display: inline-block; margin-right: 0px;">YES</button>
<button class="btn btn-default btn-md" style="float: none; display: inline-block; margin-left: 0px;"> </button>
</div>
</td>
<td width="85px">May 2016</td><td class="restaurant-name">
Joe's Crab Shack
</td>
<td class="text-center">
#my table info
</td>
</tr>
UPDATE!!! As per 'duplicate' suggestions.
After looking through this question (which was very helpful), I have changed my code to this, and I still can't get it to work. I am wondering if it is having trouble finding the exact input class? Because the plugin converts the checkbox to html, I can't (or don't know how) set specific names or ids for the buttons.
javascript:
var $input_class = $('.btn');
var tr = $(this).closest( "tr" );
function checkForChanges()
{
if ($('.btn').hasClass('btn-success'))
tr.addClass( "highlight" );
else
tr.removeClass( "highlight" );
}
for(var i=0; i<$input_class.length; i++) {
$input_class[i].onclick = checkForChanges;
}
There are issues in your code resulting from not being familiar with the language. Also keep in mind this jQuery what you posted, not javascript.
As I am not quite sure what is your final objective here so let's go step by step.
First of all:
$('.btn-group .btn-toggle .btn');
The above means an element with all three classes class="btn-group btn-toggle btn" and I do not see such in your code. Are you sure you didn't want to use $('.btn-group, .btn-toggle, .btn'); ? At the moment var $input_class is empty, so later in your code you loop through nothing.
Second thing:
as I posted in the comments make sure you run your script after loading jQuery and rest of the content of the page. If your script is above jQuery, like this:
<head>
<script type="text/javascript">/* Your script here */</script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
Above won't work for two reasons:
You run your script before you load the jQuery, so commands like $(".class") aren't understood.
You run your script before loading the content, so for example var $input_class = $('.addCheckbox'); will be empty, because the element with class addCheckbox doesn't exist yet. [for this one assume jQuery is included before the script, but the script is still inside the <head>].

How can I make inputs display inline?

I can't seem to figure out how to display the two inputs in the following code as {display: inline} format so that they appear next to each other rather than on separate lines. I've looked at other posts and have tried jQuery, <style> tags, .setAttribute etc. in order to try and add this CSS style.
I've also tried to create a class in the HTML with the requisite display: inline command in the CSS. I created this function to open up once a button on my homepage is clicked. Everything works fine, I just want the two inputs (text and button) to line up next to each other.
Any idea of where I am going wrong? I am a beginner.
var counter = 1;
var limit = 2;
var newdiv = document.createElement('div');
function addInput(divName){
if (counter == limit) {
(counter);
}
else {
nFilter.className = 'input';
newdiv.setAttribute("style", "display: inline;");
newdiv.innerHTML = "<br><input type='text' placeholder='Postal Code' name='myInputs[]'> " + " <input type='button' value='Lets Go!' onclick='url(file:///C:/Users/Joy/Documents/ZapList/HoldingPage.php)'>";
document.getElementById(divName).appendChild(newdiv).span;
counter++;
}
}
Inputs are inline-block by default, so if there is space they will display inline, if not they will wrap to the next line. Either make sure the containing elements are wide enough to accommodate your inputs or try:
newdiv.setAttribute("style", "display: inline;white-space:nowrap;");
to stop the inputs from wrapping, note that this style is applied to the div not the inputs, you may actually want to remove display:inline;.
just using style='float:left;' for each input element
<html>
<head>
<title>this is a test</title>
<meta content="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="a"></div>
<script type="text/javascript">
var counter = 1;
var limit = 2;
var newdiv = document.createElement('div');
function addInput(divName){
if (counter != limit) {
newdiv.innerHTML = "<br><input type='text' placeholder='Postal Code' name='myInputs[]' style='float:left;'> " + " <input type='button' style='float:left;' value='Lets Go!' onclick='url(file:///C:/Users/Joy/Documents/ZapList/HoldingPage.php)'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
addInput("a");
</script>
</body>
</html>
If I get you right, then you want to display two textBoxes when a button is clicked...
You can make it pretty simple and take the document.write command.
e.g.
<body>
<input type="button" value="Click me" onClick="makeSmth()"></input>
</body>
<script>
function makeSmth() {
document.write("<br><input type='text' id='textBox01'></input>");
}
</script>
I think this link may be
handy
In that case, they resolved from the form tag, and creating a css class:
.form-inline {
display: flex;
flex-flow: row wrap;
align-items: center;
}

Change tr background color when img inside td is clicked

well i am filling a table with php with values from DB
what i was trying to but unsuccessful didnt is to change the tr background color when image is clicked
here is what i tried to do
<script>
function changeColor(tr)
{
var tableRow = document.getElementById(tr);
tableRow.style.backgroundColor='red';
}
</script>
<html>
<table>
<tr id='tr<?php echo $personID;?>'>
<td>
<?php echo $personName;?>
</td>
<td>
<?php echo $personLastName;?>
</td>
<td>
<img src= "/*an image*/" onmouseover="" style="cursor: pointer;" onclick="changeColor('tr<?php echo $personID;?>')" >
</td>
</tr>
</table>
</html>
obiously this is just for one case but when i get elements from DB this table is pretty long
any ideas?
THANKS IN ADVANCE
one more thing
my table already has an css design where
td
{
background: #EDEDED;
}
tr:hover
{
background: #d0dafd;
}
this is maybe why when doing onclick="this.parentNode.parentNode.style.background='gray'"
is not working how can i fix this?
You could simply use parentNode : DEMO
<img src="http://dummyimage.com/50x50"
onmouseover="this.parentNode.parentNode.style.background='gray'"
onmouseout="this.parentNode.parentNode.style.background=''"
/>
img->parentNode=td -> parentNode=tr
jQuery code
//code for clicks
$('td img').click(function() {
$(this).closest('table').children('tr').removeClass('highlight');
$(this).closest('tr').addClass('highlight');
});
//code for hovering
$('tr').hover(function() {
//if the tr has the highlight class do nothing, otherwise add hover style
if(!$(this).hasClass('highlight')) {
$(this).addClass('hoverStyle');
}
}, function() {
//if the tr has hover style remove it when hover ends
if($(this).hasClass('hoverStyle')) {
$(this).removeClass('hoverStyle');
}
});
Then just make a CSS class to define the highlight style.

How to style Input type button in html

I have a following fragment of code which inserts a Click Button and open a google page in my CRM. How can i style my button. The button is present in the input tab dow below.What are the opptions. to maka a button more smoother and superb
<script>
function openLink(target){
window.open('https://google.co.in','_blank');
}
function addCustomButton()
{
var mergeNode = document.getElementById("BTN_TB_AccountForm_MergeWizard").parentNode.parentNode.parentNode.parentNode;
var parent=mergeNode.parentNode;
//BTN_TB_AccountForm_MergeWizard is the ID of the Merge Button on the ActionForm Bar
//Create a TD node and attach a buttom element.
var td2 = document.createElement("td");
td2.innerHTML="<input type=button value=Click onclick=\"openLink()\">";
//Append Child
parent.insertBefore(td2,mergeNode.nextSibling);
}
}
setTimeout ( "addCustomButton()", 1000 ); // To be sure the Action Bar is loaded
</script>
you can style it using the:
input {
your css here
}
or to be more specific use:
input[type=button]
You can try to set css class of button:
<input type="button" class="MyButton" value="Click" onclick="openLink();">
and set inner html of td like this:
td2.innerHTML="<input type='button' class='MyButton' value='Click' onclick=\"openLink();\">";
CSS (this style only for demostration you can set your specific or according your requriment):
.MyButton{
color: #ffffff;
background-color: #1EAA49;
*background-color: #1EAA49;
border-color: #4cae4c;
}

Categories