How to fix jquery .is(':focus') not responding - javascript

I'm making an if statement but it doesn't seem to work. I think it has to do with the :focus (jquery is implemented)
I tried using $("input:focus") but when I pressed enter anywhere, (focused or not) it shows the alert.
<script type="text/javascript" src="script.js"></script>
<body style="background-color: #90EE90;">
<center>
Sample text
<br><br><br><br>
<input type="text" name="user-input" placeholder="insert name">
<br><br>
</center>
<script>
var input = $('#user-input').val();
$(document).ready(function () {
$(document).keypress(function (key) {
if (key.which === 13 && $('#user-input').is(':focus')) {
alert("hello");
}
})
})
</script>
</body>
When I press enter while user-input is highlighted, it should've gave the Hello alert, but instead, nothing happens.

change name="user-input" to id="user-input"

Related

i want the value of the input but it always alert 0

I want the value of the input but it always alert 0, how can I get the value of input
below, I cant get the value - the value of input is just numbers
$(document).ready(function() {
var text = Number($("#text").val())
$("#btn").click(function() {
$("#p").text(text)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="text" placeholder="Enter a number" class="txt"><br>
<button id="btn">RUN</button>
<p id="p"></p>
The problem is that you get the variable value when the page loads and you never get it later. You need to get it whenever you click the button. I have edited it for you and now it works.
$(document).ready(function(){
$("#btn").click(function(){
var text = Number($("#text").val())
$("#p").text(text)
})
})
Did you added a js library on your page?
<!DOCTYPE html>
<html>
<body>
<head>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
</head>
<input type="text" id="text" placeholder="Enter a number" class="txt"><br>
<button id="btn">RUN</button>
<script>
$(document).ready(function() {
$("#btn").click(function() {
alert($("#text").val());
})
});
</script>
</body>
</html>

stop the page refreshing when enter is pressed while cursor is in a form input element but still submit?

I have been reading through many articles relating to this but they only show how to prevent anything happening not only the page refresh.
But I need to have it so when enter key is pressed the text field is submitted via a ajax request without the page refresh, like how I can use the input type button with a onclick event.
iv added a very basic mock up below to help explain what I mean.
<html>
<head>
<title>Demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.2/jquery.min.js'></script>
</head>
<body>
<form id="someForm" action="" method="post">
<!--
below is an example of the text field
id like to submit but without the
page refreshing when "Enter" is pressed
-->
<input type="text" id="demoText"/>
<button type="button" id="postBtn" onclick="postText()">Post</button>
</form>
<script>
function postText() {
alert("Random Function...");
}
</script>
</body>
</html>
You can do something like this to capture the keypress event of a control - say an input box.
$(function() {
$('#demoText').keypress(function (e) {
var key = e.which;
if(key == 13) // enter pressed
{
postText();
}
});
});
There are more examples here
To post using Ajax, do something like this:
var postText = function() {
var stuff = $.post("serverpage.php", function() {
alert( "success" );
}).fail(function() {
alert("error");
}
)};
No need for any script, the browser will do it for you if you have a submit button ( not type="button") and bind your function to submit event of the form
<form id="someForm" action="" method="post" onsubmit="postText();return false">
<input type="text" id="demoText" />
<button type="submit" id="postBtn">Post</button>
</form>
DEMO
After the advise given here this is what i came up with and it is fully functional, so thought id add it here as an answer so anyone else with a similar question can view my solution.
<html>
<head>
<title>Demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
</head>
<body>
<form id="form">
<input type="text" class="input" id="chatTxt" placeholder="Chat post..."/>
<input type="button" id="submit" value="Submit"/>
</form>
<script type="text/javascript">
$('form').keypress( function( e ) {
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
$( "#submit" ).click();
};
})
$(document).ready(function(){
$("#submit").click(function(){
var ChatText = $("#chatTxt").val();
if(ChatText ==''){
alert("Chat text is empty!");
}
else{
$.post("demo.php",{ ChatText1: ChatText },
function(data) {
alert(data);
$('#form')[0].reset();
});
}
});
});
</script>
</body>
</html>

javascript form / comparing randomly generated number to user input

I'm trying to compare a randomly generated number to a number input by the user (via a form in HTML). The JavaScript function executes instantly when the page is loaded, rather than waiting for the user to enter a number in the form. Also the form input does not seem to be doing anything.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Hot Or Cold</title>
<script type ="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="app.js" type="text/javascript"></script>
</head>
<body>
<div id="gameBox">
<p>Enter a number between 1 and 100</p>
<input type="text" name="userinput" id="userinput" maxlength="3" autocomplete="off"/>
<input type ="submit" name="submit" id="submit" class="button"/>
</div>
</form>
</body>
</html>
and my JavaScript code:
var computer = Math.floor(Math.random()*100);
var user = document.getElementById("#userinput");
function game(user, computer){
if (user == computer) {
alert("You picked the correct number!");
}
else if (user > computer) {
alert("Too high.");
}
else if (user < computer) {
alert("Too low.");
}
}
game();
It is not working how you expect because your submit button doesn't do anything, and you are in fact calling your function when the page loads.
Remove the last line of our JavaScript, the call to
game();
Change your submit button to this
<input type=button onclick=game(); class=submit value=Submit>
Remove the closing
</form>
tag since you have no opening form, but you dont need one.
Also to get the input number
var user = parseFloat(document.getElementById("userinput").value);
Since js does not use hash before ids like jquery, and form values are all strings until they are parsed.
You need to use an event handler so that your function is called when the form is submitted, like so:
document.getElementById('myform').addEventListener('submit', function(e){
var user = document.getElementById("userinput").value;
game(user, computer);
e.preventDefault();
});
I fixed your code in this JSFiddle.
i'm writing the entire code hope you get it.
<!DOCTYPE html>
<html>
<head>
<body>
<h1> Game </h1>
<input type="number" id="id1">
<button type="button"
onclick=" game()">
Click me.</button>
<script>
var computer = Math.round(Math.random()*100);
console.log(computer);
var user=document.getElementById('id1').value;
function game(){
if(user == computer)
{
alert("yay! Good Work");
}
else{
alert("Sorry Not Matched");
}
}
</script>
</body>
</head>
</html>

Where did I make a Javascript error in this short section of code?

I have made a short demo of a javascript problem. When the Submit button is clicked, the alert pops up informing the user that a blank value is not allowed, which is good. But then the page submits anyways, which is bad.
It seems this behavior is only happending on hidden fields.
(Its more clear if you enter any value into the name field. Click Submit. I know the page submits because the value in Name clears out.)
Can anyone see what is wrong here?
<html>
<body>
<form action="" method="post" name="form" onsubmit='return validate()'>
Name: <input type="text" name="name" id="name">
<br><br>Signature: Hidden <input type="hidden" name="poa_esign_signature" id="poa_esign_signature">
<br><br><button type="submit">Sign</button>
</form>
<script type="text/javascript">
function validate() {
var element=document.getElementById('poa_esign_signature');
if (element.value=='') {
alert('Signature may not be blank.');
element.focus();
return false;
}
}
</script>
</body>
</html>
Check your console. I bet the element.focus() is failing, because its a hidden input. Seems odd to focus on a hidden element.
Try using an <input type="submit"> rather than a <button type="submit">. I'm not sure if it'll make a difference, but it might be it.
Try this:
<html>
<body>
<script type="text/javascript">
window.onload = function()
{
var _form = document.getElementById("_form");
_form.addEventListener("submit", validate, false);
}
function validate(ev)
{
var element=document.getElementById('poa_esign_signature');
if (element.value=='')
{
alert('Signature may not be blank.');
element.focus();
ev.preventDefault();
}
}
</script>
<form action="www.google.it" method="post" name="form" id="_form">
Name: <input type="text" name="name" id="name">
<br><br>Signature: Hidden <input type="hidden" name="poa_esign_signature" id="poa_esign_signature">
<br><br><button type="submit">Sign</button>
</form>
</body>
</html>
Bye
onsubmit='return validate()'
should be
onsubmit='validate()'

getting "xxx is not a function" in JS

here's a little code I try to run on Firefox:
<html>
<head>
<title>Ex4: My Sequence Finder</title>
<script type="text/javascript">
function action() {
alert("action");
if (formValidation() == false)
return;
}
function searchInput() {
alert("searchInput");
return;
}
</script>
</head>
<body>
<font face="arial" size="5" color="blue">Input section</font> <br/>
<p>Query Sequence</p>
<form name="form">
<textarea id="input" rows="8" cols="60"></textarea><br/>
<textarea id="enhancers" rows="4" cols="30"></textarea><br/>
<textarea id="silencers" rows="4" cols="30"></textarea><br/>
<input type="button" value="button1" onclick="action()" />
<input type="button" value="button2" onclick="searchInput()" />
<div id="results"></div>
</form>
</body>
</html>
As you can see one of the button calls searchInput() and that works fine, the other
is supposed to call action(), but I get "action() is not a function". Btw they both just call alert() at this point, so I know it got in the function.
I have no idea as to why this happens, any help would be great.
Thanks!
Form elements have an action attribute (specifying the URI that should process the form data).
This attribute name "overrides" the javascript function name, causing the error you see.
Rename your function to something else and it will work.
You can solve this by using
var function1 =new function(){
var action=new function() {
alert("action");
if (formValidation() == false)
return;
}
}
<input type="button" value="button1" onclick="function1.action()" />
action calls formValidation which doesn't seem to be a function. Maybe the parser took this error and chose not te register action as a function because of it.

Categories