Show div based on if text string equals a specific string - javascript

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>

Related

I can't seem to define variables in my code, because document.getElementById( ) won't insert the value in it [duplicate]

This question already has an answer here:
The values for document.getElementById().value are null
(1 answer)
Closed 10 months ago.
I am trying JavaScript and HTML with a little CSS (that is not required), and I can't seem to define this variable.
I have the element id with this HTML code:
<p class="margin"><b>Got </b>
</p><input type="text" class="margin" id="iGotThis">
<p class="margin"><b> out of </b></p>
<input type="text" class="margin" id="outOfThis">
and get it into a variable with js and this code:
var made = document.getElementById("iGotThis").value;
var total = document.getElementById("outOfThis").value;
var perMade = made / total;
and I am trying to alert the result with an alert function:
document.getElementById("submit").click();
}
});
function perFunction() {
alert(total);
};
Here is the full code:
<!DOCTYPE html>
<html>
<head>
<style>
.margin {
margin-left: 80px;
}
</style>
</head>
<body>
<br>
<br>
<p class="margin"><b>Got </b></p><input type="number" class="margin" id="iGotThis"><p class="margin"><b> out of </b></p><input type="number" class="margin" id="outOfThis">
<br>
<br>
<input type="submit" id="submit" class="margin" onclick="perFunction()">
<script>
var iGotThis = document.getElementById("iGotThis").value;
let outOfThis = document.getElementById("outOfThis").value;
var perMade = iGotThis / outOfThis;
// This entire portion has no use for the variables
var input = document.getElementById("outOfThis");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
// This is where the useless section ends
function perFunction() {
alert(iGotThis.value);
};
</script>
</body>
</html>
I have tried just alerting the variable made or total but just comes up blank. I can't think of a solution so I am hoping someone can help. I am still pretty new to this stuff and can't so everything.
there is no ID as "total" in the HTML code. Please check that
Input type=textbox is wrong. You can use type=text. Maybe the browser doesn't understand textbox's value, because textbox isn't an official HTML type value. You see an textbox, because the browser doesn't know what IT should use.

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>

Take input value and display in another div

I cant for the life of me figure out why the following is not working. I took if from the W3school example here.
Basically I want to take the value from the input text when it changes and modify another div to include the value. I only want the div to show the new value, but I do want it to change it each time so I figured the onchange was the way to go.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + x.value;
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<div id="divID"></div>
</body>
</html>
Thanks in advance for all the help on this one.
You have 2 problems, first is that x is undefined.
second you should use another trigger for this for this to happen each time.
try this out:
function myFunction()
{
var input = document.getElementById('fname')
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + input.value;
}
and change your html to:
<input type="text" id="fname" onkeypress="myFunction()">
x is undefined in your function, it should be document.getElementById('fname').
And if you want to change the div each time you press the key, use onkeyup or onkeypress instead of onchange.
You may change x.value to document.getElementById("fname").value, if I understand your question correctly.
<head>
<script type="text/javascript">
function input(){
var input_taker = document.getElementById('email').value;
document.getElementById('display').innerHTML = input_taker;
}
</script>
</head>
<form method="post" action="#">
<input type="text" name="email" placeholder="email#example.com" id="email" onchange="input()">
<input type="submit" name="save" value="save">
</form>
<div id="display"></div>
Ok, so check this out - http://jsfiddle.net/2ufnK/2/
The issue is that you need to define x here,
var x = document.getElementById("fname");
x now references to the html object.
Then you can just call the, ".value", method to get its text. Then everything else works the way you've written it.

insert text to selected Textbox use Javascript

I have 2 textBox and 1 button!
I want to insert text to one of these textboxs. When I click to textbox_1 and click button, mytext will appear at textbox_1. When I click to textbox_2 and click button, mytext will appear at textbox_2.
How can I do this by using JavaScript?
Please help me! I'm new on JavaScript!
put id's of the two textboxes as textbox_1 and textbox_2 and put onclick='onCLickButton();' on the <button> tag
and write the following code in the script
var text_to_be_inserted = "sample";
function onCLickButton(){
document.getElementById("textbox_1").value='';
document.getElementById("textbox_2").value='';
if(document.getElementById("textbox_1").focused){
document.getElementById("textbox_1").value=text_to_be_inserted;
}
else if(document.getElementById("textbox_2").focused){
document.getElementById("textbox_2").value=text_to_be_inserted;
}
else{
// do nothing
}
}
Edited
Please accept my apologies actually I am used to use these functions as I have my own js file having these functions.
please add onfocus='onFocusInput(this);' in the <input> tags and add the following code in the script
function onFocusInput(object){
document.getElementById("textbox_1").focused=false;
document.getElementById("textbox_2").focused=false;
object.focused = true;
}
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts to text box when clicked the button";
function DisplayText(){
if(!index){
document.getElementById("txt1").value = text;
document.getElementById("txt2").value = "";
}
else{
document.getElementById("txt2").value = text;
document.getElementById("txt1").value = "";
}
index = index ? false : true;
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="button" value="Change Text" onclick="DisplayText()"/>
</body>
</html>
Take a look at the onFocus() attribute for the INPUT tag - and think about keeping track of what was last given the focus. I'm being a little vague as this sounds a lot like homework.
It isn't the prettiest / most delicate solution, but it works and you can build off it to fulfill your needs.
<script>
var field = 0;
function addText(txt){
if(field === 0) return false;
field.value = txt;
}
</script>
For a form such as
<form>
<input type="text" name="box1" id="box1" onfocus="field=this;" />
<input type="text" name="box2" id="box2" onfocus="field=this;" />
<input type="button" onclick="addText('Hello Thar!');" />
</form>

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