i am newbie. i want to validate my dynamically created text fields.
unfortunately i couldnt use <form> as i am using it in django. i could have used jquery validator if i had used <form>. now how do i validate these fields.
my simple code looks like
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$(".errMsg").hide();
var data = "";
for(var i =0;i<5;i++){
data = data + "Name : <input type='text' id='name"+i+"' class='required' > Age : <input type='text' id='age"+i+"' class='required' ><br>";
}
$("#mytable").html(data);
$("#clickbtn").click(function(){
for(var j=0;j<5;j++){
if($("#name"+j).val() == ""){
alert(j);
$("#name"+j).focus();
$(".errMsg").show();
}
if($("#age"+j).val() == ""){
$("#age"+j).focus();
$(".errMsg").show();
}
if(isNan($("#age"+j).val())){
$("#age"+j).focus();
$(".errMsg1").show();
}
}
});
});
</script>
</head>
<body>
<h1>Register here</h1>
<div id="mytable"></div>
<button id="clickbtn">click</button>
<div class="errMsg">This is required</div>
<div class="errMsg">Invalid age</div>
</body>
</html>
i want to validate all the fields and if field is empty i want to highlight everything and display error msg under that texbox.
in this code i could focus only last textbox. how to do it for all.
Please help me.. thank you
isNan is typo error. It should be isNaN.
And please return false in every condition so the script execution will stop there and that particular element will focused.
Please check below snippet for more understanding.
$(document).ready(function(){
$(".errMsg").hide();
var data = "";
for(var i =0;i<5;i++){
data = data + "Name : <input type='text' id='name"+i+"' class='required' > Age : <input type='text' id='age"+i+"' class='required' ><br>";
}
$("#mytable").html(data);
$("#clickbtn").on('click', function(){
for(var j=0;j<5;j++){
if($("#name"+j).val() == ""){
$("#name"+j).focus();
$(".errMsg").show();
return false;
}
if($("#age"+j).val() == ""){
$("#age"+j).focus();
$(".errMsg").show();
return false;
}
if(isNaN($("#age"+j).val())){
$("#age"+j).focus();
$(".errMsg1").show();
return false;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytable"></div>
<button id="clickbtn">click</button>
<div class="errMsg">This is required</div>
<div class="errMsg">Invalid age</div>
Try this,
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$(".errMsg").hide();
var data = "";
for(var i =0;i<5;i++){
data = data + "Name : <input type='text' id='name"+i+"' class='required' > Age : <input type='text' id='age"+i+"' class='required' ><br>";
}
$("#mytable").html(data);
$("#clickbtn").on('click', function(){
for(var j=0;j<5;j++){
if($("#name"+j).val() == ""){
alert(j);
$("#name"+j).focus();
$(".errMsg").show();
}
if($("#age"+j).val() == ""){
$("#age"+j).focus();
$(".errMsg").show();
}
if(isNan($("#age"+j).val())){
$("#age"+j).focus();
$(".errMsg1").show();
}
}
});
});
</script>
</head>
<body>
<h1>Register here</h1>
<div id="mytable"></div>
<button id="clickbtn">click</button>
<div class="errMsg">This is required</div>
<div class="errMsg">Invalid age</div>
</body>
</html>
Try below code this will may be help you out
$(document).on('click', '#clickbtn',function (){
//Write your code
})
Related
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a it displays for a split second and goes away. Please help
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>game</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
/*var input;
var room;
function submitFunction() {
alert("hello")
}
*/
</script>
<script type="text/javascript">
var input;
var room;
room = "Main Enterence"
$(document).ready(function () {
$("#mainForm").submit(function() {
input = document.getElementById("textInput").value;
if (input == "east") {
if (room == "Main Enterence") {
room = "Bedroom"
enterBedroom();
}
}
if (input == "west") {
}
if (input == "north") {
}
if (input == "south") {
}
})
})
function enterBedroom() {
$( "#consoleOutput" ).append( "<p>Test</p>" );
}
</script>
<div id="consoleOutput">
<p id="welcomeText"></p>
</div>
<form onsubmit="submitFunction()" id="mainForm">
<input type="text" id="textInput">
<input type="submit" name="sumbit">
</form>
</body>
</html>
Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a it displays for a split second and goes away. Please help
This happens, because the page is refreshed - you submit form. You have to add first parametr to submit event and use preventDefault() function on it
$("#mainForm").submit(function(event) {
event.preventDefault();
});
Error:
There are two functions invoked during submit of the form...
When you need page not to refresh then don't use submit without preventing the default event...
Solution:
var input;
var room;
room = "Main Enterence";
$("#mainForm").click(function() {
input = document.getElementById("textInput").value;
if (input == "east") {
if (room == "Main Enterence") {
room = "Bedroom"
$("#consoleOutput").append( "<p>Test</p>" );
}
}
if (input == "west") {
}
if (input == "north") {
}
if (input == "south") {
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="consoleOutput">
<p id="welcomeText"></p>
</div>
<form id="mainForm">
<input type="text" id="textInput">
<input type="button" value="submit" name="submit">
</form>
It clears because you are using submit which will cause the page to reload/refresh. Change that to click
your html button:
<input type="button" name="sumbit" id="submit" value="submit">
your js:
$(document).ready(function () {
$("#submit").click(function() {
.
.
.
I hope I'm not repeating a question but I've searched around and couldnt find help so I thought I should ask directly, I'm still a beginner and this is an assignment for my class so please be as thorough as possible
I'm trying to create a form where as the user clicks on another field, it checks if the input he put in the first one is as required by the website, without having to click enter or a submit button.
this is the HTML file.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function(){
$("div.ID").focusin(function(){
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").focusout(function(){
$(this).css("background-color", "#FFFFFF");
userid_validation(userid,5,12);
});
});
</script>
</head>
<body>
<div class="ID" >
User ID: <input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password: <input type="text" name="psw" size="12" />
</div>
</body>
</html>
and this is the JS file
function userid_validation(userid,mx,my)
{
var uid_len = userid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
//uid.focus();
return false;
}
return true;
}
I'm most probably doing something completely wrong but I don't know what. thanks in advance !
You need to apply focusin and foucsout on input elements. Currently you have applied it on div. Also you have code error on calling following function,
userid_validation(userid, 5, 12); // userid not defined.
Please check if this works.
function userid_validation(userid, min, max) {
var uid_len = userid.length;
if (uid_len == 0 || uid_len > max || uid_len < min) {
alert("User Id should not be empty / length be between " + min+ " to " + max);
//uid.focus();
return false;
}
return true;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function() {
$("div.ID").find('input').focusin(function() {
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").find('input').focusout(function() {
$(this).css("background-color", "#FFFFFF");
userid_validation($(this).val(), 5, 12);
});
});
</script>
</head>
<body>
<div class="ID">
User ID:
<input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password:
<input type="text" name="psw" size="12" />
</div>
</body>
</html>
I'm trying to clear a text field and it does not work. I get the alert but it does not clear it. What am I doing wrong?
This is a generic function that can be call on any text field.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function clearThis(target)
{
alert('before...' + target.value);
if ($(target).value == "Search ")
{
$(target).value = "set to something else";
$(target).style.color = '#000000';
$(target).style.fontStyle = 'italic';
}
else
{
$(target).value = "";
}
alert('after...' + target.value);
}
</script>
<title>My page</title>
</head>
<body>
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)"/>
</div>
</body>
</html>
Your use of $ would suggest that you are using JQuery but you arent including the library in your page.
If you are using jQuery, use the correct jQuery way to get and set values (.val()) and styles(.css()). And of course, include the jQuery library...
function clearThis(target) {
alert('before...' + target.value);
if ($(target).val() == "Search ") {
$(target).val('set to something else');
$(target).css({'color':'#000000', 'font-style': 'italic'})
} else {
$(target).val('');
}
alert('after...' + target.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)" />
</div>
If, in fact, you aren't using jQuery, you need to omit the $() syntax from your code..
function clearThis(target) {
alert('before...' + target.value);
if (target.value == "Search ") {
target.value = "set to something else";
target.style.color = '#000000';
target.style.fontStyle = 'italic';
} else {
target.value = "";
}
alert('after...' + target.value);
}
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)" />
</div>
Please check below code
function clearThis(target)
{
// alert('before...' + target.value);
//alert(target);
if (target.value == "Search ")
{
target.value = "set to something else";
target.style.color = '#000000';
target.style.fontStyle = 'italic';
}
else
{
target.value = "";
}
//alert('after...' + target.value);
}
HTML code
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)"/>
</div>
Two thing you need to update in your code first one is you should add jquery.js file and second one is if you want change value go through id or class.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
function clearThis(target)
{
if (target.value == "Search ")
{
$("#username").val("set to something else");
}
else
{
$("#username").val('');
}
alert('after...' + target.value);
}
</script>
<title>My page</title>
</head>
<body>
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)"/>
</div>
</body>
</html>
You are doing it wrong.
$(target) is jquery object and not js so value could not be accessible
You can do like this(js) :
target.value
or
Like this (jquery)
$(target).val()
To Clear the textbox value using JQuery, Use following Line:
$(control).val("");
This is my simple code which I have been working to just show valid or invalid if the wrong text is inserted but the problem I’m having is that when I hit enter the valid and invalid flashes without staying on screen.
Here is my Fiddle
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
}
}
<form>
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my" onchange="validate()"></input>
<label id="Result"></label>
</form>
What is the mistake i am doing and How can i fix this ?
The problem is that you have your code inside tag. You need to prevent form submission if you want to stay on the page.
I have not included CSS here!!
<div class="container">
<div id="nav">
<div id="search">
<form id="form1">
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my"></input>
<label id="Result"></label>
</form>
</div>
</div>
</div>
$(document).ready(function(){
$("#form1").submit(function(event){
if ( !validate()) {
alert("Error");
event.preventDefault();
return false;
}
});
});
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
return true;
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
return false;
}
}
Here is a fiddle. Hope it will help.
I need to add product info from inputs to table by using jQuery library. I am trying for quite some time now, but I don't get anywhere. First I need to enter data to inputs, select appropriate radio button and than validate input fields. If there are no errors, product info should be added to table. I tried with the following code: jsFiddle
Nothing works as intended tho. What am I doing wrong?
JS code:
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function () {
//Check if any of requested inputs is empty
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").val('Missing product name');
break;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").val('Missing price');
break;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
//Check radio buttons and assign values
if ($('input[value = "true"]'.is(':checked')) {
onStack = "Product available";
} else if ('input[value = "false"]'.is(':checked') {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>$productName</td><td>$price</td><td>$onStack</td></tr>");
});
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<body>
<form method="" action="">
<input type="text" id="name" placeholder="Product name" />
<br />
<input type="text" id="price" placeholder="Price" />
<br/>
<input type="radio" name="stack" value="true">Product available
<br />
<input type="radio" name="stack" value="false">Product not available
<br />
<input type="submit" value="Submit">
</form>
<div id="errors"></div>
<br />
<table border="1">
<tr>
<th>Product name</th>
<th>Price</th>
<th>Stack</th>
</tr>
</table>
<div id="sumOnStack">Sum of available products</div>
<div id="SumNotOnStack">Sum of unavailable products</div>
<input type="button" id="resetForm" value="Reset form" />
<br />
</body>
</html>
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function ( e) {
//Check if any of requested inputs is empty
$("#errors").html('');
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").html('Missing product name');
return false;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").html('Missing price');
return false;
} else if($('input[name="stack"]:checked').length == 0) {
$("#errors").html('Missing product availibility');
return false;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
var stack = $('input[name="stack"]:checked');
console.log( $(stack).val() );
//Check radio buttons and assign values
if ($(stack).val() == 'true') {
onStack = "Product available";
} else {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>"+productName+"</td><td>"+ price +"</td><td>"+ onStack +"</td></tr>");
return false;
});
});
Please try this. Hope above code will help u.