My javascript placeholder function(s) only work in IE - javascript

I decided as placeholders are part of HTML5 and not fully supported by the browsers to make my own little placeholder system using Javascript.
This script seems to work perfectly for IE9 but not in Chrome, Safari, Oprea or Firefox.
I'm not sure what the culprit is but for some reason when I click in the field, it drops the cursor in amongst the placeholder text rather than clearing the field and allowing the user to type in a blank field as intended.
Could someone please help me correct this issue?
Chrome is returning the following error messages
Uncaught TypeError: Cannot set property 'className' of null
Uncaught TypeError: sting is not a function
The way I code this was that once the form loads the input field 'livesin' it calls my function, then when a user types or the field loses focus it calls the script again.
This is the form field that is using the placeholder system, the span contains my little tick or cross graphics for the form validation.
<label>Where do you live<br />
<input id="livesin" onfocus="placeholder()" onblur="placeholder(); addTick('livesin')" maxlength="50" placeholder="e.g. NSW, Australia" />
<script>placeholder()</script>
</label>
<span id="livesintick" class="neutral"></span>
Function placeholder checks to see if the value of the input field is blank, and if so adds my placeholder text and a class to style it, if the field contains my placeholder text I set the value back to being blank and the class to style the user input to look normal once more. After either of these options in then calls another function, explained beneath.
function placeholder(){
if (_("livesin").value == "") {
_("livesin").className = "placeholderFake";
_("livesin").value = "e.g. NSW, Australia";
} else if (_("livesin").value == "e.g. NSW, Australia") {
_("livesin").className = "placeholderNormal";
_("livesin").value = "";
}
addTick('livesin')
}
_() Function
function _(x){
return document.getElementById(x);
}
Function addTick accecpts any element name passed to it from my form and basically displays a tick graphic next to each form field that isn't empty.
function addTick(elem){
// Specific for livesin field, checking for fake placeholder
if (_(elem).value == "e.g. NSW, Australia") {
alert (elem);
if (_(elem).className == "neutral") {
exit;
}
_(elem+"tick").className = "neutral";
}
if (_(elem).value != "") {
_(elem+"tick").className = "valid";
}
}
My css is as follows
#livesin.placeholderFake {
color:#808080;
vertical-align:middle
}
#livesin.placeholderNormal {
color:#000000;
vertical-align:middle
}

Related

Javascript form using regex not validating correctly

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

Using jQuery $(this).addClass() breaks working code

