How can I change the label for css style? - javascript

I have a checkbox with label.
<input type="checkbox" name="comment" id="abc1" value="the value."
onclick="createOrder()"><label for="abc1" onclick="createOrder()"
title="title"> onscreen text for this checkbox </label>
In a javascript function, I want to change the appearance of the input. Here is an example that works (changes the element's visibility) but is not what I want to do:
if (n !== -1) {
document.getElementById(id).style.visibility = "hidden";
}
However, I don't want to make it invisible. I want to change the text color of the words associated with the checkbox ("onscreen text for this checkbox") The text would change from the default black to grey.
I don't know how to change the "label for" style. Can anyone help change the javascript? The result would simply change the color of the text.

As you said the code you're trying works so to target next node, you can use .nextSibling
if (n !== -1) {
document.getElementById(id).nextSibling.style.color= "#c8c8c8"; //color you need"
}
else{
document.getElementById(id).nextSibling.style.color= "#fefefe"; //Default color
}

You can do something like using jQuery:
jQuery:
$(document).ready(function(ee){
$("#abc1").click(function(){
if ($(this).is(':checked')) {
$(this).next().css({"color": "Red"});
}else
{
$(this).next().css({"color": "black"});
}
});
});
HTML:
<input type="checkbox" name="comment" id="abc1" value="the value." ><label for="abc1" title="title"> onscreen text for this checkbox </label>
This should work.
Thanks

it can easily be achieved, doesnt matter where the label is located or how many are there.
there is an answer Here that shows how to get elements by their attributes.
lets take the function from that answer, adjust it and use it for your question:
//get all labels with for=abc1 attribute
el=getLabelByForAttribute("abc1");
//loop through those labels and change their style
el.forEach(function(elem,idx){
elem.style["color"]="grey";
});
function getLabelByForAttribute(a)
{
var matchingElements = [];
//get all labels in the document
var allElements = document.getElementsByTagName('label');
for (var i = 0, n = allElements.length; i < n; i++)
{
//if those labels have the required 'for' attribute
if (allElements[i].getAttribute("for") ==a)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
<input type="checkbox" name="comment" id="abc1" value="the value." onclick="createOrder()">
<label for="abc1" onclick="createOrder()" title="title">onscreen text for this checkbox</label>

Related

How do I use window.find to change css style?

Through a combination of AJAX and PHP, I put some text data in a span at the bottom of the page. Now I want to search this text for a string. My page is full of checkboxes, and their values are the strings I will search for.
Goal: Using a loop, cycle through the values of all checkboxes on the page. Search the page for each checkbox's value (ideally, within the text in the AJAX-informed span). If the checkboxes value is found, change that checkboxes CSS style color.
My code so far: I have a form full of checkboxes all named "comment" each with unique IDs:
<input type="checkbox" name="comment" id="hjl1" value="the comment."
onclick="createOrder()"><label for="hjl1" onclick="createOrder()"
title="comment"> onscreen text for this checkbox </label>
When triggered , using Javascript, I go through every checkbox in that form.
var comment=document.forms[0].comment;
var txt="";
var ii;
for (ii=0;ii<comment.length;ii++)
{str=comment[ii].value;}
Now I want to insert window.find in that loop to check if that value is on my page.
if (window.find) {
var found = window.find (str);
if (!found) {
document.getElementById("?????").style["color"] = "red";
}
}
The idea is that when the checkbox is checked, the javascript would search for the value "the comment." on page. If found, the checkbox label will add the CSS style color red.
Somehow, I want to combine these ideas, but there are so many problems. How do I get the element by ID in this loop? Can window.find search the text created by php in my span?
Would it be better to not use window.find at all?
var source = document.getElementsByTagName('html')[0].innerHTML;
var found = source.search("searchString");
I'm so confused and new. Please be patient. Thank you for reading this far.
I misunderstood at first, and wrote code to highlight text within the page.
Yes, window.find is fine to use for this as you only need to know if the value exists or not. It might behave a bit odd (scroll to bottom) when used in frames though.
Also, I added a function for your onClick, but I'm not sure if this is wanted. It will change color of the label if text if found when clicked (also).
Below is a small example:
function checkThis(ele) {
var str = ele.value;
if (window.find) {
var found = window.find(str);
if (found) {
var id = ele.getAttribute('id');
var lbl = document.querySelectorAll('label[for="' + id + '"]');
if (lbl) lbl[0].style.color = "red";
}
}
}
window.onload = function() {
var comment = document.form1.getElementsByTagName('input');
for (var x = 0; x < comment.length; x++) {
if (comment[x].type == 'checkbox') {
var str = comment[x].value;
if (window.find) {
var found = window.find(str);
if (found) {
var id = comment[x].getAttribute('id');
var lbl = document.querySelectorAll('label[for="' + id + '"]');
if (lbl) lbl[0].style.color = "red";
}
}
}
}
}
<form name="form1">
<input type="checkbox" name="comment" id="hjl1" value="the comment." onclick="checkThis(this);" />
<label for="hjl1" onclick="createOrder()" title="comment">onscreen text for this checkbox</label>
<input type="checkbox" name="comment" id="hjl2" value="the comment2." onclick="checkThis(this);" />
<label for="hjl2" onclick="createOrder()" title="comment">onscreen text for this checkbox</label>
<br/>
<b>first comment.</b><br/>
<b>other comment.</b><br/>
<b>some comment.</b><br/>
<b>the comment.</b><br/>
<b>whatever comment.</b><br/>
<b>not this comment.</b><br/>
</form>
try this as your function code
function loopy() {
var comment=document.forms[0].comment;
var txt="";
var ii;
for (ii=0;ii<comment.length;ii++) {
if (comment[ii].checked) {
str=comment[ii].value;
id = comment[ii].id;
nextLabelId = comment[ii].nextSibling.id;
if (window.find) { // Firefox, Google Chrome, Safari
var found = window.find (str);
if (found == true) {
// found string
//comment[ii].style['outline']='1px solid red';
document.getElementById(nextLabelId).className = 'selected';
}
} else {
// this browser does not support find()
alert('not supported');
}
}
}
}
So, in order to get the checkbox id, you just add id = comment[ii].id in your loop.
To change the color, it's best to use class name and use styling in the css file. so if you want to change the label that is after the checkbox to red you will first find the label's id using nextSiblings and then add the .selected class name. Just remember that you need to remove the coloring if the user un-check the box
Regarding the usage of find(), not supported by all browser so this could be an issue and also not sure it will be able to find on the content you injected to the DOM by AJAX so this needs some testing.
I would suggest moving this code to jQuery as some features seems to be easier using their functionality.

Hide textbox based on its value

I've got a canvas on which I can add text and image layers, below the canvas I have a couple of textboxes in which I display information about the selected layer. The things I display are:
X coördinate
Y coördinate
Width
Height
Font
Font Size
Font Color
Titel
Angle
Now since an image layer does not have a Font, Font Size and Font Color it will display 'undefined' now.
I am using this javascript code to display the info in the textboxes:
document.getElementById('width').value = Math.round(layer.width*100)/100;
document.getElementById('height').value = Math.round(layer.height*100)/100;
document.getElementById('x').value = layer.offsetX;
document.getElementById('y').value = layer.offsetY;
document.getElementById('color').value = layer.fontColor;
document.getElementById('color').style.color=layer.fontColor;
document.getElementById('font').value = layer.fontFamily;
document.getElementById('size').value = layer.fontSize;
document.getElementById('title').value = layer.title;
document.getElementById('angle').value = Math.round(layer.angle*100)/100;
The question:
Is there any way to hide the textboxes disappear when they contain the word 'undefined'?
Also will it be possible to hide the plain text in front of the boxes? (Font:, Size:, Color)
A working version of the canvas can be found in this codepen!
You can create a helper function that hides or shows the element depending on the value === undefined or not:
function setElementValueById(id, value){
var element = document.getElementById(id);
if(element != null){
element.style.display = value !== undefined ? '': 'none';
element.value = value;
}
}
// usage
setElementValueById('font', layer.fontFamily);
Edit:
To hide the label also, you can group each box and its label inside a single element (div):
(based on your codepen example)
<td>
X:
<input id="x" type="number" onkeypress="return isNumber(event)" size="5">
Y:
<input id="y" type="number" onkeypress="return isNumber(event)" size="5">
becomes:
<td>
<div>X:
<input id="x" type="number" onkeypress="return isNumber(event)" size="5">
</div>
<div>Y:
<input id="y" type="number" onkeypress="return isNumber(event)" size="5">
</div>
Then modify the function to show/hide the parent div:
// Searches for the element with the given id and sets its value.
// If the value is strictly equal to 'undefined',
// the element's parent will be hidden.
function setElementValueById(id, value){
var element = document.getElementById(id);
if(element != null){
element.parentElement.style.display = value !== undefined ? '': 'none';
element.value = value;
}
}
// usage
setElementValueById('font', layer.fontFamily);
Here is simple solution:
var value = // get the value from layer
if(typeof value === 'undefined') {
// hide the box
}
Since it looks like you are not using jQuery, it will be harder for you to hide the input:
document.getElementById(id).style.display = 'none';
And show:
document.getElementById(id).style.display = 'block';
With jQuery, you can do this:
$(id).show();
Respectively:
$(id).hide();

how to find the next td element type using jquery

<tr>
<td class="value" style="width:40%;">
<label class="label">Gender value</label>
</td>
<td class="value" style="width:40%;">
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>M</label>
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>F</label>
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>U</label>
</td>
</tr>
I have the above HTML, I am reading all the controls from my webpage dynamically. In above I want to read the label value to its specified type and read the next value on the basis of its type:
Please look on my code:
// Read labels text
$("#tblCustomFields tr .label").each(function () {
var value = this.innerHTML;
console.log(this);
var type = $(this).closest('td').next().find('input').val();
alert(value);
alert(type);
//If next element type is *checkbox* then read checkbox values
if(type == "checkbox")
{
// Read checkbox values
$('tblCustomFields tr input:checked').each(function (s) {
var inputCheckBox = new Array();
inputCheckBox.push([this.id, 0]);
});
for (var i = 0; i < inputCheckBox.length; i++) {
alert(inputCheckBox[i]);
}
}
});
The above code will give me all the checkboxes on the webpage but I want the checkboxes only defined in the above HTML, and I also want to read the values of only those checkboxes which are checked. Please help.
GOAL: I am binding the dynamic HTML to the page its type might be checkbox or dropdown or text. Now I want to read the page labels and the values related to that labels. For ex my label(Gender value) has values of type checkbox so I just want to read the checked checkbox values related to that label.
UPDATE: At least tell me that how can I get the next element type
I am using the below code:
var type = $(this).closest('td').next().find('type').val();
ANY HELP
I think that all the markup has to be reviewed, but anyway, I think I know (please notice me if don't) what you want.
Try this:
// Read labels text
$("#tblCustomFields tr .label").each(function () {
var value = this.innerHTML;
console.log(this);
alert(value);
var inputCheckBox = new Array();
$(this).first().closest("td").next().find("input[type='checkbox']:checked").each(function(){
inputCheckBox.push($(this).next("label").text());
});
for (var i = 0; i < inputCheckBox.length; i++) {
alert(inputCheckBox[i]);
}
});
I'll make you a jsFiddle to test it.
Your question is confusing.
$("#tblCustomFields tr .label") - This will look for a child of TR with class label. Your HTML, shows that this resides inside td. If all the label elements have class label, you can refer each by -
$(".label).each(function(){
//do whatever you want
});
To get the element type next to the label with class label -
$(".label).each(function(){
var NextTd = $(this).parent().next(); // refers to the next td
$(NextTd).each(function(){
var type = $(this).find('input').prop('tagName');
//do whatever you want
});
});

How to change the style of a radio button with javascript when clicked

I have an order form that has three sets of radio button options. Ultimately, I would like to have the text of the radio button in each group change to bold and red when it is clicked. However, I'm not having any luck just changing the color of even one group. Below is the loop I was using to try to change one group of radio buttons. My logic was to go through the group of radio buttons and if one of them were clicked it would change the style of the text. What am I doing wrong with this function?
function highlight() {
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
return document.getElementByName.style.color = 'red';
}
}
}
This is one group of radio buttons in my code. The other two groups are similar:
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/> Desktop Case ($500.00) </br>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/> Mini-Tower Case ($600.00) </br>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> Full-Tower Case ($700.00) </br>
Any help would be greatly appreciated.
If you amend your code, and wrap the text in a label element and, incidentally, you can't change the color or font-weight properties of text unless it's wrapped in an element, and that would have to be a separate element for each string of text you want to affect :
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/><label for="case1">Desktop Case ($500.00)</label>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/><label for="case2">Mini-Tower Case ($600.00)</label>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> <label for="case3">Full-Tower Case ($700.00)</label>
You can achieve this with just CSS:
input[type=radio]:checked + label {
color: red;
font-weight: bold;
}
JS Fiddle demo.
Incidentally, to use plain JavaScript I'd suggest:
function choiceHighlight(radio){
var groupName = radio.name,
group = document.getElementsByName(groupName);
for (var i = 0, len = group.length; i < len; i++){
group[i].nextSibling.className = group[i].checked ? 'chosen' : 'unchosen';
}
}
var radios = document.getElementsByName('cases');
for (var i = 0, len = radios.length; i < len; i++){
radios[i].addEventListener('change', function(){
choiceHighlight(this);
});
}
JS Fiddle demo.
Your return statement looks off:
return document.getElementByName.style.color = 'red';
Also note that you've attempted to give the radio inputs a color of red, but they cannot be styled in this way. The text that you have next to the inputs is not part of the input itself.
Here's a simplified script that gets you the input values onchange (not onselect). You should be able to use this as a better starting point: http://jsfiddle.net/rWp6E/
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
radios[i].onchange = function () {
alert(this.value);
}
}
getElementByName isn't valid Javascript. A better way to do this would be to use the onCheckedChanged event to change your style:
<input id="case1" type="radio" name="cases" oncheckedchanged="highlight(this)" value="500.00"/>
<script type="text/javascript">
function highlight(e) {
if(e.checked == true)
{e.style.color = "red"}
else
{e.style.color = "some other color"}
}
Note that you will actually have to change the style of the label if you want to change the color of the text.
There is also a :checked selector in CSS3 (as someone else mentioned above), however it will not work in some older browsers, namely IE8 and earlier.

