generate n number of table rows depending on value of input jquery - javascript

<input type="number" id="nostorey" name="" class=' InputBox' />
<table id="floor">
<tr id="headtable">
<td>
<center>Floor Names</center>
</td>
<td>
<center>Floor wise Area</center>
</td>
</tr>
<tr>
<td>
<p>1st Floor</p>
</td>
<td>
<input type='text' id="firstfloor" name='' maxlength="10" value="" class=' InputBox' />
</td>
</tr>
<tr>
<td>
<p>2nd Floor</p>
</td>
<td>
<input type='text' id="secondfloor" name='' maxlength="10" value="" class=' InputBox' />
</td>
</tr>
<tr>
<td>
<p>3rd Floor</p>
</td>
<td>
<input type='text' id="thirdfloor" name='' maxlength="10" value="" class=' InputBox' />
</td>
</tr>
<tr>
<td>
<p>4th Floor</p>
</td>
<td>
<input type='text' id="fourthfloor" name='' maxlength="10" value="" class=' InputBox' />
</td>
</tr>
<tr>
<td>
<p>Total</p>
</td>
<td>
<input type='text' id="total" readonly name='' maxlength="10" value="" class=' InputBoxD' />
</td>
</tr>
</table>
$("#nostorey").bind('change', function() {
if ($.trim($(this).val()) < 5) {
if ($(this).val().match(/^\d*$/)) {
if ($(this).val() == 1) {
console.log("1");
console.log($(this).val());
$('#secondfloor').prop('disabled', true);
$('#thirdfloor').prop('disabled', true);
$('#fourthfloor').prop('disabled', true);
} else if ($(this).val() == 2) {
console.log("2");
console.log($(this).val());
$('#secondfloor').prop('disabled', false);
$('#thirdfloor').prop('disabled', true);
$('#fourthfloor').prop('disabled', true);
} else if ($(this).val() == 3) {
console.log("3");
console.log($(this).val());
$('#secondfloor').prop('disabled', false);
$('#thirdfloor').prop('disabled', false);
$('#fourthfloor').prop('disabled', true);
} else if ($(this).val() == 4) {
console.log("4");
console.log($(this).val());
$('#secondfloor').prop('disabled', false);
$('#thirdfloor').prop('disabled', false);
$('#fourthfloor').prop('disabled', false);
}
}
} else {
var newItemHTML = '<tr><td ><span>' + $(this).val() + 'th Floor</span></td><td><input type="text" name="" class="InputBox " id="floor' + $(this).val() + '"></td></tr>';
$("table#floor tr").last().before(newItemHTML);
}
});
This is my code to tell how many floor I have in my input text by default I have 4 floors. Onchange of onstorey input I want to add the remaining floors currently what i did is to set if else but this is not working the way i want it because this way if I reduce the number of floor it is not reducing the number of input to write the area. I want to ask idea on how to make this possible
Make it in a way that when the number in storey input is more than 4 it will add the remaining floors.
When the number is reduced the number of input in the table should also decrease, but not less than the default value which is 4
This is the Sample
UPDATED sample
here

