Removing default data of a text box while clicking the text - javascript

As you know I want to remove default value of a text box while clicking on it, This code works.
But when I click on the box and then click again another part of screen (I mean out of textbox) the data won't come back.
what should I do?
<html><head><title>(Type a title for your page here)</title>
<script type="text/javascript">
function make_blank()
{
document.form1.type.value ="";
}
</script>
</head>
<body >
<form name=form1 method=post action='test.php'>
<input type=text name=type value='Enter your user id' onclick="make_blank();">Enter User ID
<b>Type</b>
<input type=submit value=Submit> </form>
</body>
</html>

The solution to your problem is one of the following, depending on whether you're using HTML5 or XHTML (or HTML4). Since you're not stating which one you're using, I'll add both.
By the way, you really want to use the focus event, and not the click event. This is because a user can also navigate to a form field using his/her keyboard or by other access keys.
As Quentin correctly states, the specification is clear about what a placeholder text is supposed to be used for. Therefore I've updated the text you're using to something more fitting.
HTML5
<input type="text" name="type" placeholder="email#example.com">
XHTML
HTML:
<input type="text" name="type" value="email#example.com"
onfocus="make_blank(this);" onblur="restore_placeholder(this);" />
Javascript:
function make_blank (oInput)
{
if (!('placeholder' in oInput))
oInput.placeholder = oInput.value;
if (oInput.value != oInput.placeholder)
oInput.value = '';
}
function restore_placeholder (oInput)
{
if (oInput.value == '' && 'placeholder' in oInput)
oInput.value = oInput.placeHolder;
}

The following combination of HTML5 and JavaScript (for HTML4) works nice for me:
HTML:
<input type="text" name="type" placeholder="email#example.com"
onfocus="make_blank(this);"
onblur="restore_placeholder(this);" />
Javascript:
function make_blank(oInput) {
if (oInput.value == 'placeholder') {
oInput.value = '';
}
}
function restore_placeholder(oInput) {
if (oInput.value == '') {
oInput.value = 'placeholder';
}
}

Related

JavaScript only changes text of first iteration with thymeleaf

I hope you are all well.
I have a school assignment, and I want to dynamically be able to change the name of a 'project'. This assignment is about projects. The way I've done it right now works with the first 'project' from a list of 'projects' iterated through with thymeleaf. I'm aware that what I've done right now is absolutely bad code behavior, but we have had no teaching in JS yet. But I really wanted this feature.
I don't know how to make this work for each project preview, right now it works for the first preview, but for the rest it just erases the project name from database. (see picture)
<div class="projects" th:each="projectNames : ${listOfProjects}">
<form action="deleteProjectPost" method="post">
<input type="hidden" th:value="${projectNames.projectID}" name="deleteID">
<input type="image" src="delete.png" alt="Submit" align="right" class="deleteProject" onclick="return confirm('Are you sure that you want to delete this project?')">
</form>
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text()" align="right" class="editProject">
</form>
<form action="/projectPost" method="post">
<input class="projectInfo" name="projectID" type="text" th:value="'Project No.: ' + ${projectNames.projectID}" readonly="readonly">
<input class="projectInfo" type="text" th:value="'Project name: ' + ${projectNames.projectName}" readonly="readonly">
<input class="projectInfo" type="text" th:value="${projectNames.projectStartDate} + ' - ' + ${projectNames.projectEndDate}" readonly="readonly">
<input type="submit" value="OPEN" class="openProject">
</form>
</div>
<script>
function change_text() {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = document.getElementById("oldName").value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
document.getElementById("newName").value = changedText;
}
</script>
First form in HTML is the red cross to delete an entire 'project'. Second form is what is intended to change the name displayed on the 'project preview', but only works on first preview and deletes project name from the rest. Last form is the actual preview. I couldn't find another way to have multiple forms and do different POSTS while working with Java Spring and Thymeleaf.
My wish is to make the change_text() function work for each 'project preview'
Best regards!
function change_text(imageInput) {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = imageInput.parentNode.querySelector('.old-name').value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
imageInput.parentNode.querySelector('.new-name').value = changedText;
}
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" class="old-name" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" class="new-name" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text(this)" align="right" class="editProject">
</form>
Ok so I made a few changes. First, notice the inputs with oldName and newName now have classes on them. These can be repeated. If you are not using the ids for anything other than the script, you should remove them. Otherwise if you have styling rules for them you should consider changing those CSS rules to use the class instead so you can remove the invalid repeating ids.
Secondly, the onlick of the image now passes in this. What that does is it passes in the actual input that the user clicked, so you have some context into which form element the user is interacting with.
Then looking at the logic, the method now accepts in imageInput which is the this from the onclick.
Using imageInput.parentNode we go up the DOM Tree to the parent element of the input, which is the form in this case. We can then turn around and use querySelector to find the other element in the form we want to manipulate. And it will only find the element in our particular form because that is what we are selecting off of.

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

How to only show a div if a certain entry field is filled in (but not submitted)?

