What is wrong there? textarea shows nothing but value is - javascript

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.

Related

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.

My javascript placeholder function(s) only work in IE

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
}

How to make jquery reference dynamic html elements

Below is part of a script I have which dynamically adds html input text boxes. Each one of these input boxes should be an autofil text box. This is the code I'm using - http://www.nodstrum.com/2007/09/19/autocompleter/. Demo is here - http://res.nodstrum.com/autoComplete/.
For the above example it is only one input box but my code allows for dynamic input text boxes (i.e. the user clicks on a button and more pop up).
The problem I have is I don't know how to fix the jquery so that it's dynamic for the input text box id. How do I make it dynamic so that fill() outputs data to foo01, foo11, foo21 etc. not just foo11?
<script src="jquery-1.2.1.pack.js" type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#foo11').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
<script type="text/javascript">
var x = 1;
function add() {
var fooId = "foo";
for (i=1; i<=2; i++)) {
var element = document.createElement("input");
element.setAttribute("type", fooId+x+i);
element.setAttribute("name", fooId+x+i);
element.setAttribute("id", fooId+x+i);
if(i==1){
element.setAttribute("onkeyup", "lookup(this.value);");
element.setAttribute("onblur","fill();");
element.setAttribute("value", "First name");
}
if(i==2){
element.setAttribute("value", "Last name");
}
var foo = document.getElementById("fooBar");
foo.appendChild(element);
}
x++;
}
</script>
rpc.php
<?php
include_once("includes/config.php");
$conn = new mysqli("$localhost", "$dbusername", "$dbpass", "$db", "3306"))
if(!$conn) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $conn->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE '$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this...
// $queryString = 'Uni';
// Returned data = 'United States, United Kindom';
$query = $conn->query("SELECT name FROM cities WHERE name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->name.'\');">'.$result->name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
****************EDIT*****************
It needs to be filled individually. It looks like this:
Text Box (foo00) Text Box
Add
If you click on Add you get
Text Box (foo00) Text Box
Text Box (foo10) Text Box
Add
If I was to click on text box (0,0) and started typing "Lo" a text box would pop up with London, Logon etc. Then if you click on "London", only (0,0) will be updated and will now be "London" i.e.
London Text Box
Text Box Text Box
Add
Now I click on the text box below London (foo10) and start typing "Ro" and a text box would pop up with Rome, Romania etc. I click on Rome and only foo10 should be updated and will look like this:
London Text Box
Rome Text Box
Add
Hopefully that helps with the questions below.
I've never used jquery before this example. I'm using jQuery 1.2.1 because that's what the example said. I'll need to look into a newer version of JQuery.
************** EDIT 2 **********************
I didn't realise that the file rpc.php called fill(), which is where I believe the issue to be. I've updated the code above to include rpc.php and the jquery which calls it.
In the following function, you have hard coded the id foo11
function fill(thisValue) {
$('#foo11').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
Instead, you can use this operator to access the specific textbox that called the fill() method.
function fill(this) {
$(this).val(thisValue); // will access the current element but not sure where you are getting the value
setTimeout("$('#suggestions').hide();", 200);
}
and change the onblur like this
element.setAttribute("onblur","fill(this);");
After reading your updated question, I tried to make a sample application but unfortunately I can't make it to work without changing too much. The problem is, the method you are using to create auto complete works in a way that it is difficult to make it work with dynamically added HTML. So here are my 2 alternatives.
Make some changes in the rpc.php code and only emit values as array and create HTML on the client.
Since you are already using jQuery, try jQuery autocomplete
You can find info about autocomplete here and here
I already made a sample for you using jQuery autocomplete. Check this fiddle

Detect first character in textfield with Jquery

I'd like to know how to do the following with Jquery:
I have 1 textfield in a form.
Whenever the first character is a number, change the attr name of this field to 'number'. If the first character is a letter, change this attr name to 'letter'.
!! This also has to work when a number or text is copy-pasted into the field.
Thanks!
Jeroen
Bind (some) event(s) to the text field: The keyup event is used to update the name attribute when the user modifies the text (including shortcut CTRL+V copy-pasting), the paste and mousemove events are used to deal with copy-pasting (dragging, contextmenu).
$("#your-input").bind("keyup paste mousemove", function() {
var char = this.value.charAt(0); // Use vanilla JavaScript to get the
// first character of the text field
if (/[0-9]/.test(char)) { // Test against a pattern: digit
$(this).attr("name ", "number");
} else if (/[a-zA-Z]/.test(char)) { // Else, pattern: letters
$(this).attr("name", "letter");
} else { // Finally, no name?
$(this).attr("name", "");
}
});
Remove else {...}, and replace else if(/[a-zA-Z]/.test(char)) { with else { if you want the default name to be letter.
Something like this:
$("#yourformid").submit(function(){
var input = $("#yourinputid"),
val = input.val();
input.attr("name", /^\d/.test(val) ? "number" :
/^[A-Z]/i.test(val) ? "letter" : "");
});
It's difficult to handle paste in all browsers, but if you just set the attribute when the form is submitted you're covered no matter what the user does including drag'n'drop changes to the field. (Obviously I'm assuming it doesn't matter what the attribute is before submit.)

Categories