Search Bar needs double click before cursor appears - javascript

What do I have to change in the code to get the cursor appear in the search bar after one click instead of a double click? Or why the placeholder does not disappear after one click into the field? (The basic idea of the value and placeholder should stay this way).
HTML
<form action="search.php" method="GET">
<input type="text" name="q" id="searchbox" placeholder="" value="Suche..." maxlength="99" autocomplete ="off" onMouseDown="active();" onBlur="inactive();"/>
<button id="searchbutton"> Los!</button>
</form>
Javascript
function active(){
var searchbox = document.getElementById('searchbox');
if(searchbox.value == 'Suche...'){
searchbox.value = ''
searchbox.placeholder = 'Suche...'
}
}
function inactive(){
var searchbox = document.getElementById('searchbox');
if(searchbox.value == ''){
searchbox.value = 'Suche...'
searchbox.placeholder = ''
}
}

You don't need to use all that code to make a placeholder. You just need this:
<form action="search.php" method="GET">
<input type="text" name="q" id="searchbox" placeholder="Suche..." maxlength="99" autocomplete ="off">
<button id="searchbutton"> Los!</button>
</form>
And it will work. If you use the placeholder tag, when you click on it and start typing it the text will dissapear, you don't need JavaScript code for that.
And one more thing... that code is not "jQuery" code, it's just JavaScript code.
To change the placeholder color use CSS:
::-webkit-input-placeholder {
color: black;
}
:-moz-placeholder { /* Firefox 18- */
color: black;
}
::-moz-placeholder { /* Firefox 19+ */
color: black;
}
:-ms-input-placeholder {
color: black;
}

Related

Change the CSS when there is a required element

