Hide textbox based on its value - javascript

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();

Related

Changing two input values to one

I am trying to change the two input boxes from feet/inches to one input box to centimeters when centimeters is selected as an option. It works with feet and inches but I want only one input when user selects centimeters. How would I able to change it using javascript?
<form action=" " onsubmit="">Enter your Height:
<input type="text" id="height"> </input>
Feet <input type="text" id="height2"> </input>Inches
<select id = "typeH">
<option value = "feet">Feet/Inches</option>
<option value = "cm">Centimeter</option>
</select>
Here is one of the function in my js code:
function calculateBMI() {
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
var height2 = document.getElementById('height2').value;
var typeW = document.getElementById("type").value;
var typeH = document.getElementById("typeH").value;
if (typeW === "lbs") {
weight = weight * 0.45;
} else if (typeW === "kg") {
weight = weight;
}
if (typeH === "feet") {
height = height * 0.3048;
height2 = height2 * 0.0254;
var totalheight = height + height2;
} else if (typeH === "cm") { //this is the part where i want to change the two input boxes to one if the user selects cm as type of height
typeH.addEventListner("click", change());
//change();
height = height * 0.0328084;
height2 = 0;
var totalheight = height + height2;
}
var total = weight / (totalheight * totalheight);
roundToTwo(total);
document.getElementById('result').value = roundToTwo(total);
}
You'll need some javascript. Here is a quick and dirty solution, also using CSS:
document.getElementById('typeH').addEventListener('change', function(e) {
var el = e.target;
// Mark all of them as hidden
for(var i = 0; i < el.options.length; i++) {
var spanEl = document.getElementById(el.options[i].value);
spanEl.className = 'hidden';
// Reset all of the input options
var inputs = spanEl.querySelectorAll('input');
for(var j = 0; j < inputs.length; j++) {
inputs[j].value = '';
}
}
// Show the one that was selected
document.getElementById(el.options[el.selectedIndex].value).className = '';
});
.hidden {
display: none;
}
<form action="" onsubmit="">
<span>Enter your Height:</span>
<span id="feet"><!-- This id must match the value in the select option -->
<input type="text" id="heightInFeet" name="heightInFeet"></input> Feet
<input type="text" id="heightInInches" name="heightInInches"></input> Inches
</span>
<span id="cm" class="hidden">
<input type="text" id="heightInCentimeters"></input> Centimeters
</span>
<select id="typeH">
<option value="feet">Feet/Inches</option><!-- This value must match the id of the span -->
<option value="cm">Centimeters</option>
</select>
</form>
In the Javascript, we add an event listener to the change event of the #typeH select element. (This is the equivalent of putting a function in the onChange attribute inline in the HTML.)
In the CSS, we just add a class that hides the irrelevant elements.
In the HTML, we reorganize the DOM tree so the sections of inputs and text (namely for feet/inches and centimeters) into wrapper span elements. That way in javascript, we can hide all of the inputs in the spans, and then "show" (or rather, remove the hidden class) on the selected option.
Hopefully this is educational for you.
Apart from the code you are using to calculate the weight and height values, you need to use another code to handle the hiding/showing case.
You need to bind an onchange event on the select element where, you will hide/show the second input according to the selected value.
In your JS create the following function:
function filterHeight(select) {
if (select.value !== "feet") {
document.getElementById("height2").style.display = "none";
} else {
document.getElementById("height2").style.display = "block";
}
}
Where document.getElementById("height2") is used to refer the second input and .style.display is used to hide/show it.
Then in your HTML add onchange="filterHeight(this)" to the select element:
<select id="typeH" onchange="filterHeight(this)">
Where this refers to the select element itself, so you can access its value inside the callback function.
Demo:
This is a working demo snippet:
function filterHeight(select) {
if (select.value !== "feet") {
document.getElementById("height2").style.display = "none";
} else {
document.getElementById("height2").style.display = "block";
}
}
<form action=" " onsubmit="">Enter your Height:
<input type="text" id="height"> </input>
Feet <input type="text" id="height2"> </input>Inches
<select id="typeH" onchange="filterHeight(this)">
<option value="feet">Feet/àInches</option>
<option value="cm">Centimeter</option>
</select>

