How to prevent empty input in text input form? - javascript

Here is my HTML -
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> My Shopping List</title>
<link rel="stylesheet" type="text/css" href="shoppinglist.css">
<link href='http://fonts.googleapis.com/css?family=Quicksand:300,400|Advent+Pro:300' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="shoppinglist.js"></script>
</head>
<body>
<div class="container">
<p id="shoppinglist"> My Shopping List App</p>
<input type="text" name="user" class="entertext">
<input type="button" value="Enter" class="returnkey">
<br>
<br>
<ol></ol>
</div>
</body>
</html>
Here is my JavaScript -
$(document).ready(function () {
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$("input[type='text']").keyup(function(event) {
if(event.keyCode == 13) {
$("input[type='button']").click();
}
});
$("ol").on("click", "input[type='checkbox']", function() {
$(this).parent().remove();
});
});
How do I create JavaScript for someone whose entering empty? So something to prevent them from empty text input?

You can check if the value of the text input is equal to a blank string:
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
//start new code
if ($.trim(item) === '') {
alert("Please Enter Something!");
return false;
}
//end new code
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$.trim() removes any extra white-space, to make sure the input doesn't just have white-space as a value.

Something like this?
$('.returnkey').on('click', function() {
var string = $.trim($('.entertext').val());
if (string == '') {
alert('Field is empty');
return false;
}
}

Related

Getting text of an element using text method and then checking condition but not getting appropriate output

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Assignment Q1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="style/style1.css" type="text/css" rel="stylesheet">
<script>
$(document).ready(function() {
$('button').click(function() {
var text = $(this).text();
console.log(text);
if (text == 'night') {
$('body').css('background-color', 'black');
$(this).text('day');
console.log(text);
} else {
$('body').css('background-color', 'white');
$(this).text('night');
console.log(text);
}
});
});
</script>
</head>
<body>
<button>
night
</button>
</body>
</html>
The thing that is happening over here is that when I am clicking on the button for the first time nothing is working ,but from the second click on wards the code is working as expected.
I have also checked what text method is getting for the first time
output:
night
night
and after the second click text method is getting
output:
night
night
day
day
Not able to understand what is happening over here and how text method output is changing by itself?
The problem is that the button looks like this in the HTML:
<button>
night
</button>
The whitespace is important - when you call .text on the button, you get all the text content of the button, including the whitespace.
Either don't use any whitespace initially:
<button>night</button>
Or call .trim() on the resulting text:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Assignment Q1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="style/style1.css" type="text/css" rel="stylesheet">
<script>
$(document).ready(function() {
$('button').click(function() {
var text = $(this).text();
console.log(text);
if (text.trim() == 'night') {
$('body').css('background-color', 'black');
$(this).text('day');
console.log(text);
} else {
$('body').css('background-color', 'white');
$(this).text('night');
console.log(text);
}
});
});
</script>
</head>
<body>
<button>
night
</button>
</body>
</html>
The issue is because the text() you receive from the method call has whitespace around it so it doesn't match the 'night' string you're comparing to.
To fix this, use trim() to remove that whitespace:
$(function() {
$('button').click(function() {
var text = $(this).text().trim();
if (text == 'night') {
$('body').css('background-color', 'black');
$(this).text('day');
} else {
$('body').css('background-color', 'white');
$(this).text('night');
}
console.log(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
night
</button>
Also note that you can improve the logic by using classes to set the styling and then toggleClass():
$(function() {
$('button').click(function() {
$('body').toggleClass('day night');
$(this).text(function(i, t) {
return t.trim() == 'night' ? 'day' : 'night';
});
});
});
.night { background-color: #000; }
.day { background-color: #FFF; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="day">
<button>
night
</button>
</body>

How do I remove a appended element with jQuery?

In jQuery I want to be able to add and remove an element. I got the code for appending an element. Now I want to remove that same element when I click on it.
What is the best way to make this so called ToDo list in jQuery?
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
$("#toDoList").append("<p>" + newToDo + "</p>");
$("#newToDo").val(" ");
}
});
});
<h1>Todo list</h1>
<form name="form" action="#">
<input id="newToDo" type="text" name="in">
<button id="add">Add!</button>
</form>
<div id="toDoList"></div>
You should use event delegation to attach event to dynamically created elements like :
$("#toDoList").on('click', 'p', function() {
$(this).remove();
});
NOTE : Any button tag inside a form will be considered as submit button so it will refresh you page, to avoid that you should add type="button" to your button, like :
<button type="button" id="add">Add!</button>
Hope this helps.
$(document).ready(function() {
$("#add").click(function() {
var newToDo = $("#newToDo").val();
if (newToDo.length > 0) {
$("#toDoList").append("<p>" + newToDo + "</p>");
$("#newToDo").val(" ");
}
});
$("#toDoList").on('click', 'p', function() {
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Todo list</h1>
<form name="form" action="#">
<input id="newToDo" type="text" name="in">
<button type="button" id="add">Add!</button>
</form>
<div id="toDoList"></div>
You can simply store the element in a variable:
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
var anotherToDo = $("<p>" + newToDo + "</p>");
$("#toDoList").append(anotherToDo);
$("#newToDo").val(" ");
// later when you want to delete it
anotherToDo.remove();
}
});
});
Or give it an ID and then remove it using that:
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
var anotherToDo = $("<p>" + newToDo + "</p>").attr('id', '#someid');
$("#toDoList").append(anotherToDo);
$("#newToDo").val(" ");
// later when you want to delete it
$('#someid').remove();
}
});
});
Looks like it's already been answered for you, but here's an easy way to do what you want in jQuery:
// external.js
$(function(){
var todo = $('#todo');
function todos(){
$('#todos>li').click(function(){
todo.val($(this).text());
});
}
function remove(){
$('#todos>li').remove(":contains('"+todo.val()+"')");
}
function add(){
var tv = $.trim($('#todo').val());
if(tv !== ''){
remove(); $('#todos').append('<li>'+tv+'</li>'); todos(); todo.val('');
}
}
todo.focus(function(){
todo.val('');
});
$('#frm').submit(function(e){
add(); e.preventDefault();
});
$('#add').click(add);
$('#rmv').click(function(){
remove(); todos();
});
});
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:940px; padding:20px; margin:0 auto;
}
label{
margin-right:4px;
}
#todos>li{
cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Add Remove to List - jQuery</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='frm' name='frm'>
<label for='todo'>New To Do</label><input id='todo' name='todo' type='text' /><input id='add' name='add' type='button' value='add' /><input id='rmv' name='rmv' type='button' value='remove' />
<ol id='todos'></ol>
</form>
</div>
</body>
</html>
It the New To Do input (without the quotes, of course): Type "Go to the Store". Hit Enter. Type "Do my Hair". Hit Enter. Type "Go on a Bike Ride". Hit Enter. Click on the list now where you want to remove then press the remove button. If it was an accident, you can press add again, but focusing on the input clears the text, for your next input, with this design. It's also form ready for database implementation.