I'm creating a form where an error message appears when the input loses focus if the input is empty. I also want to add a class to the input to give it a red border.
The problem arises when I add $(this).addClass("error"); - the error message no longer shows. Does using addClass() change the reference of this within the function? Can anybody explain to me what is happening? I'm usually pretty good with jQuery but I'm a bit lost here.
Here's my code:
$(function() {
$.fn.showError = function(error) {
$(this).addClass("error");
$errorElement = this.closest(".input-field").find(".error");
if (!$errorElement.length) {
$errorElement = $('<span class="error"></span>').appendTo(this.closest(".input-field"));
}
$errorElement.text(this.data("errormsg"));
};
$("input").on("focusout", function(e) {
$(this).showError();
});
});
.error {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="input-field">
<input type="text" data-errormsg="Please enter your first name" />
</div>
$errorElement = this.closest(".input-field").find(".error");
Since you just added error to the input, this line finds the input and adds the text to it, however since an input element has no children, the text isn't shown. Use
$errorElement = this.closest(".input-field").find("span.error");

Changing html content using if statement and jquery

i'm trying to display certain sentences and images according to the value of a select menu.
If an user selects that his platform is "Android", then he'll see an specifc message. If he selects that his platform is "iOS", then he will see another.
I want to achieve this using a variable "isAndroid", if it is true it will display the Android message plus the android icon and if it is false it will display the iOS message and the iOS icon.
Then i implemented the jquery method "change()" to being able to swtich and change the content whenever the selector value is changed between "Android" and "iOS". I've managed to achieve my objective in a different and more complicated way, but i want to do it with this boolean to use it on more stuff later, if "isAndroid" is true it will do many other things, but i'm showing the basic here to keep it simple.
This is my actual HTML and Javascript code:
function platformAndroid() { //function with the content of Android. it should run if "esAndroid" is true
$("#iconoDispositivo").attr("src","http://i.imgur.com/ksYWdrF.png");
$("#chosenPlatform").html("Your chosen platform was android");
}
function platformIos(){ //function with the content of iOS. it should run if "esAndroid" is false
$("#iconoDispositivo").attr("src","http://i.imgur.com/YPqQsib.png");
$("#chosenPlatform").html("Your chosen platform was iOS")
}
var isAndroid = true;
function dispositivoStart(){ // this functions displays the correct stuff when user refresh the page
if($('#dispositivo').val() === "Android"){ //if my select input value is android, then "esAndroid" is true
isAndroid;
} else {
isAndroid = false; // otherwise it is false
}
$('#dispositivo')on.("change",function(){ //here i wrote this piece of code to switch "esAndroid" to true or false when they select different values on the selector input
if($(this).val() === "Android"){
isAndroid;
} else {
isAndroid = false;
}
})
if(isAndroid){ // here is the piece of code that displays the content. if esAndroid is true, then the function that displays "Android" content runs.
platformAndroid()
} else {
platformIos() //if "esAndroid" is false, then the function that displays "iOS" content runs
}
}
dispositivoStart();
#chosenPlatform {
font-size: 20px;
color: green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Platform choose
</title>
</head>
<body>
<h2>Platform</h2>
<div class="field">
<label for="dispositivo">Choose your platform</label><br>
<select id="dispositivo">
<option>Android</option>
<option>iOS</option>
</select>
</div>
<div class="field">
<p id="chosenPlatform">Your chosen platform was Android</p> <img src="http://i.imgur.com/ksYWdrF.png" width="32" alt="androidIcon" id="iconoDispositivo">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js"></script>
</body>
</html>
I can't understand why in the snippet i can't call jquery correctly, in my own files i use cdns, but that's the code that i'm trying to run.
With the current code, the boolean from "isAndroid" changes to false, but doesn't display the content that it should display when "isAndroid" is false (the iOS content). It also doensn't switch back to true when the select input value switchs to "Android" again.
As i said at the beggining, i could achieve my objetive if i use
#dispositivo.val() === "Android"
but i think that doing "isAndroid" = true/false is simpler, becouse later on i have to keep using that boolean to display certain content depending on that selector value.
I hope i was clear enough, this is my second question written on Stackoverflow, thanks in advance.
Before we address your primary issue, we should address your HTML. Run the HTML through a validator (not W3C, it's outdated). The demo features a working example of HTML content being inserted into a <section> and values being set in an <output> form control, which is determined by a user's selection of a <select>.
Methods, Properties & Processes
jQuery
.on() Event Delegation
.html(), .text(), & .val()
JavaScript
ES6 Template Literals
switch()
Details are commented in demo
Demo
/* NOTE: ES6 Template Literals are being used instead of
|| String Literals:
[Example: String Literal >>>
var SL = "This is a String, this is a " + variable\
+ " concatenated";
[Example: Template Literal >>>
var TL = `This is a String, this is a ${variable}
interpolated`;
*/
/* Register change event on the select#mobile
|| .on() method delegates events. Main advantage
|| of delegating events is that the event will
|| be registered not only for elements currently
|| in DOM, but elements that will be there in the
|| future.
*/
/* Callback function is getContent which is invoked
|| upon a change event occurring on #mobile
*/
$('#mobile').on('change', getContent);
function getContent(e) {
// Store the value of a form control (i.e. #mobile)
var opt = this.value;
/* Pass value to a switch(). A switch() method is
|| a if/if else condition that's easier to read.
*/
switch (opt) {
// if (opt === 'android') {...
case 'android':
/* If getting/setting data of a form control
|| use .val() method.
|| ex. input, output, select, etc..
*/
// Change the value of output#out
$('#out').val(`Selected OS is Android`);
/* If getting/setting content between an element's
|| tags use .html() or .text() methods
|| ex. <div>CONTENT</div>
*/
// Change the HTML of section.dock
$('.dock').html(
`<h1>Samsung Galaxy</h1>
<label>Model: <input></label>
<button>DONE</button>`);
break;
case 'iOS':
$('#out').val(`Selected OS is iOS`);
$('.dock').html(
`<h1>iPhone</h1>
<label>Model: <input></label>
<button>DONE</button>`);
break;
/* If its neither 'android' nor 'iOS', then it
|| refers to default case. In this particular case
|| output#out and section.dock will be erased.
*/
default:
$('#out').val('');
$('.dock').html('');
break;
}
}
select,
input,
button,
label {
font: inherit
}
<form id='interface'>
<select id='mobile'>
<option value='-'>-------------</option>
<option value='android'>Android</option>
<option value='iOS'>iOS</option>
</select>
<output id='out'></output>
</form>
<section class='dock'></section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript catch unselected radio button along with textboxes and alert

I'm practically new here and i'm a beginner in programming.
I am creating an html/js based template for my team for easy consolidation of data and copy to clipboard so we can easily paste it in our main tool.
The problem is that doesn't seem to work properly (at least here at the office, at home it does work).
It doesn't prompt when the radio selection is empty, so I am resorting to using my current function that catches any textboxes/textarea that is empty. (sample code below)
if (document.getElementById('INbrief').value == "") {
errCatch +="-Issue/Request \n";
valid = false;
}
if (document.getElementById('INdesc').value == "") {
errCatch +="-Issue/Request Description \n";
valid = false;
}
if (!valid) {
document.body.removeChild(dummyTxtArea);
alert(errCatch);
return valid;
} else {
document.body.removeChild(dummyTxtArea);
alert ("Data has been copied to Clipboard.");
}
The above if else is inside a Function that is called when the Evenlistener is triggered via "click" of the submit button. I tried inserting a 'for' statement above the if else inside the function but it wont work and the alert will only show that the textbox/area are empty. Thanks in advance for your help
Your code was throwing errors at lines 4 and 5 when you were trying to get the value of an unchecked radio box and set the variable to that value:
var selectedLOB = document.querySelector('input[name="INlob"]:checked').value; //LOB selected
var selectedSev = document.querySelector('input[name="INsev"]:checked').value; //Severity selected
In order to fix this you must first check if the radio is selected, and then if it is get the value that is selected. You can do that by replaceing your lines 4 and 5 with the following:
var selectedLOB = document.querySelector('input[name="INlob"]:checked') ? document.querySelector('input[name="INlob"]:checked').value :false;
var selectedSev = document.querySelector('input[name="INsev"]:checked') ? document.querySelector('input[name="INsev"]:checked').value :false;
This code will first check to see if the radio is checked, if it is it will set the variable to the value, if it is not it will set the variable to false.
(The a ? b : c is know as the conditional or ternary operator and is just a short if() else()statement). This change will stop the errors from being thrown.
You will also need to update your checks further down for the radios to:
if (selectedLOB == false) {
errCatch +="-Choose LOB \n";
valid = false;
}
if (selectedSev == false) {
errCatch +="-Choose Severity \n";
valid = false;
}
As a side note you don't have to set uncheck radios to false, you could set them to a string like 'unchecked' or ''empty' if it helps make your code more readable. Just be sure to make sure that your checks match what you set it to.

What is wrong there? textarea shows nothing but value is

I wring a code to show hint to user in textarea in grey color;
Idea is next:
1) Initially in area is "Please, type your enquiry there" in grey color;
2) if user click on it, color change to black and text to ''. This part works fine
3) if user type, but than delete (i.e. left field blank) than we need to put "Please, type your enquiry there" in grey color; And this do not work non in Chrome, non in Firefox.It display nothing. When I use chrome inspector, it shows
element.style { color: rgb(141, 141, 141); }
what is right and "Please, type your enquiry there" in HTML what is also right, but field is empty. What might be the problem???
I specially put console.log and they also display output that should be...
This is HTML:
<textarea name='contact_text' id='contact_text'
onclick='text_area_text_cl();' onBlur='text_area_text_fill();'>
</textarea>
<script>
var contact_text_changed = false;
var contact_contacts_changed = false;
function text_area_text()
{
if (contact_text_changed == false)
{
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your enquiry there');
}
else
{
$("#contact_text").css("color","#000000");
}
// Write your code here
};
function text_area_text_cl()
{
if (contact_text_changed == false)
{
$("#contact_text").text('');
$("#contact_text").css("color","#000000");
console.log('sdfdfs111');
contact_text_changed = true;
}
};
function text_area_text_fill()
{
if ($("#contact_text").val() == '')
{
contact_text_changed = false;
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your enquiry there');
//document.getElementById('contact_text').innerHTML = 'Please, type your enquiry there'
console.log('sdfdfs');
}
else
{
console.log('__');
}
};
// call funcitons to fill
text_area_text();
</script>
To set the value of a <textarea> you need to use .val():
$("#contact_text").val('');
or
$("#contact_text").val('Please, type your enquiry there');
etc. It's tricky to make "placeholder" code work properly. Newer browsers allow:
<textarea placeholder='Please, type your enquiry there' id='whatever'></textarea>
and they manage it all for you.
edit — from the comments, here's an explanation as to why it appears that .html() works (well, it does work, but read on) initially. The markup contents of a <textarea> element — that is, the DOM structure contained within the element — represents the initial value of the <textarea>. Before any user interaction (and/or before the "value" property of the DOM has been touched by JavaScript), that's what's shown as the value of the field. Changing that part of the DOM, then, changes that initial value. Once there's been some user interaction, however, the initial value is no longer relevant to the page view, so it's not shown. Only the updated value is shown.

Categories