I'm a student developer and I'd like to make a message appear when I click on the submit button but there's still a select required
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<p class="messagerequire">Test, If there is a require to submit I appear ! </p>
Here it has the style display:none and I thought I would do that if the form doesn't validate because of a requirement, it changes the CSS.
I've been searching since this morning for answers, but I haven't found or understood.
<input type="submit" name="register" value="register">
Thanks you
Simply check if the select input is invalid in your submit handler, then change the display property for that p element (in this case the first element that has the class). Not the most elegant solution but the simplest in your case:
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', function() {
document.getElementsByClassName('messagerequire')[0].style.display = 'block';
})
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<p class="messagerequire">Test, If there is a require to submit I appear !</p>
<input type="submit" id="submit">
A better approach in my view would be to have two classes for showing and hiding the error and dynamically toggling the p elements' class instead of modifying it's styles.
you code should be something like below. becuase you are using input type=submit so before submit it should validate.
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.getElementById('error').style.display='block';
return false;
}
}
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<form name="myForm" action="/page.php" onsubmit="return validateForm()" method="post">
<p class="messagerequire" id='error'>Test, If there is a require to submit I appear ! </p>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
You need to use JavaScript to achieve this.
function submitThis(){
let name = document.getElementById("name").value;
if(name.length === 0){
document.getElementsByClassName("error")[0].innerText = "Cannot leve name empty.";
//Removing(hinding) the error after 5 seconds.
setTimeout(()=>{
document.getElementsByClassName("error")[0].innerText = "";
}, 5000);
}
}
.error {
color: red;
}
<input type="text" palceholder="Name" id="name" required />
<br>
<br>
<p class="error"></p>
<br>
<br>
<button onclick="submitThis()">SUBMIT</button>
Please you try it.
$('#submit').click(function(){
$('.messagerequire').css('display','block');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<body>
<p class="messagerequire">Test, If there is a require to submit I appear !</p>
<input type="submit" id="submit">
</body>

JavaScript: element.setAttribute(attribute,value) , element.attribute=value & element.[attribute]=value not changing attribute value

My task is to remove Placeholder from input box when user clicks on it and make label visible.
If user doesn't fill anything in it again place back the placeholder and make label invisible.
I am able to hide it but can't reassign it.
I have tried element.setAttribute(attribute,value) , element.attribute=value & element.[attribute]=value type but isn't working.
I have kept default visibility of <label> "hidden"
I have created hide() and show() functions for the task both having 2 parameters viz.
id of input box
id of label
Code JavaScript:
var placehlder;
function hide(input_id,lbl){
var e1=document.getElementById(input_id);
placehlder=e1.getAttribute('placeholder');
/*document.write(placehlder);*/
e1.placeholder="";
var e2=document.getElementById(lbl);
e2.style.visibility="visible";
}
function show(input_id,lbl){
var e1=window.document.getElementById(input_id).value;
var e2=document.getElementById(lbl);
/*document.write(placehlder);*/
if (e1.length ==0)
{
e2.style.visibility="hidden";
e1.placeholder=placehlder;
/*e1.setAttribute('placeholder',placehlder);*/
/*e1['placeholder']=placehlder;*/
}
}
Code HTML:
<form>
<label id="first" >First Name</label><br/>
<input id="box" type="text" placeholder="First Name" onclick="hide(id,'first')" onfocusout="show(id,'first')"/>
</form>
Full Code: HTML + CSS + JAVASCRIPT:
var placehlder;
function hide(input_id,lbl){
var e1=document.getElementById(input_id);
placehlder=e1.getAttribute('placeholder');
/*document.write(placehlder);*/
e1.placeholder="";
var e2=document.getElementById(lbl);
e2.style.visibility="visible";
}
function show(input_id,lbl){
var e1=window.document.getElementById(input_id).value;
var e2=document.getElementById(lbl);
/*document.write(placehlder);*/
if (e1.length ==0)
{
e2.style.visibility="hidden";
e1.placeholder=placehlder;
/*e1.setAttribute('placeholder',placehlder);*/
/*e1['placeholder']=placehlder;*/
}
}
#first{
visibility: hidden;
}
#box{
}
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>
Functions
</title>
</head>
<body>
<form>
<label id="first" >First Name</label><br/>
<input id="box" type="text" placeholder="First Name" onclick="hide(id,'first')" onfocusout="show(id,'first')"/>
</form>
</body>
</html>
EDIT 1:
I have got the solution to my problem using CSS in answer by #Darlesson .
But if possible please tell whats wrong in my Code.
EDIT 2:
As pointed by #lenilsondc my code didn't worked because of var e1 didn't had element but the value attribute of element.
var e1=window.document.getElementById(input_id).value;
replaced to
var e1=window.document.getElementById(input_id);
did worked with e1.placeholder=placehlder;
I would suggest to use CSS for the placeholder portion instead:
:focus::placeholder{
opacity: 0;
}
:focus::placeholder {
opacity: 0;
}
<input placeholder="Visible">
If you can't do this using css (using #Darlesson's answer) for compatibility reasons, you can do this as the following snippet using javascript.
The trick is to store the old placeholder so that when you need to restore you have it available. In this case I used a new attribute data-placeholder where I store de current value and clean the real placeholder attribute. Finally, when the element lose focus, you can get the attribute data-placeholder and reset the real placeholder value with it.
var myInputLabel = document.getElementById('myInputLabel');
var myInput = document.getElementById('myInput');
// when element gets focused
myInput.addEventListener('focus', function (e) {
// save current placeholder
myInput.setAttribute('data-placeholder', myInput.getAttribute('placeholder'));
// clear current placeholder
myInput.setAttribute('placeholder', '');
// show label
myInputLabel.style.display = 'inline';
});
// when element gets blured
myInput.addEventListener('blur', function (e) {
// restore the placeholder stored on data-placeholder
myInput.setAttribute('placeholder', myInput.getAttribute('data-placeholder'));
// hide label
myInputLabel.style.display = 'none';
});
<form>
<label id="myInputLabel" style="display: none;">Name</label><br>
<input type="text" id="myInput" placeholder="Name">
</form>
You can do it without any JS, and only HTML/CSS something like;
.group {
display: flex;
}
.group label {
display: none;
order: 1;
}
.group input {
order: 2;
display: block;
}
.group input:focus ~ label {
display: block;
}
/*
note: browser compatibility is only ~82%
https://caniuse.com/#feat=css-placeholder
*/
.group input:focus::placeholder {
color: transparent;
}
<div class="group">
<input type="text" id="id1" placeholder="Description">
<label for="id1">Description</label>
</div>
var input = document.getElementById("box");
var label = document.getElementById("first");
// When the user clicks on the input element
input.addEventListener("focus", function() {
// Make label visible
first.style.visibility = "visible";
// Remvoe placeholder
input.placeholder = "";
});
// When the user clicks away
input.addEventListener("focusout", function() {
// Check if he did not typed anything
if (input.value === "") {
// Restore placeholder value and hide label
input.placeholder = "First Name";
first.style.visibility = "hidden";
}
});
#first{
visibility: hidden;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>
Functions
</title>
<style>
#first{
visibility: hidden;
}
</style>
</head>
<body>
<form>
<label id="first" >First Name</label><br/>
<input id="box" type="text" placeholder="First Name" />
</form>
</body>
</html>

