i have a form and would like to give users the ability to duplicate a group of fields as many times as necessary. With one group it iterates correctly but when I add a second group the "current" variable iterates collectively instead of being unique to each group... i tried changing all of the "current" to "newFieldset.current" but that returns NAN... any ideas?
<script type="text/javascript">
$(document).ready(function() {
var current = 0;
//Add New Fieldset with Button
var newFieldset = {
init: function(groupIndex) {
current++;
$newPerson= $("#Template"+groupIndex).clone(true);
$newPerson.children("p").children("label").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("for",$currentElem.attr("for")+current);
});
$newPerson.children("p").children("input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$currentElem.attr("name")+current);
$currentElem.attr("value",$currentElem.attr("value")+groupIndex+current);
$currentElem.attr("id",$currentElem.attr("id")+current);
});
$newPerson.appendTo("#mainField"+groupIndex);
$newPerson.removeClass("hideElement");
},
currentID: null,
obj: null
};
$(".addButton").each(function() {
$(this).click(function() {
var groupIndex = $(this).attr("title");
//newFieldset.obj = this;
//var fieldIndex = $(this).attr("class");
newFieldset.init(groupIndex);
});
});
console.log('r');
});
</script>
<style>
.hideElement {display:none;}
</style>
<form name="demoForm" id="demoForm" method="post" action="#">
<div id="groupCtr1">
<fieldset id="mainField1">
<div id="Template1" class="hideElement">
<p>
<label for="firstname">Name</label> <em>*</em>
<input id="firstname" name="firstname" size="25" /> <input id="lastname" name="lastname" size="25" />
</p>
<p>
<label for="email">Email</label> <em>*</em><input id="email" name="email" size="25" />
</p>
</div>
<div>
<p>
<label for="firstname1">Name</label>
<em>*</em> <input id="firstname1" name="firstname1" size="25" /> <input id="lastname1" name="lastname1" size="25" />
</p>
<p>
<label for="email1">Email</label>
<em>*</em><input id="email1" name="email1" size="25" />
</p>
</div>
</fieldset>
<p>
<input type="button" class="addButton" title="1" value="Add Another Person">
</p>
</div>
<div id="groupCtr2">
<fieldset id="mainField2">
<div id="Template2" class="hideElement">
<p>
<label for="coname">Company Name</label> <em>*</em>
<input id="coname" name="coname" size="25" />
</p>
<p>
<label for="codesc">Description</label> <em>*</em><input id="codesc" name="codesc" size="25" />
</p>
</div>
<div>
<p>
<label for="coname1">Company Name</label>
<em>*</em> <input id="coname1" name="coname1" size="25" />
</p>
<p>
<label for="codesc1">Description</label>
<em>*</em><input id="codesc1" name="codesc1" size="25" />
</p>
</div>
</fieldset>
<p>
<input type="button" class="addButton" title="2" value="Add Another Company">
</p>
</div>
<input type="submit" value="Save">
</form>
Attach the value to the element with the jQuery data method. Increment it on click, and then pass it to the newFieldset.init method as the second param. Voila!
$(document).ready(function() {
//Add New Fieldset with Button
var newFieldset = {
init: function(groupIndex,current) {
$newPerson= $("#Template"+groupIndex).clone(true);
$newPerson.children("p").children("label").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("for",$currentElem.attr("for")+current);
});
$newPerson.children("p").children("input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$currentElem.attr("name")+current);
$currentElem.attr("value",$currentElem.attr("value")+groupIndex+current);
$currentElem.attr("id",$currentElem.attr("id")+current);
});
$newPerson.appendTo("#mainField"+groupIndex);
$newPerson.removeClass("hideElement");
},
currentID: null,
obj: null
};
$(".addButton").click(function() {
var groupIndex = $(this).attr("title");
var current = $(this).data('current');
$(this).data('current',++current);
//newFieldset.obj = this;
//var fieldIndex = $(this).attr("class");
newFieldset.init(groupIndex,current);
}).data('current',0);
console.log('r');
});
Happy jquery-ing to you sir.
if you dont make the current variable global it will should work. try this:
var newFieldset = {
current: 0,
init: function() {
this.current++;
//rest of init code
},
//all your other fieldset code here
};
/* all other code */
EDIT: After re-reading the question, I would take a completely different approach to what you're trying to achieve. The above code will still exhibit the same behavior for you. If the question hasn't been successfully answered I'll do a bigger writeup when i get home.
I would do something like that:
...
var currents = {};
var newFieldset = {
init: function(groupIndex) {
var current = 0;
if (currents[groupIndex]) {
current = currents[groupIndex];
}
++current;
currents[groupIndex] = current;
...
Related
Can any one help me with this, I'm trying to use this code on a POS to calculate the change to give a customer and it works for the must part.
The problem I'm having is if I an order costs £9.99 and I enter £10, instead of it calculating the change as £0.01 it calculates it as £ 0.009999999999999787
Here is the code that I'm using.
function sum() {
var og_total = document.getElementById('og_cart_total').value;
var og_tendered = document.getElementById('og_cash_tendered').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = '£';
if (!isNaN(og_change)) {
document.getElementById('og_change_given').value = og_symbol + og_change;
}
}
<input type="hidden" id="og_cart_total" value="19.99" onkeyup="sum();" />
<div class="control-group">
<label class="control-label" for="og_cash_tendered">Tendered:</label>
<div class="controls">
<input class="cm-autocomplete-off" type="text" name="payment_info[og_cash_tendered]" value="" id="og_cash_tendered" onkeyup="sum();" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="og_change_given">Change:</label>
<div class="controls">
<input type="text" name="payment_info[og_change_given]" id="og_change_given" value="£-19.99" readonly="readonly" />
</div>
</div>
there is this way but it's not as promising as it should. the best way is to use a library for long numbers if it worth the trouble.
function sum() {
var og_total = document.getElementById('txt1').value;
var og_tendered = document.getElementById('txt2').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = "£";
if (!isNaN(og_change)) {
document.getElementById('og_change_text').value = og_symbol + og_change;
}
}
<input type="text" id="txt1" value="9.99" readonly="readonly" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" readonly="readonly" id="og_change_text" />
Ok, so I am trying to push the value of an HTML form input to a JavaScript array. When I load the page and submit values through the form, it returns empty strings in the array. I don't understand why this is happening. Thank you for your help.
Relevant HTML:
<form>
<div class="form-group">
<label for="name1">Name: </label>
<input type="text" class="form-control b" id="nameone">
<label for="pref1">Preferences: </label>
<input type="text" class="form-control a" id="prefone"> </div>
<div class="form-group">
<label for="name2">Name: </label>
<input type="text" class="form-control c" id="nametwo">
<label for="pref2">Preferences: </label>
<input type="text" class="form-control a" id="preftwo"> </div>
<div class="form-group">
<label for="name3">Name: </label>
<input type="text" class="form-control d" id="namethree">
<label for="pref3">Preferences: </label>
<input type="text" class="form-control a" id="prefthree"> </div>
<div class="form-group">
<label for="name4">Name: </label>
<input type="text" class="form-control e" id="namefour">
<label for="pref4">Preferences: </label>
<input type="text" class="form-control a" id="preffour"> </div>
<!-- ... -->
<button type="submit" class="btn btn-primary" id="sbm">Submit</button>
</form>
Relevant JavaScript:
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
// ...
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
document.getElementById('sbm').onclick = namesdefine();seat(document.getElementsByClassName('a').value);check();changeHTML();
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
You're calling the namesdefine() function when you assign to .onclick. You should be assigning the function to .onclick, so leave out the () after it.
document.getElementById('sbm').onclick = namesdefine;
Either use:
document.getElementById('sbm').onclick = namesdefine;
Or
document.getElementById('sbm').addEventListener('click', namesdefine);
If you need to call them all, use this:
document.getElementById('sbm').onclick = function () {
namesdefine();
seat(document.getElementsByClassName('a').value);
check();
changeHTML();
}
And it's always a good practice to check for null after getElementById()
Try to get your data in a loop.
You can use getElementByTagName or getElementByClassName.
var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
//Create array here arr.push(elements[i].value);
}
You can call that in your click function.
Hope that helps.
I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
I am looking to build a simple webpage that can check to see if a string contains certain information. I'm taking a summer course in Java and wanted to give Javascript a try. Maybe a bad idea?
I want the user to enter information - name, phone number, and a couple other options in a form. Then I want the user to enter more information in the text area. The text area will reference the input data and if there is a match it will alert the user.
I have limited javascript experience, but I've been able to manipulate user input with javascript in the past.
Not sure what my problem here is. Any tips (especially regarding style and logic) are greatly appreciated! PS - I'm using Bootstrap if that matters...
Thanks in advance :)
HTML
<div class="container">
<div class="col-md-6">
<form>
<input type="text" id="Name" placeholder="Name" style="width:100%"><br /><br />
<input type="text" id="Number" placeholder="Number" style="width:100%"><br /><br />
<input type="text" id="Next" placeholder="Something Else" style="width:100%"><br /><br />
<input type="text" id="WhatEver" placeholder="Something Else" style="width:100%"><br /><br />
</form>
</div>
<div class="col-md-6">
<textarea id="LongText" placeholder="Enter Info" style="width:100%; height:250px">
</textarea> <br />
<input type="submit" class="btn btn-danger" id="tSubmit" value="Submit" onclick="GetInput();Check();">
</div>
<div class="col-md-12">
<h1>Output</h1>
<div id="tOutPut" style="color:red;"></div>
</div>
</div>
JS
GetInput()
{
var tNameValue = document.getElementById("Name").value;
var tValue = document.getElementById("Number").value;
var tArray = document.getElementById('LongText').value.split('\n');
}
Check( tArray, tNameValue, tValue )
{
for(var i = 0; i < tArray.length; i++ )
{
if( i === tNameVaue )
{
document.getElementById( 'tOutPut' ).innerText = "Name Match" <br />;
}
if( i === tValue )
{
document.getElementById( 'tOutPut' ).innerText = "Match" <br />;
}
}
}
*
Your javascript has many things wrong. Here is the HTML and the Javascript. The logic must be improved but the code is working.
<div class="container">
<div class="col-md-6">
<form>
<input type="text" id="Name" placeholder="Name" style="width:100%"><br /><br />
<input type="text" id="Number" placeholder="Number" style="width:100%"><br /><br />
<input type="text" id="Next" placeholder="Something Else" style="width:100%"><br /><br />
<input type="text" id="WhatEver" placeholder="Something Else" style="width:100%"><br /><br />
</form>
</div>
<div class="col-md-6">
<textarea id="LongText" placeholder="Enter Info" style="width:100%; height:250px">
</textarea> <br />
<input type="submit" class="btn btn-danger" id="tSubmit" value="Submit" onclick="ExecuteAll();">
</div>
<div class="col-md-12">
<h1>Output</h1>
<div id="tOutPut" style="color:red;"></div>
</div>
</div>
And here is the Javascript:
var tNameValue;
var tValue;
var tArray;
function ExecuteAll()
{
GetInput();
Check();
}
function GetInput()
{
tNameValue = document.getElementById("Name").value;
tValue = document.getElementById("Number").value;
tArray = document.getElementById('LongText').value.split('\n');
}
function Check()
{
if (tArray != null) {
for(var i = 0; i < tArray.length; i++ )
{
if( i == tNameValue )
{
document.getElementById( 'tOutPut' ).innerText = "Name Match <br />";
}
if( i == tValue )
{
document.getElementById( 'tOutPut' ).innerText = "Match <br />";
}
}
}
}
I will tell you what I did to fix the bugs:
Added function keyword to the javascript functions.
Put the variables as global so they can be used for the whole code.
Verified whether tArray is not null.
Fixed variable names.
Here is the Fiddle code: http://jsfiddle.net/3U6mE/6/
I hope it helps you get started.
hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/