I have here the complete code of what I have applied and tried. Using the JS below, I got the display of the ordered list wrongly. It must be in 1,2,3 ... (so on and forth). For this, it sticked to 1.,1.,1. .... Another is that, using the JS below, how to customize it that I will get dynamic input fields? Because what if I'll input 5? The result of the fields must be 5 in number also. But what happened, 5 fields are added/appended to the current number of fields (sample, I inputted 3 before and 3 fields displayed so when 5 is inputted, there are 8 fileds in all). What I want is the exact number of fields from the number being inputted. (not that good at JS but I am badly wanting to learn its nature).
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("ul").each(function() {
$(this).find("li").each(function(count) {
$(this)
.css("list-style-type", "none")
.prepend("<div class='listnumber'>" + (count + 1) + ".</div>");
});
});
})
</script>
<script type="text/javascript">
$(document).ready(function() {
$('[name="cand_no"]').on('change', function() {
if (this.value != '') {
var val = parseInt(this.value, 10);
for (var i = 0; i < val; i++) {
var $cloned = $('.template tbody').clone();
$('#studentTable tbody').append($cloned.html());
}
});
})
</script>
</head>
<body>
<p>
<label><strong>No.: </strong></label>
<label><input name="cand_no" type="number" placeholder="Enter no. of fields." /></label>
<div class="clear"></div>
</p>
<div class="cand_fields">
<table id="studentTable" width="630" border="0">
<tr>
<td>Name</td>
</tr>
<tr>
<td><input name="cand_name" type="text" placeholder="Name" required="required" /></td>
</tr>
</table>
</div>
<div class="template" style="display: none">
<table>
<tr >
<td><ul><li><input name="cand_name" type="text" placeholder="Name" required="required" /></li></ul></td>
</tr>
</table>
</div>
</body>
</html>
Thanks a million..
Try
$(document).ready(function () {
$(".template ul li").css("list-style-type", "none").prepend("<div class='listnumber'></div>");
})
$(document).ready(function () {
var $tmpl = $('.template tbody'),
$target = $('#studentTable tbody');
$('[name="cand_no"]').on('change', function () {
if (this.value != '') {
var val = (parseInt(this.value, 10) || 0) + 2;
var len = $target.children().length;
if (val < len) {
$target.children().slice(val).remove();
} else {
for (var i = len; i < val; i++) {
$($tmpl.html()).appendTo($target).find('.listnumber').text(i - 1);
}
}
}
});
})
Demo: Fiddle
Related
I have a cart options that has a increment the product option . The option has an text input and plus / minus options
Markup
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
there is about 5 to 6 types of input like above
And the JavaScript code:
var minus = $(".quantity-mius");
var plus = $(".quantity-plus");
var itemValue = $(".cart-main-product-qty");
$(".cart-item-qty").each(function(index) {
$(this).find(plus).on('click', function(e){
e.preventDefault();
increment();
});
$(this).find(minus).on('click', function(e){
e.preventDefault();
decrement();
});
});
function increment(){
newValue = itemValue.val();
newValue++;
itemValue.val(newValue);
};
function decrement(){
newValue = itemValue.val();
newValue--;
if(newValue < 1){
itemValue.val(0);
}else{
itemValue.val(newValue);
}
};
When i press the plus button the input value increases in all the inputs and when minus then all decreases.
Onclicking on those icon simply call the function and find its sibling with that class and calculate the value. Try with -
$(".quantity-plus").on('click', function(e){
e.preventDefault();
increment($(this));
});
$(".quantity-mius").on('click', function(e){
e.preventDefault();
decrement($(this));
});
function increment($this){
itemValue = $this.siblings('.cart-main-product-qty');
newValue = itemValue.val();
newValue++;
itemValue.val(newValue);
};
function decrement(){
itemValue = $this.siblings('.cart-main-product-qty');
newValue = itemValue.val();
newValue--;
if(newValue < 1){
itemValue.val(0);
}else{
itemValue.val(newValue);
}
};
Why don't you try like this
$(".quantity-plus").on('click', function(e){
e.preventDefault();
increment();
});
$(".quantity-mius").on('click', function(e){
e.preventDefault();
decrement();
});
It will work
In increment and decrement, you're selecting all the input elements at once (the selection is happening outside of the each call at the top of the script).
You are therefore trying to call val() and val(n) on the entire collection of inputs, in affect trying to increment and decrement all of them at once, except in reality val() (with no arguments) doesn't work like that (it should never be used with a collection on inputs, but instead with only one input at a time).
You should select the input using find within the each like you do with the + and - buttons, and pass the found input to increment and decrement as parameters to those functions, or you should do the increment or decrements inline in the each block itself instead of in separate functions.
this works : manage click event before selecting each input
<script type="text/javascript">
var itemValue = $(".cart-main-product-qty");
$( ".quantity-mius" ).click(function(e) {
e.preventDefault();
$( ".cart-main-product-qty" ).each(function( index, element ) {
console.log('decrement');
decrement();
})
});
$( ".quantity-plus" ).click(function(e) {
e.preventDefault();
$( ".cart-main-product-qty" ).each(function( index, element ) {
console.log('increment');
increment();
})
});
function increment(){
newValue = itemValue.val();
newValue++;
itemValue.val(newValue);
};
function decrement(){
newValue = itemValue.val();
newValue--;
if(newValue < 1){
itemValue.val(0);
}else{
itemValue.val(newValue);
}
};
</script>
You have to target only the input element related to clicked plus/minus button so
$(".cart-item-qty .quantity-mius").click(function(index) {
$(this).closest('td').find('.cart-main-product-qty').val(function(i, val) {
var value = +val || 0;
return value > 1 ? value - 1 : 0
})
});
$(".cart-item-qty .quantity-plus").click(function(index) {
$(this).closest('td').find('.cart-main-product-qty').val(function(i, val) {
return +val + 1 || 1;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
</table>
This works:
$(document).ready(function(){
var minus = $(".quantity-mius");
var plus = $(".quantity-plus");
$(plus).on('click', function(e){
e.preventDefault();
$(this).parent().find("input.cart-main-product-qty").val(parseInt($(this).parent().find("input.cart-main-product-qty").val())+1);
});
$(minus).on('click', function(e){
e.preventDefault();
$(this).parent().find("input.cart-main-product-qty").val(parseInt($(this).parent().find("input.cart-main-product-qty").val())-1);
});
});
FIDDLE
You said you had more that one of these on the page. Is that because there are multiple items in the cart? I added a data- attribute to your container element. Just a thought. It may help differentiate them.
<td class="cart-item-qty" data-cartItemId="3">
<div class="quantity-minus">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
You are casting too wide a net in your increment and decrement functions. You need to find itemValue that same way you are finding plus and minus within $(this) in your foreach. You need to pass along a single element.
If you check the docs on jQuery, there is a prescribed way to pass variables to the eventhandler that is called by on. jQuery API docs
Try this:
var minus = $(".quantity-minus");
var plus = $(".quantity-plus");
var itemValue = $(".cart-main-product-qty");
$(".cart-item-qty").each(function(index) {
// need to use THIS this in a nested context.
var that = $(this);
$(this).find(plus).on('click', { target: that.find(itemValue) }, increment);
$(this).find(minus).on('click', { target: that.find(itemValue) }, decrement);
});
function increment(event) {
event.preventDefault();
var el = event.data.target;
newValue = el.val();
newValue++;
el.val(newValue);
};
function decrement(event) {
event.preventDefault();
var el = event.data.target;
newValue = el.val();
newValue--;
if(newValue < 1){
el.val(0);
}else{
el.val(newValue);
}
};
Hope this helps!
Your code looks almost right.
First change this code
var minus = ".quantity-mius";
var plus = ".quantity-plus";
var itemValue = ".cart-main-product-qty";
as you use find you don't need the object.
Then the html is not complete, I used this code to make it working
<table>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1">
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" >
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
</table>
While the js is
var minus = ".quantity-mius";
var plus = ".quantity-plus";
var itemValue = ".cart-main-product-qty";
$(".cart-item-qty").each(function(index) {
var outer = $(this)
$(this).find(plus).on('click', function(e){
e.preventDefault();
increment(outer.find(itemValue));
});
$(this).find(minus).on('click', function(e){
e.preventDefault();
decrement(outer.find(itemValue));
});
});
function increment(item){
newValue = item.val();
newValue++;
item.val(newValue);
};
function decrement(item){
newValue = item.val();
newValue--;
if(newValue < 1){
item.val(0);
}else{
item.val(newValue);
}
};
Note that I added an argument to the functions increment and decrement because I guess you want to change just the relative input field
I have a user enter biograpgy in a text box html for that is
<p>Biography:
<input type="text" id="biography" name="biography" />
<span id="biographyInvalid" style="color:red; visibility:hidden"> Biography is Invalid </span>
</p>
for Javascript i have a checkme function that is called and i want to do a check inside of it
function checkme(){
var biography=document.getElementById('biography').value;
}
how can i count number of words, do i first convert it to string and then separate with spaces
<div>
<div id="count">145</div>
<div id="barbox"><div id="bar"></div></div>
</div>
<textarea id="contentbox"></textarea>
and js
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var box=$(this).val();
var main = box.length *100;
var value= (main / 145);
var count= 145 - box.length;
if(box.length <= 145)
{
$('#count').html(count);
$('#bar').animate(
{
"width": value+'%',
}, 1);
}
else
{
alert(' Full ');
}
return false;
});
});
</script>
$('#contentbox').keyup(function(){} - contentbox is the ID of the textbox.
Using $(this).val() getting the textbox value.
bar is the div ID of the count meter $('#bar').animate() increasing the width.
js:
$('#biography').keyup(function () {
var words = this.value.match(/\S+/g).length;
$('#count').html('Words Count:'+words);
});
HTML:
<div id="count"></div>
This gives you correct words count
This is working example
the HTML
<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4" onkeyup="countNoOfWords()" >This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input name="noofwords" type="text" value="" size="6" />
</form>
The JS function
<script type="text/javascript">
function countNoOfWords(){
document.myform.noofwords.value = document.myform.post_content.value.split(' ').length;
}
</script>
reference
$('input').keyup(function() {
var cs = this.value.match(/\S+/g).length;
$('#biography').text(cs);
});
Demo - http://jsfiddle.net/hNn5b/685/
I am new to UI design. I have created Captcha, Please anyone give me an idea to validate Captcha using JavaScript.Thanks in advance. I have added my code below.
Code for getting new Captcha:
<html>
<head>
<script language="javascript" type="text/javascript">
function getCaptcha() {
var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
var string_length = 5;
var captchastring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
captchastring += chars.substring(rnum,rnum+1);
}
document.getElementById("randomfield").innerHTML = captchastring;
}
</script>
<style>
HTML Code:
</head>
<body onload="getCaptcha();">
<form name="randform">
<table style="border:1px solid #ecece4">
<tr><td colspan="2" align="center"><strong>Contact Us Form</strong></td></tr>
<tr><td>Enter Captcha Code</td><td><input type="text" id="txtcode"/></td></tr>
<tr>
<td>
</td>
<td>
<div id="captcha">
<div id="captcha_gen">
<label align="center" id="randomfield"></label>
</div>
</div><input type="button" value="Refresh" onClick="getCaptcha();"/></td></tr>
<tr><td colspan="2" align="center"><input type="button" value="Submit"/></td></tr>
</table>
</form>
</body>
<html>
function validateCaptcha()
{
var chr = document.getElementById("tbxCaptcha").value;
var cap = document.getElementById("randomfield").innerHTML;
if (chr==cap)
{
return true;
}
else
{
alert ("Please enter valid verification code");
return false;
}
}
I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>
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.