Disable button whenever a text field is empty dynamically - javascript

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>

Related

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>

javascript not working for URL re-direct

Can anyone help me with this script I'm trying to get working? I need a text box with a submit button, when a certain id is entered I need them to be re-directed to a certain site (below examples in the script are are yahoo, bing, etc).
This below is what I have so far, but the submit button doesn't show up and when the submit button is hit it doesn't seem to execute the script.
I just get a #? added to the url... I'm working in opencart so I think part of the problem might be with opencart.
<html>
<head>
<script>
document.getElementById("gobutton").addEventListener("click", function(event){
event.preventDefault()
var idmap={
REDDIT:"http://reddit.com",
YAHOO:"http://yahoo.com",
BING:"http://bing.com"
};
id=document.getElementById("siteid").value;
if (id in idmap) {
alert("going to "+idmap[id]);
window.location.href=idmap[id];
} else {
alert("invalid code ["+id+"]")
}
event.preventDefault()
});
</Script>
</Head>
<Body>
<form id="urllauncher" action='#'>
<label for="siteid">Site id</label>
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>
</Body>
</Html>
Thanks for any help on this!
You should add your script at the end of the body.
You are calling document.getElementById("gobutton").addEventListener too early, at this point the button is not yet present in the page DOM, so no event is attached to it.
Working code :
<html>
<body>
<form id="urllauncher" action='#'>
<label for="siteid">Site id</label>
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>
<script>
document.getElementById("gobutton").addEventListener("click", function(event){
event.preventDefault()
var idmap = {
REDDIT:"http://reddit.com",
YAHOO:"http://yahoo.com",
BING:"http://bing.com"
};
var id = document.getElementById("siteid").value;
if(id in idmap) {
alert("going to "+idmap[id]);
window.location.href=idmap[id];
} else {
alert("invalid code ["+id+"]")
}
});
</script>
</body>
</html>
PS : try to indent your code prior to posting it !
I think if you remove that form tag ,it will solve all your problems.
I think there's no need for it be of submit type and have a form at all
Just remove those and the event.preventDefault()

Input text value into a div?

Say I have this text box:
<input type="text" id="myText" placeholder="Enter Name Here">
Upon pressing a button, I would like to send the value entered into this div:
<div id="text2"></div>
I'm not entirely sure how to do this. Do I create a function and call it to the div? How would I do that?
Could someone clear this up for me? Thanks.
Add an onclick to your button:
<input type="button" id="somebutton" onclick="addText()">
Then write the javascript:
function addText()
{
document.getElementById('text2').innerHTML = document.getElementById('myText').value;
}
Solution using onclick event:
<input type="text" id="myText" placeholder="Enter Name Here">
<div id="text2"></div>
<button id="copyName" onclick="document.querySelector('#text2').innerHTML = document.querySelector('#myText').value" value="Copy Name"></button>
JSFiddle: http://jsfiddle.net/3kjqfh6x/1/
You can manipulate the content inside the div from javascript code. Your button should trigger a function (using the onclick event), which would access the specific div within the DOM (using the getElementById function) and change its contents.
Basically, you'd want to do the following:
<!DOCTYPE html>
<html>
<script>
function changeContent() {
document.getElementById("myDiv").innerHTML = "Hi there!";
}
</script>
<body>
<div id="myDiv"></div>
<button type="button" onclick="changeContent()">click me</button>
</body>
</html>
Mark D,
You need to include javascript to handle the button click, and in the function that the button calls, you should send the value into the div. You can call $("#myText").val() to get the text of the text box, and $("#txtDiv").text(txtToAppend) to append it to the div. Please look at the following code snippet for an example.
function submitTxt() {
$("#txtDiv").text($("#myText").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myText" placeholder="Enter Name Here">
<button onclick = "submitTxt()"> Submit </button>
<div id="txtDiv"> </div>
HTML could be:
<input type='text' id='myText' placeholder='Enter Name Here' />
<input type='button' id='btn' value='click here' />
<div id='text2'></div>
JavaScript should be external:
//<![CDATA[
var pre = onload; // previous onload? - window can only have one onload property using this style of Event delegation
onload = function(){
if(pre)pre();
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
var text2 = E('text2'); // example of Element stored in variable
E('btn').onclick = function(){
text2.innerHTML = E('myText').value;
}
}
//]]>
I would recommend using a library like jQuery to do this. It would simplify the event handling and dom manipulation. None the less, I will include vanilla JS and jQuery examples.
Assuming the HTML in the body looks like this:
<form>
<input id="myText" type="text" placeholder="Enter Name Here">
<br>
<input type="submit" id="myButton">
</form>
<div id="text2"></div>
The Vanilla JS example:
//Get reference to button
var myButton = document.getElementById('myButton');
//listen for click event and handle click with callback
myButton.addEventListener('click', function(e){
e.preventDefault(); //stop page request
//grab div and input reference
var myText = document.getElementById("myText");
var myDiv = document.getElementById("text2");
//set div with input text
myDiv.innerHTML = myText.value;
});
When possible avoid using inline onclick property, this can make your code more manageable in the long run.
This is the jQuery Version:
//Handles button click
$('#myButton').click(function(e){
e.preventDefault(); //stop page request
var myText = $('#myText').val(); //gets input value
$('#text2').html(myText); //sets div to input value
});
The jQuery example assumes that you have/are adding the library in a script tag.

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>

Removing default data of a text box while clicking the text

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';
}
}

Categories