Is there a way to change the background of a div when text is entered into an input field?

I have the code below and i want every time someone enter/type text inside the input field, force the background of the div with class "target_bg" to change its color from red(default) to green.
<div class="target_bg"></div>
<input placeholder="Search for Restaurants..."
class="search_field" name="" type="text">
I searched a lot for a solution but i found only how to change the background of the input field itself.
if using jquery:
$('.search_field').on('input', function() {
$('.target-bg').css('background-color','green');
});
Here is a solution using plain javascript
var bgElement = document.querySelector('.target_bg');
var input = document.querySelector('.search_field');
input.oninput = function() { bgElement.style.background = 'green'; };
.target_bg {
width: 50px;
height: 50px;
background: red;
}
<div class="target_bg"></div>
<input placeholder="Search for Restaurants..." class="search_field" name="" type="text">

jquery, js. custom text color

How can i change the color of the text inside input box to different color. eg. text to green, red, purple etc.. I planned to use select box to store the different color and based on the selected color change the "text" color: but I am having hard time implementing into code. I am new to js, jquery any help will be greatly appreciated. Also what needs to be done to get the text with selected color to a table(do i save the color in databse?). I will be very thankful to get any help on this .
I made a small demo based on your requirements. You can read the comments in the code.
Something like this:
(function() {
function get(id) {
return document.getElementById(id); // Return the element given an id.
}
var selColors = get("selColors"); // Store the context of the selColors element.
var txtMyText = get("txtMyText"); // Store the context of the txtMyText element.
var myForm = get("myForm"); // Store the context of the myForm element.
var selectedColor = get("selectedColor");
// This is an object that has 2 properties: (color and value). These properties can hold in it string values.
var obj = {
color: "",
value: ""
};
// When you select an option.
selColors.onchange = function() {
if (this.value.length > 0) {
obj.color = this.value; // this.value contains the color that you have selected.
selectedColor.setAttribute("style", "background-color: " + obj.color);
txtMyText.setAttribute("style", "color: " + this.value); // With this you can set a style to the txtMyText textbox.
}
};
// When you submit the form.
myForm.onsubmit = function(e) {
obj.value = txtMyText.value;
console.log(obj); // Shows in the console the object with the current color and value of your textbox.
e.preventDefault();
};
})();
#myForm {
border: solid 1px #335a82;
}
#myForm fieldset {
border: solid 1px #a3c9d4;
}
#myForm fieldset div {
margin: 5px;
}
#myForm fieldset div label {
display: inline-block;
width: 120px;
}
#selectedColor {
display: inline-block;
padding: 10px;
width: 120px;
}
<form id="myForm">
<fieldset>
<legend>Configuration</legend>
<div>
<label>Colors:</label>
<select id="selColors">
<option value="">[Select a color]</option>
<option value="#5069b1">#5069b1</option>
<option value="#ff0000">#ff0000</option>
<option value="#841b72">#841b72</option>
</select>
</div>
<label>Selected color:</label>
<div id="selectedColor">
</div>
</fieldset>
<fieldset>
<legend>Preview</legend>
<div>
<label>Text:</label>
<input id="txtMyText" type="text" />
</div>
<div>
<button type="submit">Send</button>
</div>
</fieldset>
</form>
You could use js to select the class or id of the <input class=".." id="..">
Then you would be able to change the CSS attributes with js.
See the following example
<form method="post">
<input type="text" class="input1">
</form>
So your <input> class is input1. Using the following CSS code you could select a class by its name. See the example below
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
}
</script>
Now by adding a CSS atribute like color to the function you could change the existing or add a new CSS rule to your <input> field.
I think you could get pretty far with this example.
Let me know if it helps!
$('#myinput').css("color","#fdd");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test" id="myinput">
You could try this also:
$('#myinput').css('color',$('#myinput').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="#04edee" id="myinput" onkeyup="$('#myinput').css('color',$('#myinput').val());">
jQuery option to show some fun stuff:
$(function() {
$('#myColors').on('change', function() {
var picked = $(this).val();
$('#currentcolor').css("background-color", picked);
$('#results').append("<div>" + $(this).find("option:selected").text() + "|" + picked + "</div>");
});
// verbose add on click of button
$('#addHot').on('click', function() {
var valHot = '#69b4ff';
var newName = "Hot Pink Triadic Blue";
//$('#myColors').append("<option value='"+valHot+" style='color:"+nameHot+"'>"+nameHot+"</option>");
var newOpt = $("<option></option>");
newOpt.css("color:" + valHot);
newOpt.prop("value", valHot);
newOpt.text(newName);
newOpt.appendTo('#myColors');
console.log(newOpt);
});
});
<div>
<select id="myColors">
<option value="red" style="color:red">Red</option>
<option value="green" style="color:green">Green</option>
<option value="cyan" style="color:cyan">Cyan</option>
<option value="#0080ff" style="color:#0080ff">Analogous Cyan</option>
</select>
<button id="addHot" type="button">
Add Hot Pink Triadic Blue
</button>
</div>
<div>
<div id="currentcolor">
current color is background
</div>
<div id="results">
Show stuff:
</div>
</div>
What you can do create class for every color like .green .purple and just remove and add classes
$(".input1").addClass("red").removeClass("green");
and you can also add remore these classes with selected box color change

Different class (textcolor) in javascript form

I have the problem that I can't set two different text colors (via css classes) in the following javascript form. The standard class is grey (grey text color), but once someone clicks on "Type your mail here" the email color text to type in, should be black. (class black). Someone can help me?
<form name="mainform" method="post">
Your email: <input type="text" size="40" class="grey" name="email" value="{{ fields.email.input }}" onclick="ClearIfAppropriate();">{{ fields.email.error }} <input type="submit" name="submit" value="Go">
</form>
<script type="text/javascript" language="JavaScript"><!--
var LabelText = "Type your email here";
if(document.mainform.email.value.length == 0) {
document.mainform.email.value = LabelText;
}
function ClearIfAppropriate() {
if(document.mainform.email.value == LabelText) {
document.mainform.email.value = "";
document.mainform.email.class = "black";
}
}
//--></script>
CSS Classes
.grey {
color: grey;
}
.black {
color: black;
}
This is easily doable in pure CSS No javascript is necessary:
input.grey:focus
{
color: #000;
}
Although I think ie<8 doesn't support the pseudo-class :focus.
The attribute you want to change is
className
See here http://www.jsfiddle.net/dduncan/hdtvr/
Give an id to your input (id="idElement") and
instead of: document.mainform.email.class = "black";
try:
document.getElementById("idElement").setAttribute("class", "className");
Should do it.

Categories

Resources