How can I change the label for css style?

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>

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

Trouble with clearing other text boxes when value is backspaced

I am a beginner at Javascript, this is my first Javascript that isn't just 'cut/paste/hack'. I created an calculator that updates the output as input is typed, I can get all my 'answerboxes' to clear when the input box is blurred then focused, but if I backspace the value out of the input box the 'answerboxes' still show the 'answers' based on the last char. value that was backspaced.
In my 'validiateTheInput' funct. I can declare an 'if = "3"' to clear them and it works when a '3' is the value (which would not work in the end :) ), but I can't seem to catch it if the field appears blank do to user backspacing the value from the box.
Am I obsessing over something stupid, or am I just missing something?
Heres the whole thing (with some basic HTML ommitted):
There is also a bit of overkill in the validation function because I was experimenting with trying to catch the 'blank input' do to backspacing.
//jQuery keyup to grab input
$(document).ready(function() {
$('#totalFeet').keyup(function() {
validiateTheInput();
});
});
//clear calculated values
function clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField) {
answerbox.value = "";
answerbox1.value = "";
answerbox2.value = "";
totalFeetField.value = "";
};
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = document.getElementById('totalFeet');
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
// feel like I should be able to catch it here with the length prop.
if (totalFeetField.value.length == 0) {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// if input is usable, do the good stuff...
if (totalFeetField.value != "" && !isNaN(totalFeetField.value)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField.value)) {
alert("The Total Sq. Footage Value must be a number!")
document.getElementById('totalFeet').value = "";
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField.value == '3') {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField.value == 'undefined' || totalFeetField.value === null || totalFeetField.value === '') clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 5.95; // set multiplier
document.getElementById('answerbox').value = answer.toFixed(2);
}
// calc the second box
function calcSecondBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 18.95; // set multiplier
document.getElementById('answerbox1').value = answer.toFixed(2);
}
// calc the third box
function calcThirdBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 25.95; // set multiplier
document.getElementById('answerbox2').value = answer.toFixed(2);
}
HTML:
<div id="calculator">
<form name="calculate">
<label for="total">Total Value to Calculate:</label> &nbsp&nbsp&nbsp&nbsp
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes(totalFeet, answerbox, answerbox1, answerbox2);"><br /><br />
<label for="answerbox">Total Value X $5.95:&nbsp&nbsp&nbsp&nbsp$</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"><br /><br />
<label for="answerbox1">Total Value X $18.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"><br /><br />
<label for="answerbox2">Total Value X $25.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15">
</form>
</div>
The problem is that you're not storing the element objects in variables - you're storing their values:
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
...so later, when you call the following function, passing these variables as an argument:
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
...you're not passing the elements. You can fix it by removing .value off each line in your variable assignments.
Working demo: http://jsfiddle.net/AndyE/Mq6uN/
Side note and shameless plug: if you want something a little more robust than keyup for detecting input, check out this blog post.
You are passing the value of answerbox, answerbox1 etc to the clearBoxes function, not the elements themselves.
Here's a full jQuery approach:
//jQuery keyup to grab input
$(document).ready(function () {
$('input[id$=totalFeet]').keyup(function () {
validiateTheInput();
});
function clearBoxes() {
$('input[id$=answerbox]').val("");
$('input[id$=answerbox1]').val("");
$('input[id$=answerbox2]').val("");
}
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answerbox = $('input[id$=answerbox]').val();
var answerbox1 = $('input[id$=answerbox1]').val();
var answerbox2 = $('input[id$=answerbox2]').val();
// feel like I should be able to catch it here with the length prop.
if (totalFeetField == "") {
clearBoxes();
}
// if input is usable, do the good stuff...
if (totalFeetField != "" && !isNaN(totalFeetField)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField)) {
alert("The Total Sq. Footage Value must be a number!")
$('input[id$=totalFeet]').val("");
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField == '3') {
clearBoxes();
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField == 'undefined' || totalFeetField === null || totalFeetField === '')
clearBoxes();
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 5.95; // set multiplier
$('input[id$=answerbox]').val(answer.toFixed(2));
}
// calc the second box
function calcSecondBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 18.95; // set multiplier
$('input[id$=answerbox1]').val(answer.toFixed(2));
}
// calc the third box
function calcThirdBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 25.95; // set multiplier
$('input[id$=answerbox2]').val(answer.toFixed(2));
}
});
Also, here's the HTML
<form name="calculate" action="">
<label for="total">Total Value to Calculate:</label> &nbsp&nbsp&nbsp&nbsp
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes();"/><br /><br />
<label for="answerbox">Total Value X $5.95:&nbsp&nbsp&nbsp&nbsp$</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"/><br /><br />
<label for="answerbox1">Total Value X $18.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"/><br /><br />
<label for="answerbox2">Total Value X $25.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15"/>
</form>
Sometimes mixing jQuery and plain javascript doesn't work too well. This code should work in clearing your textboxes when the first textbox is empty. It also works on number validation.

