Change color using querySelector - javascript

I'm following a Javascript tutorial using a book.
The exercise is change the background color in a <input type="search"> using document.querySelector. When I try to search something with no text in the search box, the background from <input> changes to red. I did it using onsubmit and some conditional. But in the next part, it must returns to white bckground using onfocus and I'm not getting.
The code that I tried is
document.querySelector('#form-busca').onsubmit = function() {
if (document.querySelector('#q').value == '') {
document.querySelector('#q').style.background = 'red';
return false;
}
}
document.querySelector('#form-busca').onfocus = function() {
document.querySelector('#q').style.background = 'white';
}
Can someone help me? Thanks a lot!

almost got it dude.
change:
document.querySelector('#form-busca').onfocus
to:
document.querySelector('#q').onfocus
revised code:
correct sample:
document.querySelector('#form-busca').onsubmit = function() {
if (document.querySelector('#q').value == '') {
document.querySelector('#q').style.background = 'red';
return false;
}
}
document.querySelector('#q').onfocus = function() {
document.querySelector('#q').style.background = 'white';
}

It sounds like you want the input's background color to change to white when the input element is focused.
Try changing your onfocus selector to:
document.querySelector('#q').onfocus ...

You want the onfocus handler to be on the #q element, not on #form-busca; the form's focus doesn't matter, you want to clear the background when the input element gains focus:
document.querySelector('#q').onfocus = function() { ... }

Try the following code:
// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";
This will make the color of h1 red.

Related

How to auto-focus after changing display from none to block?

I have a list of inputs under a list of divs respectively. I have a button that when clicked it will switch one input from from not display to display. This is something like:
if (switched) {
document.getElementById("div-xxx").style.display = "block";
}
However, is there a way I could make the input inside the displayed div being auto focused after this switch? I tried something like
document.getElementById('input-xxx').autofocus = true;
after the display code, but there is no autofocus at all.
document.getElementById('input-xxx').focus() will change the focus to the selected element.
document.getElementById('input-xxx').setAttribute('autofocus', true) will assign the autofocus attribute to the html element
object.focus(); will help
if (switched) {
document.getElementById('div-xxx').style.display = "block";
document.getElementById('input-xxx').focus();
}
The only thing that worked for me was
if (switched) {
document.getElementById('div-xxx').style.display = "block";
document.getElementById('old-input').setAttribute('autofocus', false);
document.getElementById('input-xxx').setAttribute('autofocus', true);
document.getElementById('input-xxx').focus();
}

How to make a Javascript form validation with coloured textbox (red/green) without using inline css?

So I have made a Javascript form validation where I get an alert message if nothing is written in the form. Instead of an alert message I want a coloured (red/green) textbox. When you don't write anything in it and try to submit it, you get a red box with a message. When you write down what you need to write and submit it, you get a green box.
function validateFormC() {
let x = document.forms["contactForm"]["name_contact"].value;
if (x === "") {
alert("Don't forget to write down your name!");
return false;
}
I already know how to make coloured checkboxes with html. I need to know how to do it with Javascript for a school project. But it's important that I don't use inline css. Any help would be appreciated, thanks.
You can create a class selector in CSS:
.red-input {
border: 1px solid red;
}
then in your JavaScript you can select the element and add that class to it:
// With Vanilla JavaScript
document.getElementById('input_id').classList.add('red-input');
// With jQuery
$('#input_id').addClass('red-input')
You need something along the lines of:
var warnMessage = document.createElement("div");
warnMessage.innerHTML = "Don't forget to write down your name!";
warnMessage.setAttribute('class', 'warnMessage');
document.body.appendChild(warnMessage);
Then create a matching CSS style : warnMessage probably with bgcolor:red;
Same again for your success message, but green.
Try something like this. You can change borderColor to backgroundColor if you prefer.
function validateFormC() {
var x = document.forms["contactForm"]["name_contact"];
if (x.value === "") {
alert("Don't forget to write down your name!");
x.style.borderColor = 'red';
return false;
}
else
x.style.borderColor = 'green';
}

Simple Javascript text box verification error

I'm trying to check whether the length of characters typed into the text box is less than 6, and if it is, I want its background to be red. Unfortunately, I can't seem to figure out where I'm going wrong with this simple problem.
var textBox = getElementsByName('random');
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
}
}
<input type="text" name="random" onfocus="checkLength();">
A few issues in your code:
you need to put <script> code at the end, so that DOM is loaded and ready before you access elements in it.
getElementsByName('random') needs to document.getElementsByName('random'), which will actually return a list so you need to get first element from the list.
Also logically, you need to remove the red background once the text
length in input exceeds 6 and it would be better if you attach function to oninput event.
<input type="text" name="random" oninput="checkLength();">
<script type="text/javascript">
var textBox = document.getElementsByName('random')[0];
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
</script>
When the page first loads, the element with a name of random doesn't exist.
You will need to initialise your textBox global after the page loads.
You can do this by replacing
var textBox = document.getElementsByName("random")[0]
with
var textBox;
window.onload = function() {
textBox = document.getElementsByName("random")[0]
}
Try this
// add an id of "random" to your input
function checkLength() {
const textBox = document.getElementById("random")
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
Working example: http://jsbin.com/caseqekusi/1/edit?html,js,output
Note: If you want the box to be red right away, you'll have to modify it a bit, let me know if you have questions.
I would suggest to use oninput as well, so it updates as you type and marks the field as "valid" as soon as you have reached a certain length.
You could also get rid of var textbox = ... by using document.activeElement. It makes your function reusable for other input fields. And it no longer matters when your code is loaded.
function checkLength() {
// Get current focused element
const textBox = document.activeElement;
if ( !textBox.value || textBox.value.length < 6 ) {
textBox.style.backgroundColor = "red";
}
else {
textBox.style.backgroundColor = "#fff";
}
}
<input type="text" name="random" onfocus="checkLength()" oninput="checkLength()">

Set HTML text input to null with JQuery

Using JQuery event handlers I want to adjust the default value of a HTML text input and set it to empty.
The input
<button id="setColor">Set Color</button>
<input type="text" id="colorText">
The function
$("#setColor").on("click", function ()
{
document.getElementById('#colorText').defaultValue = "";
});
I have also tried
$("#colorText").defaultValue = "";
$("#colorText").val = "";
$("#colorText").value = "";
but every time I click the SetColor button it seems to keep its previously set default value.
document.getElementById('colorText').defaultValue = "#0000ff";
Your question is not cleared to me, But i got a simple mistake in your code, you write extra # in getElementById
try this:
$("#setColor").on("click", function ()
{
document.getElementById('colorText').value = "";
});
Are you trying to reset the textbox color or want to reset the value?
document.getElementById('colorText').value = '';
$("#colorText").val("");
You can try this with jquery.

changing input text to textarea just like in facebook

i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}

Categories

Resources