JS function not displaying anything - javascript

I have made a function and captured the value of a textbox. On a button click, it should alert the value.
The code is:
function substitute (argument) {
var myVal=document.getElementById('myTextBox').value();
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
};
}
It is then executed using this:
<input type="button" name="Button" value="Click Me" onclick="substitute();">
But nothing happens. Please tell me where am I doing it wrong.

You have a few errors:
.value() is not a function: use .value
You don't need that semicolon at the end of the if statement
Your text box might not have the id that you're referring to: make sure that you have id="myTextBox" in the opening tag
While it won't cause any errors, your function definition lists a parameter, but you do not pass one when you call it.
Always check your browser console for errors if nothing is happening. Always.
function substitute () { // Parameter "argument" is not necessary
var myVal=document.getElementById('myTextBox').value; //.value, not .value()
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
}; // You don't need this semicolon
} // You were missing this curly brace
Demo

value is not a function, it's a property, therefore:
var myVal=document.getElementById('myTextBox').value;
As you're brand new to JS, I'll give you a piece of advice: If you want to manipulate the DOM, use jQuery.

In Your code, you are not passing any parameter to function subsititute(), But # function definition you wrote substitute(argument). Thats a big issue, and also you put there is a semi-column after if condition inside the function. No need of it
Try This..
<input type="text" id="myText" value="Hello" />
<input type="button" name="Button" value="Click Me" onclick="substitute();" />
In script part,
function subsitute()
{
var myVal=$('#myText').val();
alert(myVal);
if (myVal=='')
{
alert('Empty Textbox');
}
}

http://jsbin.com/tewudopi/1/edit
Add an ID to the button. When referencing the button, it is not ".value()", it is simply ".value".
As a side note, you should use === instead of == to compare.
function substitute() {
var myVal=document.getElementById('myTextBox');
alert(myVal.value);
if (myVal.value.length===0) {
alert('Empty Textbox');
}
}

Maybe something like the following.
<script type="text/javascript">
function substitute() {
var myVal=document.getElementById('myTextBox').value;
if (myVal.length>0) {
alert(myVal);
}
if (myVal.length==0) {
alert('Empty Textbox');
}
}
</script>
<input type="button" name="Button" value="Click Me" onclick="substitute();">
<textarea name="myTextBox" id="myTextBox"></textarea>
Fiddle demo

Related

Submit button to call function

My submit button is not doing anything when I click on it. I believe my event listener is correctly established. Any ideas on why it wont do anything?
JS FILE
document.getElementById("submitbutton").addEventListener("click", saveNames());
function saveNames() {
var player1name = document.getElementById("player1").value;
var player2name = document.getElementById("player2").value;
var player3name = document.getElementById("player3").value;
var player4name = document.getElementById("player4").value;
var player5name = document.getElementById("player5").value;
savePlayer(player1name);
savePlayer(player2name);
savePlayer(player3name);
savePlayer(player4name);
savePlayer(player5name);
gameScreen(2);
}
HTML FILE:
<input type="text"name="p1"><br>
<input type="text"name="p2"><br>
<input type="text"name="p3"><br>
<input type="text"name="p4"><br>
<input type="text"name="p5"><br>
<input id="submitbutton"type="submit" value="Submit">;
You're not binding to the function, you're binding to the result of the function. Just pass the function itself, don't invoke it. (Get rid of the parentheses):
document.getElementById("submitbutton").addEventListener("click", saveNames);
Why?
Because when that one line of code above executes, if you have the errant parentheses then the first thing it does is execute the saveNames function in order to get the result to pass to the addEventListener function. And that result is undefined because saveNames doesn't return anything.
Presumably also that first invocation of the saveNames function doesn't visibly do anything (though it does execute) because the inputs have no values in them yet at that time.
Consider as a contrived example:
doSomething( doSomethingElse() )
This would execute doSomethingElse() and then pass its returned result to doSomething(). The same is true when adding event listeners, you're just calling a function like any other function.
add the listener like this -
document.getElementById("submitbutton").addEventListener("click", saveNames);
note , I have removed () at end.
Use Id instead of name. you are reading these elements with id then you need to specify that.
Give a spaces before name or type.
//Remove the parenthese after "saveNames" - leaving them will call saveNames when it is encountered
document.getElementById("submitbutton").addEventListener("click", saveNames);
function saveNames() {
//Use an array as it's neater
var players = [
document.getElementById("player1").value,
document.getElementById("player2").value,
document.getElementById("player3").value,
document.getElementById("player4").value,
document.getElementById("player5").value
]
//loop and save
players.forEach(function(name) {
if (name) {
savePlayer(name);
}
});
//gameScreen(2);
}
function savePlayer(name) {
console.log(`${name} saved.`);
}
<input id="player1" type="text" name="p1"><br>
<input id="player2" type="text" name="p2"><br>
<input id="player3" type="text" name="p3"><br>
<input id="player4" type="text" name="p4"><br>
<input id="player5" type="text" name="p5"><br>
<input id="submitbutton" type="button" value="Submit">