Toggle the display of a text field with a checkbox

When Unlimited is checked, remove the input box. That works. However, when the checkbox is unchecked the input box wont show back up.
<script type="text/javascript">
function getQuantity() {
var checkbox = document.getElementById("unlimited");
var qty = document.getElementById("quantityspace");
if(checkbox.checked == true){
qty.style.display = 'none';
}else if(checkbox.checked == false) {
qty.stlye.display = '<input type="text" id="quantity" size="4" value="1" name="quantity" />';
}
}
</script>
<input type="checkbox" id="unlimited" name="unlimited" value="x" onClick="getQuantity(); " /> Unlimited? <span id="quantityspace">or specify:
<input type="text" id="quantity" size="4" value="1" name="quantity" /></span>
qty.stlye.display = '<input type="text" id="quantity"
size="4" value="1" name="quantity" />';
should be:
qty.style.display = 'inline'; // or block
display is a property of the already existing input tag. You don't need to assign the entire tag to the property to make it show up again -- in fact that's dead wrong. Simply assign that property a new valid value for display, like inline, inline-block or block and it will show up again.
In your else if(...) you have:
qty.stlye.display
Do you mean style?
Additionally, you're incorrectly defining the display attribute. It should be a valid value. You probably want it to be:
else if(!checkbox.checked) {
qty.style.display = 'inline'; // or something from the W3C link above
}
Is it just that you've misspelled 'qty.stlye.display'?
Change the qty.stlye.display line to:
qty.style.display = "";
Note that you misspelled "style" there.
You misspelled "style" as "stlye" and you're setting the display style to HTML for some reason. It should be 'inline' or 'block' or whatever it was before you set it to 'none'.
I think what you want is this:
function getQuantity() {
var checkbox = document.getElementById("unlimited");
var qty = document.getElementById("quantityspace");
if(checkbox.checked == true){
qty.innerHTML = '';
}else if(checkbox.checked == false) {
qty.innerHTML = '<input type="text" id="quantity" size="4" value="1" name="quantity" />';
}
}
If I'm correct, you want to put an input in the quantityspace element when the checkbox is not checked.
qty.style.display changes the CSS display property of the span. qty.innerHTML changes the HTML inside the span.
You could do it with .style.display with the following code:
function getQuantity() {
var checkbox = document.getElementById("unlimited");
var qty = document.getElementById("quantityspace");
if(checkbox.checked == true){
qty.style.display= 'none';
}else if(checkbox.checked == false) {
qty.style.display= 'inline';
}
}

Categories

Resources