I have taken a 70-480 Microsoft exam this morning(HTML5,CSS3 and Javascript), and I found one question to be confusing/wrong/incomplete. The question is this:
you have a checkbox input and a text input on the webpage.
<input type="checkbox" id="chkBox" />
<input type="email" id="txtEmail" disabled/>
The requirement is that, when a user checks the checkbox:
the email input should be enabled
when the user unchecks the checkbox
the email input should be disabled
the email input should have gray background
You have the following script and style defined:
<style>
(selector) {
background-color:gray;
}
</style>
<script>
var chkbox = document.getElementById("chkBox");
if(chkbox.Checked)
{
document.getElementById("txtEmail").(selector) = (selector);
}
else
{
document.getElementById("txtEmail").(selector) = (selector);
}
</script>
You can pick from the options given below to replace the (selector) in the above code. you can use the same option any number of times.
1)enabled
2)disabled
3)true
4)false
5)set
I know that for enabling and disabling I need to use option 2,3 and 4 as shown below. And for the other (selector) which is in CSS, I had no clue what option made sense there. It did not make any sense to me, do you guys think the question is wrong or incomplete?
if(chkbox.Checked)
{
document.getElementById("txtEmail").disabled = false;
}
else
{
document.getElementById("txtEmail").disabled = true;
}
There is an :disabled selector, but it should have specified a colon in front of it, in my opinion
http://www.w3schools.com/cssref/sel_enabled.asp
Please visit below link to select disabled input
https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
input[type="email"]:disabled {
background: #d3d3d3;
}
Related
JS Fiddle: https://jsfiddle.net/bcon865y/5/
Sorry if this is a little vague..
Trying to create a javascript form which validates each field using a onblur function once a field gets tested as correct the background of the field will turn green.
The submit button has a function which if all fields are green it will submit the form, however all fields are green but the form is not passing validation. I have no idea why this is happening any insight would be greatly appreciated, Hope i explained it well enough.
Below is the function in question, view the js fiddle to get the full context.
function validate() {
// Gets all the elements in the form with id="form1"
var elements = document.getElementById("form1").elements;
// loops through all elements in the form
for (var i = 0, element; element = elements[i++];) {
// Checks if the element in the form is either <input> or <select> && not green
if ((element =='[object HTMLInputElement]' || element == '[object HTMLSelectElement]') && (element.style.backgroundColor !='rgb(204,255,204)')) {
if (element.type!='color' && element.type!='submit') {
alert("Please enter data for any fields that are not green");
return false;
}
}
}
// to test the color picker
if (document.getElementById("color").value !='#000000') {
alert("please select a colour from the colour picker");
document.getElementById("The ID for your color picker goes here").focus();
return false;
}
}
It seems you're looking for a combination of the pattern field (on the input element) and the :valid & :invalid pseudo css selectors.
input[type="text"]:valid {
background: #BCED91;
}
input[type="text"]:invalid {
background: #F08080;
}
<form>
<input type="text"
id="name"
name="name"
required
pattern="[01]+">
<input type="submit">
</form>
The example above colors any text fields red if their values doesn't match the regex [01]+, and green if they do match it.
You can read more about form validation here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
I have a form with inputs which also has an iFrame embedded in the form which also has inputs (pseudo HTML):
<input type="text" name="one" value="one" />
<input type="text" name="two" value="two" />
<input type="text" name="three" value="three" />
<iframe
<input type="text" name="bacon" value="bacon">
</iframe>
<input type="text" name="four" value="four" />
<input type="text" name="five" value="five" />
When the user presses tab they are taken from input to input even inside the iframe fields selecting bacon after three. We all love bacon.
I also have some javascript that attempts to focus the next input on enter key:
$(document).ready(function() {
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
var inputs = $(':tabbable');
var next = inputs.index(this) + 1;
var input = inputs.eq(next == inputs.length ? 0 : next);
input.focus();
return false;
}
});
});
The problem is the javascript enter key code never focuses the bacon field, it will skip right over it. jsfiddle:
https://jsfiddle.net/54n8mqkh/4/
Let's all skip answers that include not using the iFrame. I know it is not an ideal implementation. However, I would accept ANY answer that allows the enter key to move through all the fields consistently including the iframe using any type of javascript. It does not have to be jquery specific.
I have tried a few different approaches to solve this but none I have found works. Thanks in advance to anyone who has a solution.
You need to focus inside of the iframe like so :
var frameBody = $("#IFrame_input").contents().find("input");
frameBody.focus();
I am going to answer my own question - after a few more hours I was able to solve my use case by expanding my selector to include the iframe. Then I build the array of inputs manually and while iterating I checked the node type for an iframe. If / when I encountered an iframe, I did the same select inside the iframe and added the inputs within the iframe:
$(document).ready(function() {
// Parent level helper function
window.tabToNext = function(me) {
var selector = ':tabbable, iframe';
var inputElems = [];
$(selector).each(function(index) {
var nodeName = $(this).prop('nodeName').toLowerCase();
if (nodeName == 'iframe') {
$(this).contents().find(selector).each(function(index) {
inputElems.push(this);
});
} else {
inputElems.push(this);
}
});
var inputs = $(inputElems);
var next = inputs.index(me) + 1;
if (next == inputs.length) next = 0;
var input = inputs.eq(next);
input.focus();
return false;
}
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
return window.tabToNext(this);
}
});
// Focus the first input
$('input[name=one]').focus();
});
FWIW: I could not just expand the selector as best I could tell and also I tried to use $.add to build the collection starting with an empty jQuery collection:
var foo = $([]);
foo.add(someElement);
... but it does not honor the order you add. It will re-order to the DOM according to the docs which SEEMS like it should be right, but for some reason my iframe child fields always ended up last and messed up the tab order.
Anyhow, I hope if someone else has this issue some day you find this helpful. Working solution:
https://jsfiddle.net/wbs1zajs/6/
This question already has answers here:
How can I add an unremovable prefix to an HTML input field?
(18 answers)
Closed 6 years ago.
How do I generate an input element that has a default starting value in there that is unchangeable? For example, I am looking for a number from the user but I want '333' to be already in the input text box since all inputs will start with that number. I also don't want the user to be able to change it. I need the 333 to be part of the value also rather than just being added via style since I need to do validation on it.
I'd use 2 inputs as William B suggested but I'd consider whether to use the disabled attribute or the readonly attribute. The disabled attribute won't allow the first input to be focused and the default browser styling will give it a gray background. The readonly attribute will allow it to be focused and may have a more desirable initial styling.
One possibilty using JavaScript:
nine = document.getElementById("nine");
nine.addEventListener("keydown", function (ev) {
var el = this;
var value = el.value;
setTimeout(function () {
if (el.value.indexOf("333") != 0) {
el.value = value;
}
}, 0);
});
<input type="text" value="333" id="nine" />
I'd suggest using 2 inputs that look like a single input, with the first one readonly. See this fiddle: https://jsfiddle.net/39whrqup/2/
<input readonly value="333" class="static-input">
<input class="nonstatic-input">
.static-input {
margin-right: -20px;
width: 50px;
border: 0;
}
.nonstatic-input {
border: 0;
}
When reading the user input you will have to prepend the static portion, naturally:
var userInput = document.querySelector('input.static-input').value +
document.querySelector('input.nonstatic-input').value;
What I'm going after is a code that will gather all my text input fields and detect whether or not they have any input. If so I'd like for there to be a glow effect added, if they're left empty or they delete the data and leave it empty I'd like for the glow effect to turn off.
So far from everything I've found this is what I came up with so far, it doesn't work of course, but it's the best I could try to rationalize.
function glow(){
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
if (text.value ==null){
text.style.boxShadow="#8fd7d2 0px 0px 22px";
}
else
remove.style.boxShadow;
}/**function**/
I used the .getElementsByClassName because the getElementsById didn't support multiple IDs as it seems, but if there's another more efficient way of gathering them all please share.
Simple solution can be adding class having glow with javascript:
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
text[0].className = text[0].className + " glow";
DEMO
Note: If you want to add glow class to each input then you have to iterate through loop and add class to each element. Because text is
HTMLCollection of elements.
You need to get the value of each element, not of the HTMLCollection returned by document.getElementsByClassName; Array.prototype.forEach can help with this. Then, a value can’t be null, but empty.
Edit: Wait a minute… you want the glow effect if the element has an input, right? Then your if-else statement is the wrong way around.
This is the correct function:
function glow() {
"use strict";
Array.prototype.slice.call(document.getElementsByClassName("tex_inp01 tex_inp02")).forEach(function(a) {
if (a.value !== "") {
a.style.boxShadow = "0px 0px 22px #8fd7d2";
}
else {
a.style.boxShadow = "";
}
});
}
You have a couple of mistakes in your existing code (as presented in the question): (1) text.value ==null - do not check against null, because an inputs value will never be a null. Check its length. (2) remove.style.boxShadow; - I think that was a typo. It should have been text.style.boxShadow = 'none'.
..to be a glow effect added, if they're left empty or they delete the
data and leave it empty I'd like for the glow effect to turn off..
You can check if the input has been left empty by simply checking the length of the value. However, to check if the input has been entered and then deleted you will have to keep a flag to keep track of that. You can do that by hooking up the change event on inputs and then setting a flag via data attribute. Later when you are checking each input for applying a style, along with the length also check this attribute to see if the input was edited out.
Here is a simple example putting together all of the above (explanation in code comments):
var inputs = document.getElementsByClassName("a b"), // returns a collection of nodelist
button = document.getElementById("btn"); // just for the demo
button.addEventListener("click", checkInputs); // handle click event on button
[].forEach.call(inputs, function(elem) { // iterate over all selected inputs
elem.addEventListener("change", function() { // handle change event
this.setAttribute("data-dirty", true); // set a data attribute to track..
}); // .. a flag when it is changed
});
function checkInputs() {
[].forEach.call(inputs, function(elem) { // iterate over selected inputs
var isDirty = elem.getAttribute("data-dirty"); // check the dirty flag we set
if ((elem.value.length > 0) || (isDirty)) { // if empty or changed
elem.style.boxShadow = "none"; // reset the style
} else {
elem.style.boxShadow = "#f00 0px 0px 5px"; // else apply shadow
}
});
}
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<button id="btn">Check</button>
If you wanted to validate the inputs while the user is typing, you can use keyboard events to check the value of the input(s):
document.querySelector('input[type="text"]').addEventListener('keyup',
function(event){
var element = event.target;
if (element.value.trim() === '') {
element.classList.add('empty');
} else {
element.classList.remove('empty');
}
});
See fiddle for example: http://jsfiddle.net/LrpddL0q/.
Otherwise this could be implemented the same way without the addEventListener to perform as a one-off function.
Jquery can help you as the following
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$(".MyInput").bind('keypress', function () {
$('.MyInput').css("boxShadow", "#8fd7d2 0px 0px 22px");
});
$(".MyInput").bind('keydown', function () {
if ($(".MyInput").val() == "") {
$('.MyInput').css("boxShadow", "none");
}
});
});
</script>
HTML:
<input type="text" value="" class="MyInput" />
this code working only online If you need to download Jquery library visit this
https://jquery.com/download/
The application creates a temp HTML Page for Print Version.
I can disable everything on the page so that user can not interact with the page..but that makes evrything grey in color and user is having problem with reading. SO i want to make everything to be readonly..
Here is my piece of code,
var x = 0;
var element;
while (x < document.getElementsByTagName("input").length) {
element = document.getElementsByTagName("input")[x].type
if (element = "BUTTON") {
document.getElementsByTagName("input")[x].onclick = null;
}
if (element = "TEXT") {
document.getElementsByTagName("input")[x].readOnly = true;
}
if (element = "CHECKBOX") {
document.getElementsByTagName("input")[x].disabled = true;
}
x++;
}
if i remove the if block for checkbox it is working fine. but if i include the checkbox condition it is making everything disabled(even buttons and text)..when i debug i see all the if blocks are executing.. i do not understand why.
Can some one plz help me out in this regard?
When checking for equality, use === right now you're using the assignment operator, =, which means every check will return true.
to compare use == instead of =
if (element == "BUTTON") { }
Use == instead of = inside if condition.
If you simple want to disable everything on the page - a faster way to do it is place transparent DIV over page content with z-index of a higher value.
Something like this:
Hello: <input type="text"/> <br>
Check this: <input type="checkbox" />
<div style="position: absolute; z-index: 10; top:0; left;0; width:100%; height:100%" />
Demo: http://jsfiddle.net/j39Au/
I think the differential styling for disabled inputs is useful because it provides a visual feedback for the user.
This doesn't address your question directly but it may be a good alternative. You could apply styling to the disabled inputs to suit your preference, maybe something like this.
input[disabled=disabled] {
background: rgba(255,0,0,0.05);
border: dashed 1px rgba(255,0,0,0.1);
color: black;
cursor: not-allowed;
}
Finally I made a workaround to this issue.
I converted all my elements(hyperlinks, dropdowns, text) to labels and displayed them in black color.