clear text box using JS function in a href on click

I have this function:
<script>
function ClearTextBox(textbox_name) {
$(textbox_name).val("")
}
</script>
that removes values from a text input
i am trying to call it using:
Clear
but its not clearing the text box
You should use Unobtrusive JavaScript .
Try this code.
$('a').on('click',function(){
$('#customercompany1').val("");
});
It seems working fine for me.. but the console shows the following error
Uncaught SyntaxError: Unexpected token )
this is due to the javascript:void(); in your href attribute.
so i changed the mark up to
Clear
<input type="text" id="customercompany1" value="test value" />
and the script as
function ClearTextBox(textboxname) {
$(textboxname).val(" ");
return false;
}
Hope this helps....
DEMO HERE
Write your function like this:
function ClearTextBox(myInput) {
var txtBox = document.getElementById(myInput);
txtBox.value = "";
return false;
}
And write your html like this:
Clear
<input type="text" id="customercompany1" />
Need to see your HTML to be sure, but I'm guessing your text box looks like this :
<input type="text" name="customercompany1"/>
and it needs to look like this :
<input type="text" name="customercompany1" id="customercompany1"/>
The '#' jQuery selector matches on the id attribute, not the name attribute.
(This is true if you have used a textarea rather than an input)

javascript in html

i am using javascript to change the text of div tag on run time.
how can this be done..
my div tag is as:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" onclick="edit1();"/>
Div Tag
</div>
i wnt the user to input text on runtime in div and that should be displayed in div.
can someone help me..
It should be innerHTML. innerHTM is not a javascript function.
You don't get a magic variable just by having an element with an id. var something = document.getElementById('some-id')
The property is called innerHTML not innerHTM
innerHTML is a string variable not an function. Assign a value to it with =, don't try to call it with ()
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
and with proper error handling:
function edit1() {
alert('you are in edit1');
var topDiv = document.getElementById('topdiv');
if (topDiv != null) {
topDiv.innerHTML = 'hello';
} else {
alert('topdiv is nowhere to be found in this DOM');
}
}
Try document.getElementById('topdiv').innerHTML = "Hello"
To get the div you should use document.getElementById('topdiv'). There is indeed a WebKit feature, that elements with an ID are automatically expanded as global variables, but it's highly questionable, that this becomes mainstream.
Then, innerHTM should read innerHTML, and you assign directly:
foo.innerHTML = "hi there"
you should use
document.getElementById('topdiv').innerHTML = 'hello';
You should use references instead of ID's, using this.
In that case this means the node that triggers the event.
<div style="color:Blue" onmouseover="button1(this);">
<input type="button" onclick="edit1(this);"/>
Div Tag
</div>
function button1(divRef){
//divRef is the reference to the DIV
}
function edit1(inputRef){
//inputRef is the reference of the INPUT
//inputRef.parentNode is the reference to the DIV
}
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
This should work by specifying the id
In standard JavaScript usage you'd do as per #DarinDimitrov 's answer.
document.getElementById("topdiv").innerHTML = ('hello');
Once you're happy with JavaScript I would suggest you look at the JQuery libraries - the powerful syntax will let you write short, neat code like this:
$("#topdiv").html('hello');
Your file
<div id="topdiv" style="color:Blue" onmouseover="button1();"> Div Tag</div>
<form><input type="button" id="btndiv" value="Edit" onClick="window.open('t2.html','popuppage','width=850,toolbar=1,resizable=1,scrollbars=yes,height=700,top=100,left=100');" value="Open popup"/></form>
t2.html file
function sendValue (s){var selvalue = s.value;window.opener.document.getElementById('topdiv').innerHTML = selvalue;window.close();}
<form name="selectform"><input name="details" value=""><input type=button value="Copy input to parent opener" onClick="sendValue(this.form.details);"></form>
Got Idea from this source enter link description here