see your updated fiddle: http://jsfiddle.net/fq42seff/3/
i first added the class="floor" to all your floor input boxes, to have a unique selector for these input boxes. the entry field for the amount of floors and the total field is excluded.
then i changed your js the following:
//created two functions addFloors() and removeFloors()
function addFloors(actual, target){
for(i = actual +1;i<=target;i++) //this loop creates the new floors
{
newItemHTML = '<tr><td ><p>' + i + 'th Floor</p></td><td><input type="text" name="" class="floor InputBox " id="floor' + i + '"></td></tr>';
//i also changed the html inside the first td from <span> to <p> to match your html markup
$("table#floor tr").last().before(newItemHTML);
}
}
function removeFloors(target){
if(target >= 4) //remove all floors except the base 4
{
$('.floor').slice(target).parent().parent().remove();
//since i select the .floor input box, i have to use the parent() function two times, to move the selector up to the <tr> element
}
}
next, we extend your change function:
$("#nostorey").bind('change', function() {
curVal = $.trim($(this).val()).match(/^\d*$/); //get the value from the first input box
curFloors = $('.floor').length; //get the current nbr of floors
if(curVal > curFloors) //if you want more floors, then currently available
{
addFloors(curFloors, curVal); //add floors
}else if(curVal < curFloors) //if you want less
{
removeFloors(curVal); //remnove them
}
last but not least, enable/disable the first 4 input boxes:
$('.floor').each(function(index){ //for each .floor input box
if(index >= curVal) //if it's index is greater then the needed floor count
{
$(this).prop('disabled', true); //disable it
}else
{
$(this).prop('disabled', false); //else enable it
}
});
the last part - the enabling/disabling could be splitted and extend the add/remove functions - this would make them get run only when needed. right now, it gets executed on every value change. but i guess, you can figure out the rest by yourself...

I added a grid of checkboxes depending on the number of floors also upon generating these checkboxes i put an attribute for each checkboxes depending on which row they are in. The span text or that row will be the value of the checkboxes for that row. With the help of
Guruprasad Rao
he came up with this fiddle
Fiddle
For code betterment feel free to update the fiddle to help others

Correct me if I am wrong. Here is my for loop.
else {
var floors = parseInt($("#nostorey").val()-4);
$("tr[id^=floor]").hide();
if(floors != NaN){
for(i=5;i<floors+5 ;i++){
var newItemHTML = '<tr id="floor'+i+'"><td ><span>' + i + 'th Floor</span></td><td><input type="text" name="" class="InputBox floor"' + i + '"></td></tr>';
$("table#floor tr").last().before(newItemHTML);
}
}

Related

Add Multiple Levels of Input Fields

I have a product page that will input a cost, quantity and spit out the cost after taking the product of the 2.
I have figured it out here http://jsfiddle.net/61tch8md/ for the most part (I believe) but the issue I have is that the user can add multiple lines and each line needs to only add the quantity and cost of the fields on that row. Right now when I add additional rows, the first line will control the price for all the lines.
HTML
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description 1" name="product-1-description" /></td>
<td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity 1" name="product-1-quantity" /></td>
<td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price 1" name="product-1-price"/></td>
<td><span class="wei-price-total"></span></td>
<td> </td>
</tr>
</tbody>
</table>
<div class="wei-add-service">Add Item</div>
JavaScript / Jquery
jQuery( "tr" )
.keyup(function() {
var value = jQuery( ".unit-price" ).val();
var value2 = jQuery( ".quantity" ).val();
var total = value * value2;
jQuery( ".wei-price-total" ).text( total );
})
.keyup()
var counter = 2;
jQuery('a.wei-add-service-button').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description" name="product-' +
counter + '-description" /></td><td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity" name="product-' +
counter + '-quantity" /></td><td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price" name="product-' +
counter + '-price"/></td><td><span class="wei-price-total">$49.99</span></td><td>remove</td></tr>');
jQuery('table.order-details').append(newRow);
});
jQuery('table.order-details').on('click','tr a',function(e){
e.preventDefault();
jQuery(this).parents('tr').remove();
});
Thanks in advance.
Change your code so it selects the inputs in the row that the keyup happened on.
jQuery('table.order-details').on("keyup", "tr", function() {
var row = jQuery(this);
var value = jQuery( ".unit-price", row ).val();
var value2 = jQuery( ".quantity", row ).val();
var total = value * value2;
jQuery( ".wei-price-total", row ).text( total );
});

JQuery sum using checkbox value and textbox value

How could I get the Final Total based on the sum of a checkbox value and the contents of a textbox?
JSFiddle example
My HTML:
<table border="1">
<tr><td>10<input type="checkbox" class="tot_amount" value="10"></td><td>10<input id="os1" type="text"></td></tr>
<tr><td>20<input type="checkbox" class="tot_amount" value="20"></td><td>20<input id="os2" type="text" ></td></tr>
<tr><td>Total<input type="text" id="total1" readonly></td><td>Total2<input id="total2" type="text" readonly></td></tr>
</table>
Final Total<input type="text" id="final" readonly >
And Javascript:
$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#total1').val('');
}
else {
$('#total1').val(total);
}
});
$('#os1, #os2').on('input',function(){
var os1= parseFloat($('#os1').val()) || 0;
var os2= parseFloat($('#os2').val()) || 0;
$('#total2').val(os1 + os2);
});
Just bind a focus event and do it -
$('#final').bind('focus',function(){
$(this).val(parseInt($('#total1').val())+parseInt($('#total2').val()));
});
LIVE http://jsfiddle.net/mailmerohit5/h43te3z6/

Display fields when user selects particular value from combo box - Validation logic issue

I have a combo box, and there are 2 values to be selected from it. either Male or Female. When user selects Male then another 2 textboxes gets displayed. Those 2 text box cann't be empty (as they are being validated).
The problem : When the user selects Female, the 2 textboxes discussed above is hidden, and I am not allowed to navigate to the next screen without filling some values to those 2 fields (because its being validated). How can i solve this?
My COde
<table>
<tr>
<td align="left">
<select id="gender" name="gender" onchange='genderfind(this.value);'>
<option value="female">female</option>
<option value="male">Male</option>
</select>
</td>
<td id="gb" style="display:none;"> <td>
<input type="text" name="name" /></td>
<td align="left"><span id="msg_name"></span> </td>
<td>
<input type="text" name="lastname" /></td>
<td align="left"><span id="msg_lastname"></span> </td>
</td>
</tr>
</table>
</body>
JQUERY
function validateStep() {
var isValid = true;
var un = $('#name').val();
if (!un && un.length <= 0) {
isValid = false;
$('#msg_name').html('first name missing').show();
} else {
$('#msg_name').html('').hide();
}
// validate password
var l = $('#lastname').val();
if (!l && l.length <= 0) {
isValid = false;
$('#msg_lastname').html('last name missing').show();
} else {
$('#msg_lastname').html('').hide();
}
return isValid;
}
///
<script>
function genderfind(val) {
//alert(element);
if (val == 'male' ) {
document.getElementById('gb').style.display = 'block';
} else {
document.getElementById('gb').style.display = 'none';
}
}
</script>
After isValid = true; wrap the rest of the code just before return isValid; in an if loop if(document.getElementById('gb').style.display == "block") { /*[ your validation]*/
}
And your HTML code is incorrect. You cannot directly have a td inside another td. Its good practice if you put span or div or p or anyother element instead of the td's inside <td id="gb" style="display:none;">.
call validateStep() function only when the two fields are visible.
if($('#msg_name').is(":visible")){
validateStep ();
})