Detect character in div and remove it Javascript or jQuery

I have this div:
<h1>$340</h1>
I need to detect if inside of this div there is a dollar symbol,
If so - remove it
I'll explain again:
I have got this code so far so I manage to detect if the symbol is in the div, but I can't figure how to remove it and update the DOM?
var sign = $('h1').text();
if (sign.indexOf("$") >= 0) {
//remove the sign
}
This is quite easy using a simple regex
var div = $('your selector here');
div.html(div.html().replace(/\$/g, ''));
That's what I have meant, without the If condition:
$('h1').text( $('h1').text().replace("$", ''));
Something like this should work:
$("h1").each(function() {
var $el = $(this);
var text = $el.text().replace("$", "");
$el.text(text);
});
Try like this
var price = $("h1").html().replace(/[^\d\.]/g, '');
console.log(price);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$( document ).ready(function() {
var val=$('#demo').html().replace('$','');
$( "div" ).replaceWith( val );
});
</script>
</head>
<body>
<h1 id='demo'>$540</h1>
</body>
</html>
Jquery can select based on contents. See https://api.jquery.com/contains-selector/.
What you need to do is:
$( "div:contains('$')" ).remove();
$(function() {
$("#button").click(function() {
var input = $("#input").val();
input = input.replace('$', '');
$("#input").val(input);
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<input type="text" id="input" placeholder="type here..." />
<button id="button">Remove</button>
</body>
</html>
This is the JQuery approach, I used replace on click on button to remove $ from input.
function HasDollar() {
if($("h1").html().indexOf("$") != -1)
return true;
else
return false;
}
try this.

Need help for a getInput function

I've been having trouble with my javascript code.
<!DOCTYPE html>
<html>
<head>
<title>js-game</title>
<script src="script.js" type="text/javascript"></script>
<script src="story.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="game">
<ul id="output">
<li onclick="main()">Click here to start!</li>
</ul>
<input autofocus id="inputLine" type="text">
<p onclick="" id="enterInput">ENTER</p>
</div>
</body>
</html>
// Variables
var log="<li>Hello</li>";
var lastVar="";
// Functions
function getInput() {
document.getElementById("enterInput").addEventListener("click", function() {
return document.getElementById("inputLine").value;
document.getElementById("inputline").value="";
});
}
function output(output) {
log=log + "<li>" + output + "</li>";
document.getElementById("output").innerHTML=log;
}
function main() {
output("What's your name?");
alert(getInput());
}
As you can probably see I want to get input from a <input type="text"> with the id of inputLine. And a button with the id of enterInput.
But all I get back is undefined, and I've been working on this for a long time, so I'm getting frustrated.
Sorry for bad english.
Try doing it like so:
document.getElementById("enterInput").addEventListener("click", getInput );
function getInput() {
var val = document.getElementById("inputLine").value;
//do something with val
document.getElementById("inputLine").value="";
return val;
}
See this demo
Or to fetch it as a variable with getInput():
document.getElementById("enterInput").addEventListener("click", function(event){
var val = getInput();
alert(val);
});
function getInput() {
var val = document.getElementById("inputLine").value;
document.getElementById("inputLine").value="";
return val;
}
See this demo

fail to focus on page load

I can focus on the text input when I click the button but it doesn't focus on the text input when page first loaded even though I am using the same function. How can I focus at the input textfield once the page is loaded ?
http://codepen.io/anon/pen/derwi
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
function generate_question (){
var num1 = Math.floor(Math.random()*10),
num2 = Math.floor(Math.random()*10);
$('.result').hide();
$('.left').html(num1 + ' x ' + num2 + ' = <input type="text" size="3" class="answer">');
$('.answer').val('');
$('.answer').focus();
$('.answer').keypress(function(e){
if (e.which == 13) {
if ($(this).val() == num1 * num2) {
$('.result').html('Very Good!');
$('.result').show();
} else {
$('.result').html('Try Again');
$('.result').show();
}
}
})
}
$(document).ready(function(){
generate_question();
$('#again').click(function(){
generate_question();
});
$('#again').keypress(function(e){
if (e.which == 32){
generate_question();
}
});
})
</script>
</head>
<body>
<div class="content">
<div class="left"></div>
<div class="result"></div>
</div>
<div class="instruction">
Hit enter to check your answer.
<button type='button' id='again' style='margin-top: 10px;'>Do another one?</button>
</div>
</body>
</html>
Try $('.answer').focus(); in your ready function
$( document ).ready(function(){
$('.answer').focus();
});
DEMO: http://plnkr.co/edit/EX0xS9d8o3TqUqiEOAL5?p=preview

Categories