Javascript form validation: how to force focus to remain on 'incorrect' field?

I can't believe that I can't find the answer to this question but I really have searched and can't find it! honest!
anyway - here is the question: I am trying to create a validation function for a form that will not permit the user to proceed to the next form field if the field doesn't validate.
I just want the 'incorrect' field to have focus until it is 'correct'.
because this is for a JS class I cannot use jQuery or any other framework.
here is one of the HTML fields:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
and here is a truncated version of the JS function:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
I have tried using 'this.focus();' and 'this.parentNode.focus();' but no joy.
I am sure the answer is ridiculously simple, but I can't seem to find it.
thanks,
bennett
Try sending the object reference to the function instead of the value.
So in your input event:
validateAndDraw(this);
And change your function to:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
As a side, I would suggest looking into Progressive Enhancement.
document.getElementById('star1').focus();
Using this inside your function will refer back to the function.
Alternatively, you could pass the object in the onclick event:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
so the function could look like
function validateAndDraw(obj) {
alert(obj.value);
}
Try calling focus() in the blur event.
Also, this in your function refers to the global context, not the element.
(It only refers to the element inside the inline handler; you are making an ordinary function call from there)
You should change your function to accept the element as a parameter (which you can pass as this insidethe inline handler)
Why not pass in the element?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
Send as trigger
There are for each loop function for check input in form.
If there are input[x].value = "", so alert and focus in it, next input and next alert
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>

If input2 empty copy value from input1?

This is my first message here so I hope that newbies also get help :)
My problem is following:
let's start with code first....
javascript:
$(document).ready(function(){
if ($("input#datum2").val() == "")
{
$().click(function(){
$("input#datum2").val($("input#datum1").val());
});
}
});
html:
<form >
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
What I want this script to do is that first checks if input field datum2 is empty. If yes, than copy value from input#datum1. This action is suppose to happen each time user clicks (anywhere on page?)...
When user types something in datum1 and clicks somewhere than this value is copied to datum2. The problem is when user edits datum1 or datum2, than this value is again copied to datum2. Obviously this condition
if ($("input#datum2").val() == "")
works only once.
I'm new to javascript and jquery so I would appreciate for any help.
Thanks in advance!
Cheers,
Ile
Sounds like you'll need to bind to a different event. Blur occurs when an input loses focus, which sounds like what you're after.
$(function() {
var $datum2 = $('#datum2');
$('#datum1').blur(function() {
if(!$datum2.val())
$datum2.val($(this).val());
});
});
Couple of things:
1) $(function() { ... is a nice shortcut to $(document).ready
2) In JavaScript, an empty string evals to false, so its a nice shortcut.
I see the way round are the order of the click event and "if ($("#datum2",..."
HTML:
<form id="myform">
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
Javascript:
$(document).ready(function(){
$().click(function(){
if ($("#datum2", $("#myform")).val() == "") {
$("#datum2", $("#myform").val($("#datum1", $("#myform")).val());
}
});
});
$(document).ready(function(){
var $datum2 = $('#datum2');
$('#datum2').hover(function() {
if(!$datum2.val())
$datum2.val($('#datum1').val());
});
});

Categories

Resources