Relatively new to html coding, and very new with javascript. On this page, I don't want the option to email an editor to become visible until a tripID is filled in (but form not submitted yet). Here is the form so far without that option added yet:
TripID:
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' /><br><br>
Port:
<input type='text' id='aport' name='aport' size='6' maxlength='6' /><br><br>
<div id=acheckbox><br> E-mail editor? </b>
<input type='checkbox' name='acheck' onchange='copyTextValue(this);'/><br>
<div id='div' style='display:none'>
<br> <b>Subject:</b> <input type='text' id='asubject' name='asubject' size='70' maxlength='75'/><br><br>
<textarea name='aemailbody' cols='85' rows = '10'>Explain any packaging or labeling mistakes here...</textarea>
</div>
</div>
<script>
function copyTextValue(bf) {
if(bf.checked){
document.getElementById('div').style.display = 'block';
var atext = 'Frozen Sample Error Notice: '+ document.getElementById('atripid').value;
}else{
document.getElementById('div').style.display = 'none';
var atext = '';
}
document.getElementById('asubject').value = atext
}
</script>
</div>
Now to hide the email editor option until tripid is filled in, I got something like this to work on jfiddle:
<form action="">
tripid:<input type="atripid" id="atripid" value="">
port:<input type="aport" id="aport" value="">
</form>
<div id="acheckbox" style="display:none">
<br><br><br>
This is where the email options (subject and textbox) would appear.
</div>
<script>
$("#atripid").keyup(function(){
if($(this).val()) {
$("#acheckbox").show();
} else {
$("#acheckbox").hide();
}
});
</script>
But for some weird reason, it won't work anywhere else, so I can't figure out how to incorporate it into what I already have. Does anyone have any ideas that could help me? Thanks!
You can do something like this with pure javascript:
<input type="atripid" id="atripid" value="" onkeyup="keyupFunction()">
And define your keyupFunction().
See jsfiddle
The code you attempted on jsfiddle requires that you import jquery.js files. An alternate way of doung what you intend to do is
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' onkeyup="toggleCheckBox(this)" />
<input type='checkbox' name='acheck' id="acheckbox" style="display:none;" onchange='copyTextValue(this);'/>
with js
function toggleCheckBox(element) {
if(element.value=='') {
document.getElementById('acheckbox').style.display = 'none';
}
else {
document.getElementById('acheckbox').style.display = 'block';
}
}
The issue is the .keyup() method, which is not consistent across browsers and does not account for other means of user input. You would rather, use an Immediately Invoked Function Expression (IIFE) that will detect the propertychange of the input field in question and then to fire the desired event if the condition is met. But for the purposes of simplicity, and the fact that I'm not as well versed enough in IIFE syntax, simply bind some events to the input field, like so:
$("#atripid").on("keyup change propertychange input paste", (function(e) {
if ($(this).val() === "") {
$("#acheckbox").hide();
} else {
$("#acheckbox").show();
}
}));
#acheckbox {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="">
tripid:
<input type="atripid" id="atripid" value="">port:
<input type="aport" id="aport" value="">
</form>
<div id="acheckbox">
<br>
<br>
<br>This is where the email options (subject and textbox) would appear.
</div>

Show div based on if text string equals a specific string