Form submission cancel using javascript not working

OBJECTIVE:
I have made a form containing 3 fields, I want that If there's even a single empty field left in form
the form , it is recognised and an error message(for each empty field) is printed (not alerted), and form submission is cancelled. The error msg is initially hidden and it should be made visible only when a field is left empty.
PROBLEM:
the code to stop submission is not working.
Please post any error. It works if use only alert(), and remove the code to show and delete hidden validaeFormOnSubmit() and validateEmpty().
FORM:
<form action="start.php" method="post" onsubmit="return validateFormOnSubmit(this)" >
<table>
<tbody>
<tr>
<td><label for="fname">Team Name:</label><br></td>
<td><input name="fname" type="text" autocomplete="off">&nbsp <div id="1"> Field is
required
</div></td>
</tr>
<tr>
<td><label for="contact">Contact 1 :</label> </td>
<td><input type="text" maxlength = "10" name="contact" > &nbsp<div id="2"> Field
is required </div></td>
</tr>
<tr>
<td><label for="contact2">Contact 2:</label> </td>
<td><input type="text" maxlength = "10" name="contact2" >&nbsp <div id="3"> Field is
required </div></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</tbody>
</table>
</form>
SCRIPT
<script >
$(document).ready(function () {
var i;
for(i=1;i<=3;i++)
{
var k='#'+i;
$(k).hide();}
});
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmpty(theForm.fname,1);
reason += validateEmpty(theForm.contact,2);
reason += validateEmpty(theForm.contact2,3);
if (reason != "") {
return false;
}
return true;
}
function validateEmpty(fld,k) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "error";
var k='#'+i;
$(k).show();
} else {
fld.style.background = 'White';
var k='#'+i;
$(k).hide();
}
return error;
}
</script>
I would suggest the following:
Remove the onsubmit="..." from your HTML
Bind to the onsubmit event programmatically:
$(...).on("submit", validateFormOnSubmit);
Change the signature of validateFormOnSubmit accordingly:
function validateFormOnSubmit(event) {
// use this instead of theForm
}
Instead of returning false do event.preventDefault(), i.e.:
if (reason != "") {
event.preventDefault();
}
What about this ?
http://jsfiddle.net/45Kfy/
<code>
$(document).ready(function () {
$("input").each(function(index, item)
{
if ($(item).val().length == 0)
{
$(item).css("background-color", "red");
}
});
});
</code>
Instead of documentReady() you should trigger the button click.
(jQuery get the input value in an .each loop)
And watch out, your button is an inputfield too.

Is insertAdjacentHTML problematic?

I have two functions. The first is the one in which all the input elements will be checked to make sure they are filled correctly. Every thing works well but as the second function comes into action ( The second function 'newInput()' adds inputs ) the first function can not be applied anymore.
The debugger says the emailSec in atpositionSec = emailSec.indexOf("#"), is undefined.
Does any body know the solution??
The markup goes here:
<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
<tbody id="myInput">
<tr>
<td>
<label>Role:<span> *</span></label>
<input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<label>Email:<span> *</span></label>
<input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<button style="height: 20px;" title='Add' onclick='newInput()'></button>
</td>
</tr>
</tbody>
<input type="hidden" name="count" id="count" vale=""/>
</table>
<input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>
The First Function:
function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
role = document.forms['cms']['role'].value,
atpositionSec = emailSec.indexOf("#"),
dotpositionSec = emailSec.lastIndexOf(".");
if( topicSec == '' || topicSec == null)
{
alert ("Write your Topic!");
return false;
}
else if(role == '' || role == null)
{
alert ("Enter the Role of the email owner!");
return false;
}
else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
{
alert ("Enter a valid Email!");
return false;
}
else return true;
}
The Second Function:
//The Javascript - Adding Inputs
var i = 1,
count;
function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");
count = i;
document.forms["cms"]["count"].value = count;
i++;
}
// Removing Inputs
function del(field)
{
--count;
--i;
document.forms["cms"]["count"].value = count;
field.parentNode.parentNode.outerHTML = "";
}
The problem is that after the first addition, document.forms['cms']['emailSec'] becomes an array with all the elements with the name emailSec, so you would need to validate all of them individually using document.forms['cms']['emailSec'][i].
To save you some trouble, you could use the pattern attribute of the input elements in html5 to do this automatically. Furthermore, you could use something like <input type="email" required /> which I think will do almost all the work for you.

Categories