How to get the innerHTML of an input control including the values?

I have a div, its called tab1. Inside the tab1 div are many inputs (fields and radio buttons). I am getting the innerHTML like this:
document.getElementById("tab1").innerHTML;
Example code:
<div id="tab1">
<input type="text" id="text1" />
</div>
That works, but if I entered any value into a text1 input for example, its not in the innerHTML. How would I get the innerHTML including the entered values? Is that possible at all?
Thanks!
<div id="tab1">
<input type="text" id="text1"
onkeyup="javascript:this.setAttribute("value", this.value);"/>
</div>
This will gives the values with div's innerHTML.
document.getElementById("tab1").innerHTML;
You can change the event accordingly, I set it onKeyUp.
If you want to get the values of inputs/radios, you can do it with jQuery:
var Inputs = $("div#tab1 input, div#tab1 radio");
You now have an array of all input and radios in the variable Inputs. You can then access the values like this: Inputs[0].value
If you want to use plain JavaScript that could look like this:
var Inputs = document.getElementById("tab1").getElementsByTagName('input');
You can now access them like:Inputs[0].valueandRadios[0].value`
#edit
Thanks, I corrected these mistakes.
If you type something in the textbox, what does the innerHTML look like? Does it look like
<input type="text" id="text1" value="your_value" />?
If so, here is a simple function that returns what you want:
function getInnerHtml() {
var div = document.getElementById("tab1");
var childNodes = div.childNodes;
var innerHtml = "";
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (node.nodeType == 1) {
if (node.getAttribute("type") == "text") {
if (node.value != "") {
//! This will change the original outerHTML of the textbox
//If you don't want to change it, you can get outerHTML first, and replace it with "value='your_value'"
node.setAttribute("value", node.value);
}
innerHtml += node.outerHTML;
} else if (node.getAttribute("type") == "radio") {
innerHtml += node.outerHTML;
}
}
}
}
Hope it's helpful.

Categories

Resources