I have been looking through all kinds of information to figure out how to do this. What I am looking for is to show a div based on what is entered in a text box within a form. Later I plan on incorporating this into a form we are currently using in Joomla. This is what I have tried, among other things. This is the most basic attempt. Essentially I want this code example to spit out text value depending on what is entered. In this case, if "yes" is entered, it will spit out "Success", and if anything else is entered, it will spit out "No Luck". From there I would like it to actually show a div. But that's for later, I suppose unless anyone knows how to get there from here. With this code, only "No Luck" gets outputted, regardless if you input "Yes". Thank you in advance for any help you might be able to contribute!
<head>
<script>
function show()
{
var input = document.getElementById("someInput");
if(input == "yes"){
document.getElementById("someDiv").innerHTML = "Success";
}
else{
document.getElementById("someDiv").innerHTML = "No Luck";}
}
</script>
</head>
<html>
<input id="someInput" type="text">
<input type="button" value="Submit" onClick="show()">
<br><br>
<div id="someDiv">
</div>
<br>
</html>
You need to use the .value property if it's an input element
if(input.value == "yes"){
or the .text property if you just want the text inside another element
or the .innerHTML property if you just want the html inside another element
Head always belongs inside html tags fyi. Javascript either belongs in the head or the tag should be the last thing rendered as it is functionally faster to load.
But a solution that appends the success or value to the screen inside the someDiv element should be similar to the following.
<html>
<head>
<script type="text/javascript">
var inputtxt = document.getElementById('someInput');
var appendLocation = document.getElementById('someDiv');
function show() {
if(inputtxt.value === "yes") {
appendLocation.innerHTML = appendLocation.innerHTML + "<div>Success</div>";
}
else
{
appendLocation.innerHTML = appendLocation.innerHTML + "<div>No Luck!</div>";
}
}
</script>
</head>
<input id="someInput" type="text">
<input type="button" value="Submit" onClick="show()">
<br><br>
<div id="someDiv">
</div>
<br>
</html>

Disable button whenever a text field is empty dynamically

Here's my code:
<input type="text" onkeyup="if(this.value.length > 0) document.getElementById('start_button').disabled = false; else document.getElementById('start_button').disabled = true;"/>
<input type="button" value="Click to begin!" id="start_button" disabled/>
This works but still not efficient since the user can delete the text inside the text box and click the button while he's holding on DELETE key. Is there a more efficient way to achieve this using javascript?
Easiest way to do it :-
Simple Html and JavaScript : Run the snippet (Just 7 lines)
function success() {
if(document.getElementById("textsend").value==="") {
document.getElementById('button').disabled = true;
} else {
document.getElementById('button').disabled = false;
}
}
<textarea class="input" id="textsend" onkeyup="success()" name="demo" placeholder="Enter your Message..."></textarea>
<button type="submit" id="button" disabled>Send</button>
I have used textarea, but you can use any html input tags and try it out!
Happy coding!
Add a check when the button is clicked to see if there is any text. If there isn't, pop up an alert box (or some other form of feedback) to tell the user to enter data, and don't do the button functionality.
Example:
<input id="myText" type="text" onkeyup="stoppedTyping()">
<input type="button" value="Click to begin!" id="start_button" onclick="verify()" disabled/>
<script type="text/javascript">
function stoppedTyping(){
if(this.value.length > 0) {
document.getElementById('start_button').disabled = false;
} else {
document.getElementById('start_button').disabled = true;
}
}
function verify(){
if myText is empty{
alert "Put some text in there!"
return
}
else{
do button functionality
}
}
</script>
You could poll the value of the input. This would be less efficient and less responsive but potentially more reliable.
As you pointed out, the keyup event won't neccessarily fire when an input's value is cleared. What if they highlight the text with the mouse, right click and cut?
The change event might help, but it's still not all that reliable. It only fires on blur, and misses some changes (like an autocompletion selection).
Here's a jsFiddle demonstrating the polling solution.
In response to Eng.Fouad's comment, here's how to add the JS:
You could put it in a script tag, like this:
<script type="text/javascript">
//my code
</script>
That will work, but it will mean that your user's browser won't cache the JavaScript, meaning it will take longer to load your page. It's also cleaner to separate your scripts from your content. But if you want a quick and easy option, this should do. Put this at the bottom of your body and wrap it in a dom ready handler (see the bottom part of the answer).
As a cleaner option, you can put it in an external file e.g. someScript.js, the contents of which would be your JavaScript (with no script tags). You then link to that script from your HTML file:
<html>
<head></head>
<body>
<!-- contents of page -->
<script type="text/javascript" src="/path/to/someScript.js"></script>
</body>
</html>
NB: You need to make your script web accessible so that browsing to http://www.your-site.com/path/to/someScript.js accesses the script.
The script tag is at the bottom of the body so that the page loads the actual content first, and the scripts afterwards. This will mean that your content is visible to your users sooner.
You should make one last modification to the JavaScript in the jsFiddle. The jsFiddle has the code running "onDomReady" (see top left of the fiddle). Technically, you don't need to do this if you have your script after your content. It's there to ensure that the script runs after the content has loaded, so that if the script attempts to find elements in the DOM, they have been loaded, and are found. You should probably add this to the script in case (for some reason) you move the script to before the content. In order to wrap your script in a dom ready handler in jQuery, do this:
$(function(){
// my code
});
In that example, code put where the //my code comment is will be run only when the page is ready.
<input type="number" id="abc" onkeyup="s()">
<input type="submit" id="abc2" disabled >
<script type="text/javascript">
function s(){
var i=document.getElementById("abc");
if(i.value=="")
{
document.getElementById("abc2").disabled=true;
}
else
document.getElementById("abc2").disabled=false;}</script>
This is what worked for me. I hope it works for someone else. I needed the button disabled when the user didn't have any text or when they deleted the text.
$('#textarea').on('keypress keyup keydown', function () {
if ($('#textarea').val() == "" ) {
$('#savebtn').prop('disabled', true);
}
else {
$('#savebtn').prop('disabled', false);
}
});
$('#textarea').on('keypress keyup keydown', function () {
if ($('#textarea').val() == "" ) {
$('#savebtn').prop('disabled', true);
}
else {
$('#savebtn').prop('disabled', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" onkeyup="if(this.value.length > 0) document.getElementById('start_button').disabled = false; else document.getElementById('start_button').disabled = true;"/>
<input type="button" value="Click to begin!" id="start_button" disabled/>
Here button is disabled by default and when keyup event is triggered, check if text field value is length is zero or not. If zero then button is disabled, else enabled.
<head>
<title>Testing...</title>
</head>
<body>
<input id="myText" type="text" onkeyup="btnActivation()">
<input type="button" value="Click to begin!" id="start_button" disabled/>
<script type="text/javascript">
function btnActivation(){
if(!document.getElementById('myText').value.length){
document.getElementById("start_button").disabled = true;
}else{
document.getElementById("start_button").disabled = false;
}
}
</script>
</body>

Categories