Toggle field depending on value - javascript

$(document).ready(function () {
toggleFields();
});
function toggleFields() {
if ($("#people").val() == 1)
$("#personen1").show();
else
$("#personen1").hide();
$("#personen2").hide();
$("#personen3").hide();
$("#personen4").hide();
$("#personen5").hide();
$("#personen6").hide();
$("#personen7").hide();
$("#personen8").hide();
}
<p>Personen:
<input type="number" id="people" name="ppl" min="1" class="uniform-input number" value="1" required="">
</p>
<div id="personen1">
<p>1. Person:
<input id="personen1_person1" type="text" name="person_name" />
</p>
</div>
<div id="personen2">
<p>1. Person:
<input id="personen2_person1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="personen2_person2" type="text" name="person2_name" />
</p>
</div>
<div id="personen3">
<p>1. Person:
<input id="personen3_person1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="personen3_person2" type="text" name="person2_name" />
</p>
<p>3. Person:
<input id="personen3_person3" type="text" name="person3_name" />
</p>
</div>
I have a people number input on my landingpage. I want to use the input value to add fields to my checkout. Like if the input is 5 I want 5 fields in my checkout page so the customer can fill in the names. The code above is not working correctly. What am I missing?

The first and foremost mistake you are making is duplicating ids, which are supposed to be unique, else unintended effects may appear.
The next thing is, the snippet will not work because you haven't included jQuery library, which is more important than anything to execute the $ function.
Thirdly, find these mistakes you have made:
You didn't bind the event with the input.
You need to check the input for the existence of id.
You aren't closing the if correctly.
You can compress the code a lot of effective ways, by using class or by using ids in a single $ selector.
$(document).ready(function () {
toggleFields();
$("#people").on("keyup change", function () {
toggleFields();
});
});
function toggleFields() {
$("#personen1, #personen2, #personen3, #personen4, #personen5, #personen6, #personen7, #personen8").hide();
if ($("#people").val() < 9)
$("#personen" + $("#people").val()).show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Personen:
<input type="number" id="people" name="ppl" min="1" class="uniform-input number" value="1" required="">
</p>
<div id="personen1">
<p>1. Person:
<input id="person1-1" type="text" name="person_name" />
</p>
</div>
<div id="personen2">
<p>1. Person:
<input id="person2-1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="person2-2" type="text" name="person2_name" />
</p>
</div>
<div id="personen3">
<p>1. Person:
<input id="person3-1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="person3-2" type="text" name="person2_name" />
</p>
<p>3. Person:
<input id="person3-3" type="text" name="person3_name" />
</p>
</div>

You should not have multiple ids with same value.
That is not a right way of doing this, you should generate the HTML using JavaScript only:
// Sample code, you can create a function for this as well.
$(function(){
var count = 5; // Change this count with the input field value.
var _html = "";
for(var i=0; i<count; i++){
_html += '<p>'+(i+1)+'. Person:'
+'<input id="person'+(i+1)+'" type="text" name="person'+(i+1)+'_name" />'
+'</p>';
}
$(".container").html(_html);
});
Here is a fiddle

Every id attribute you use on a webpage has to be unique in the entire document, also -- you're using some kind of template to load when a user types a number but what if a user wants to add 10 people instead of 3 or 5? Individually adding cases will cause you much pain in the future.
I also understand that you want users to input a number and then get a certain amount of fields back from that, with that assumption made the code
$(document).ready(function() {
toggleFields();
});
will not work since it only gets executed once, onload of the page and doesn't get executed anymore after that since no events are bound.
var insertPeople = function(n) {
var amt = !isNaN(n) ? n : 1;
var fieldStr = '';
//using a for loop to 'build' the fields dynamically
for (var i = 0; i < amt; i++) {
var num = i + 1;
fieldStr += '<p>'+ num +'. person<input type="text" id="person'+ num +'" name="person'+ num +'_name"></p>'
}
//append HTML to container
$('#people-container').html(fieldStr);
}
//Use this to insert fields on page load instantly.
$(insertPeople);
//Use this if you would like a user to control the amount of fields through an input field.
$(function() { //shorthand for $(document).ready
$('#people').on('keyup', function() {
insertPeople($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="people" value="1" />
<div id="people-container"></div>
This code will loop for n times where n is the user input (validate the type of that yourself) and creates fields with ID's starting from 0 through the end point at the end of the loop. At the last step it appends the fields to a container, if this were a form then that form would simply be submit with those values.

Related

Create Custom validation Class in javaScript/Jquery

Let say there is an input element field and i want to create a new validation class myClass ,that i can insert with any html element that might performing some function and also setting attribute such as
readonly="true"
required='true'.
HTML is
<td>
<input type="text" id="endDate" name ="endDate" class="select_200" required readonly="true">
</td>
Now rather setting elements separately need one class for performing:
A function check "let say character count less then 10" and setting
attribute.
Setting attributes such as readonly ,required
So that i can add that class to all elements with similar property.
Validation + Setting/ Reseting attributes by adding class only
You can set your own custom attributes for your input elements and use those custom attributes to query the input fields and perform various actions. You can find my sample below.
$(function () {
//Set various input field attributes here
$("input[data-myCustomClass]").each(function(){
//$(this).attr("readonly", true);
$(this).attr("required", true);
});
//Sets max length - you can change this code to retrieve info from attribute
$("input[data-setFieldLength]").each(function(){
$(this).attr("maxlength", 10);
});
//Validate for field length based on "validateFor" attribute
$("input[data-validateFieldLength]").each(function(){
$(this).on('focusout', function(){
var validateFor = $(this).attr("validateFor");
if ($.trim($(this).val()).length < parseInt(validateFor))
{
$(this).focus();
$(this).select();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" data-myCustomClass data-setFieldLength id="field1" />
<input type="text" data-myCustomClasss id="field2" />
<input type="text" data-setFieldLength id="field3" /> <!-- set field length to 10 -->
<input type="text" data-validateFieldLength id="field4" validateFor="5" /> <!-- validate for 5 characters and return focus -->
you have create new function for a field?
on
<form onsubmit="return validate()" name="form">
<td>
<input type="text" id="custname" name ="endDate" class="select_200"
required readonly="true">
<font style="color:red" id="custnameerror"></font>
</td>
<button onclick="return validate()"></button>
</form>
javascript validation function like
<script type="text/javascript">
function validate(from)
{
var error=document.getElementById("custnameerror");
var custname=form["custname"].value;
error.innerHTML="";
if( custname==null || custname==""){
error.innerHTML="Enter customer name";
return false;
}
if(custname.length<3){
error.innerHTML="Customer name should be minimum 3 character";
return false;
}
if(custname.length>80){
error.innerHTML="Customer name should be in between 3 to 80
character";
return false;
}/*end */
</script>

Get values of selected checkboxes and their associated textareas in Javascript

I have a HTML form. In this form I have 5 checkboxes and each checkbox has an associated textarea.
So I want to get the values of only the checked checkboxes and their associated textarea text. I am able to get the values of the checked checkboxes but I can't figure out a way to get the values of their associated textarea.
My HTML code is:
<form class="my-form" id="id_MyForm">
<div class="form-group">
<label class="qquestion">6. Which of the following is most relevant to you and why? (Select all that apply).</label>
<div class="checkbox" id="id_Question6">
<label>
<input type="checkbox" id="input_que6a" value="Time" name="question6" />Time
</label>
<textarea name="question6a_textarea" id="id_que6a" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" id="input_que6b" value="Money" name="question6" /> Money
</label>
<textarea name="question6b_textarea" id="id_que6b" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" id="input_que6c" value="Family" name="question6" /> Family
</label>
<textarea name="question6c_textarea" id="id_que6c" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" id="input_que6d" value="Hobbies" name="question6" /> Hobbies
</label>
<textarea name="question6d_textarea" id="id_que6d" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" value="Other" name="question6" id="other_que6" /> Other
</label>
<br>
<textarea name="question6_textarea" id="id_Question6_textinput" class="form-control" placeholder="Please elaborate"></textarea>
</div>
</div>
<div class="text-center">
<button type="button" id="id_SubmitForm" class="btn btn-success">Submit</button>
</div>
</form>
My JavaScript code is:
/* Latest compiled and minified JavaScript included as External Resource */
var question6AnsArray = [];
/* To hide all the text areas when the page loads */
$("#id_Question6_textinput").hide();
$("#id_q6_opH_textarea").hide();
$('#id_que6a').hide();
$('#id_que6b').hide();
$('#id_que6c').hide();
$('#id_que6d').hide();
/* To show appropriate text area for selected check box */
$('#input_que6a').click(function() {
$("#id_que6a").fadeToggle(this.checked);
});
$('#input_que6b').click(function() {
$("#id_que6b").fadeToggle(this.checked);
});
$('#input_que6c').click(function() {
$("#id_que6c").fadeToggle(this.checked);
});
$('#input_que6d').click(function() {
$("#id_que6d").fadeToggle(this.checked);
});
$('#other_que6').click(function() {
$("#id_Question6_textinput").fadeToggle(this.checked);
});
$("#id_SubmitForm").click(function() {
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
//Here I want to get the value for the textarea.
});
var question6Answer = question6AnsArray.join(", ");
alert(question6Answer);
});
Here is a link to JSFiddle
$("#id_SubmitForm").click(function() {
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
question6AnsOtherArray.push($(this).closest("label").next("textarea").val());
});
var question6Answer = question6AnsArray.join(", ");
var question6OtherAnswer = question6AnsOtherArray.join(", ");
alert(question6Answer);
alert(question6OtherAnswer);
});
And, You could actually optimize your code this way a little bit too..
/* Latest compiled and minified JavaScript included as External Resource */
var question6AnsArray = [];
var question6AnsOtherArray = [];
/* To hide all the text areas when the page loads */
$("#id_Question6_textinput").hide();
$("#id_MyForm textarea").hide();
/* To show appropriate text area for selected check box */
$("input[type=checkbox]").click(function() {
$(this).closest("label").next("textarea").fadeToggle();
})
$('#other_que6').click(function() {
$("#id_Question6_textinput").fadeToggle(this.checked);
});
$("#id_SubmitForm").click(function() {
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
question6AnsOtherArray.push($(this).closest("label").next("textarea").val());
});
var question6Answer = question6AnsArray.join(", ");
var question6OtherAnswer = question6AnsOtherArray.join(", ");
alert(question6Answer);
alert(question6OtherAnswer);
});
from your this context step back up to your parent then grab the next text element.
$('input[type="checkbox"]').on('click', function() {
if ( $(this, ':checked') ) {
$(this).val();
$(this).parent().next('textarea').val();
)
}
Try below function at last:
$("#id_SubmitForm").click(function() {
question6AnsArray = [];
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
question6AnsArray.push($('.form-control').val());
//Here I want to get the value for the textarea.
});
var question6Answer = question6AnsArray.join(", ");
alert(question6Answer);
});

Change input value on tab

I'm coding a small web app to log team members work time. It all works well, except one thing. When you tab on a fieldset a new page opens with a form to change the time for that person. The first time you tab it works, but when you click on the next fieldset it changes all input fields with the name 'begin-time' ?
I think i'm missing something but I'm not sure what it is.
I have the following form;
<form id="time-form">
<fieldset>
<div class="row">
<input type="text" value="Jonh Doe" id="fullname" name="fullname" readonly="">
<div class="time">
<input type="text" value="00:00" id="begin-time" name="begin-time" readonly="">
<input type="text" value="00:00" id="end-time" name="end-time" readonly="">
</div>
</fieldset>
<fieldset>
<div class="row">
<input type="text" value="Jane Doe" id="fullname" name="fullname" readonly="">
<div class="time">
<input type="text" value="00:00" id="begin-time" name="begin-time" readonly="">
<input type="text" value="00:00" id="end-time" name="end-time" readonly="">
</div>
</fieldset>
</form>
with the new form 'on tab';
<form id="add-time">
<input type="time" name="begin_time">
<input type="time" name="end_time">
</form>
and the javascript;
$$('#time-form fieldset').tap(function() {
var beginTime = $(this).find("[name='begin-time']");
$('#add-time input[name=begin_time]').change(function() {
beginTime.val(this.value);
});
$$('.add-time').tap(function() {
$('#addTimePage').addClass('pt-page-moveToRightEasing pt-page-ontop');
$('#timePage').addClass('pt-page-moveFromLeft pt-page-current');
setTimeout(function () {
$('#timePage').removeClass('pt-page-moveFromLeft');
$('#addTimePage').removeClass('pt-page-moveToRightEasing pt-page-ontop pt-page-current');
}, 400);
});
});
edit: I have setup a simple fiddle of the problem.
Okay, so I noticed a few problems:
Your first .click() call was targeting ALL time-form fieldsets when it should have only been targeting input fields.
Your .change() and second .click() are called inside the first .click() meaning the new methods will be called multiple times (because each use of .click() and .change() adds on to the actual event.
Your submit button wasn't actually submitting anything. It was just hiding itself.
To fix this, I gave each fieldset a class name of .fieldset-time so they can easily be looped through. I added an onclick() event to each <fieldset> to easily manipulate the one (and its children) that was clicked.
Here's the new JavaScript code:
// invoked each time an input with the onclick() attribute is clicked
function editTime(obj) {
$("#addTimePage").fadeIn();
$(obj).attr("id", "active"); // set id to active so we know this is the one we want to change
}
$("#submit").click(function() {
// get the new beginning and end times set by the user
var newBeginTime = $("#add-time input[name=begin_time]").val();
var newEndTime = $("#add-time input[name=end_time]").val();
// loop through all elements with class .fieldset-time and find the active one
$(".fieldset-time").each(function() {
if ($(this).attr("id") == "active") {
$(this).attr("id", "");
$("input[name=begin-time]", this).val(newBeginTime);
$("input[name=end-time]", this).val(newEndTime);
return false; // break out of the .each() loop
}
});
// finally, clear and hide the add time box
$("#add-time input[name=begin_time], #add-time input[name=end_time]").val("");
$("#addTimePage").fadeOut();
});
And the new JSFiddle: http://jsfiddle.net/J4Hjf/7/
I hope that's what you were looking for. :)

associate number in number field with the number of newly created js div's

I have a set of number input fields, labeled small & medium.., and a set of div's with the label small and medium. When you add a number to the small number input field a text input insertsAfter the div labeled small. When you subtract a number from the small number input field, the text input field that was recently added is removed. the adding and removing of the text input is be the last one in the list. This same thing goes for the medium number field and medium label/textfield
please see JSFiddle for reference
http://jsfiddle.net/7PhJZ/53/
Right now my script is working correctly when I click the up or down buttons on the number field. But When I type in, for instance 5 in the small number field, only one new div/name input fields appears under the label small. I need the adding and subtracting of these input fields to be generated when I use the arrows and when I type in a number. So when I type in "5" 5 name/text input fields should appear under the associated label.
html :
<div id="product-1">
<div class="size-field">
<div id="size-label">s</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small"
min="0" max="9999" data-product-id="1"></input>
</div>
</div>
<div id="size-label">m</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number"
name="Medium" min="0" max="9999" data-product-id="1"></input>
</div>
<div class="name-number-header">
<h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
<br clear="all">
<div id="product-2">
<div class="size-field">
<div id="size-label">s</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small"
min="0" max="9999" data-product-id="2"></input>
</div>
</div>
<div id="size-label">m</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium"
min="0" max="9999" data-product-id="2"></input>
</div>
<br clear="all">
<div class="name-number-header"><h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
js :
$('.product-quantity').each(function () {
$(this).data('val', this.value);
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val'),
input = $('<div/>', {'class': 'name-number-field'}).html('<input
class="name-field" name="name" placeholder="Name" type="text">'),
ele = $(this).closest('[id^="product"]').find('[data-size="' + this.name + '"]'),
inc = val >= old;
if (inc) {
$(input).insertAfter(ele.nextUntil(':not(.name-number-field)').last()
.length ? ele.nextUntil(':not(.name-number-field)').last() : ele);
} else {
ele.nextUntil(':not(.name-number-field)').last().remove();
}
$(this).data('val', this.value);
});
See this fiddle
You need to put a for loop outside the code that created the elements:
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val');
for (var count=0; count<Math.abs(val-old) ; count++)
{
...
}
Update based on comments
See this updated fiddle. There were some problems that were in the original code:
The data was not initialised. Fix: if( !startVal || startVal.length == 0 )
The comparison was not with ints. Fix: inc = (parseInt(val) >= parseInt(old));
Your code is checking for the direction of change between old and new only, not how much difference there is. If it's an increase (of any amount), you add an element; if it's a decrease, you remove one.
You need to wrap that code in a loop and execute it as many times as the difference between old and new.
for (var i=0 ; i<Math.abs(val-old) ; i++) {
if (inc) {
$(input).insertAfter(ele.nextUntil(':not(.name-number-field)').last()
.length ? ele.nextUntil(':not(.name-number-field)').last() : ele);
} else {
ele.nextUntil(':not(.name-number-field)').last().remove();
}
}

How to dynamically add text fields to a form based on a number the user puts in

I'm attempting to make a form that asks the user for a number of units, then asks whether or not they would like those units to be provisioned, and depending on the answer, generates text fields corresponding with the number of units the typed in, along with a text field asking for an account number.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
function Getunits(value) {
var units = document.getElementById('units');
for(count=0; count<=units; count++) {
$("<input type='text'>").appendTo("inpane");
}
document.getElementByTag('futureacc').InnerHTML='What is your account number? <input type="text" value="accountnum">';
}
</script>
</head>
<body>
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/><br />
</div>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="Getunits('units.value')"/> Yes <input type="radio" name="select" value="no"/> No
</div>
Obviously I would like the new text fields to appear inside the futureacc div and inpane div respectively.
I don't know whether it's the loop that doesn't do anything or that I'm not appending correctly but as I currently have it this does nothing...
Any help would be greatly appreciated.
You had a number of errors with your code. It was confusing because you were mixing jQuery and pure Javascript. It's generally better to just use jQuery if you've decided to use it anyway. Your loop should have been iterating while it was smaller than units.val(), not while it was smaller than or equal to units. innerHTML is spelled with a lowercase "i," and your appendTo selector needed a period before the class name. I went ahead and cleaned up your code so it should work now!
HTML:
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/>
</div><br>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="getUnits()"/> Yes <input type="radio" name="select" value="no"/> No <br>
</div>
</form>
</div>​
Javascript:
function getUnits() {
var units = $("#units").val();
for (var count = 0; count < units; count++) {
$("<input type='text' /><br>").appendTo("#futureacc");
}
$("#futureacc").append('<br>What is your account number? <input type="text" placeholder="accountnum">');
}​
WORKING DEMO
var units = document.getElementById('units');
needs to be
var units = document.getElementById('units').value;
you are passing value to onclick but it is a string will not give you exact value anyway you are not using it in you function so it doesnt have any side effect.
also you need to some error check to make sure that user has entered a number
with
for(count=0; count<=units; count++)
You are adding 1 more text box than user entered value. so if user has entered 4 you are creating 5 <= should be changed to <
This is wrong
onClick="Getunits('units.value')"
Instead use this:
onClick="Getunits(units.value)"
try this
$(document).ready(function(){
$('input[name=select]').click(function(){
if($(this).val() ==='yes'){
var numberOfTextboxes = $('#units').val();
for(var i =0; i<numberOfTextboxes; i++){
$('#unitammount').append('<input type="text" />');
}
}
});
});
See the fiddle

Categories