Generating html inside for loop - javascript

I'm using this jquery validation: http://www.runningcoder.org/jqueryvalidation/
It works perfectly but if I generate my code dynamically with javascript, if one of the input fails the data-validation, the error message will appear in all inputs.
Is there a way to fix this?
for (var i = 0; i < result.length; i++) {
inputs += '<div class="input-group bottom15"><span class="input-group-addon">' + (i + 1) + '</span>' +
'<input type="text" class="form-control" placeholder="Insert the description for ' + result[i] + '" name="paramDescriptions" id="paramName' + (i + 1) + '"' +
'data-validation-message="The description must be between 2 and 25 characters. No special characters allowed."\n' +
'data-validation="[L>=2, L<=25, MIXED]" required></div>';
}
The code above generates...
<div id="inputDiv" class="col-sm-10">
<div class="input-group bottom15"><span class="input-group-addon">1</span><input type="text" class="form-control" placeholder="Insert the description for FREQUENCY" name="paramDescriptions" id="paramName1" data-validation-message="The description must be between 2 and 25 characters. No special characters allowed."
data-validation="[L>=2, L<=25, MIXED]" required=""></div>
<div class="input-group bottom15"><span class="input-group-addon">2</span><input type="hidden" class="form-control" name="paramName" value="DAYS"><input type="text" class="form-control" placeholder="Insert the description for DAYS" name="paramDescriptions" id="paramName2" data-validation-message="The description must be between 2 and 25 characters. No special characters allowed."
data-validation="[L>=2, L<=25, MIXED]" required=""></div>
</div>

The jQuery form Validation looks for elements using this part of the code:
node.find('input:not([type="submit"]), select, textarea')
so every input field in your example will be checked. However, the error is registered for the field's name attribute:
var inputName = $(input).attr('name')
// ...
registerError(inputName, error[0].replace('$', inputShortName).replace('%', error[1]));
That's the reason you see error message for both fields.
A simple change of the field's name value to a unique value will fix this issue.

Related

In Javascript why is appending to TextArea field failing in one case but not the other

I have a javascript function that takes a value from a select and append its to the end of a textarea field (mask) whenever a new selection is made from the select
function addToEditMask(select, mask)
{
var selectedValue = document.getElementById(select).value;
document.getElementById(mask).append(" + "+selectedValue);
}
This function is used by two different elements on the same page as follows:
<div class="form-group">
<label for="edit_filename_mask_mask" id="edit_filename_mask_masklabel">
Mask
</label>
<textarea type="text" id="edit_filename_mask_mask" name="edit_filename_mask_mask"
aria-describedby="edit_filename_mask_masklabel" class="form-control" rows="10" cols="80"></textarea>
</div>
<div class="form-group">
<label for="editMaskVarList" id="editMaskVarListlabel">
Mask Fields
</label>
<select class="mb-2 form-control custom-select" id="editMaskVarList" onchange="addToEditMask('editMaskVarList', 'edit_filename_mask_mask');">
<option>
acoustic (Acoustic)
</option>
.....
and
<div class="form-group">
<label for="add_filename_mask_mask" id="add_filename_mask_masklabel">
Mask
</label>
<textarea type="text" id="add_filename_mask_mask" name="add_filename_mask_mask"
aria-describedby="add_filename_mask_masklabel" class="form-control" rows="10" cols="80"></textarea>
</div>
<div class="form-group">
<label for="addMaskVarList" id="addMaskVarListlabel">
Mask Fields
</label>
<select class="mb-2 form-control custom-select" id="addMaskVarList" onchange="addToEditMask('addMaskVarList', 'add_filename_mask_mask');">
<option>
acoustic (Acoustic)
</option>
......
In each case the select and the mask are both within a Bootstrap modal dialog. But it only works for the second case (add_filename_mask_mask) not the first case (edit_filename_mask_mask)
I added some debugging to ensure
function addToEditMask(select, mask)
{
var selectedValue = document.getElementById(select).value;
document.getElementById(mask).append(" + "+selectedValue);
alert('Adding to mask:'+mask+':'+scriptvar+':'+document.getElementById(mask).value);
}
that the function was actually being called in both cases and all the variables a renamed correctly. Yet although there are no webconsole errors and the append() method doesnt report any error the value of mask doesnt change for edit_filename_mask_mask
I cannot create a SSCE since there seems to be no difference between the working and non working version. The only difference of note is that when modal dialog is first displayed edit_filename_mask_mask has a value but add_filename_mask_mask does not. However edit_filename_mask_mask continues to fail if I blank out edit_filename_mask_mask , and add_filename_mask_mask when has value.
What happens if you try some safety checks ?
function addToEditMask(select, mask)
{
var selectedValue = document.getElementById(select).value || "";
var textarea = document.getElementById(mask);
textarea.value = (textarea.value || "") + " + " + selectedValue;
}
Variable name is "selectedValue" and you call to "selectValue"

Textarea character counter not working on dynamically created table

I have a dynamically created table and on the click of a button a modal opens. The first time I click on any button and enter values:
https://imgur.com/a/4YNdO
And then for the next time if I click on another button, it shows:
https://imgur.com/a/pjloi
91 characters remaining, but it should show 100 characters remaining as it is another modal.
My HTML:
<div class="modal-body">
<p><input type="checkbox" name="email" id="email" class="email" > Notify Via Email<br></p>
<p><label for="message">Message </label>
<textarea rows="3" name="message" id="message" class="form-control input-md message" onclick="remainingChar()"></textarea></p>
<div id="textarea_feedback" class="textarea_feedback"></div>
</div>
My jQuery:
function remainingChar(){
var text_max = 100
$('.textarea_feedback').html(text_max + ' characters remaining');
$('.message').keyup(function() {
var length = $(this).val().length;
var length = text_max-length;
$('.textarea_feedback').html(length + ' characters remaining');
});
}
Call your remainingChar() function on your modal raise, something like:
$('.raise-modal-button').on('click', function{
remainingChar();
$('.modal-body').show();
});

jQuery Find Name Based On Form

So I am currently trying to fill a form using jQuery based on saved information. Currently, I am doing this:
$.each(form_data.form_data, function(name, val) {
var $el = $('[name="' + val.name + '"]');
var type = $el.attr('type');
switch(type){
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="' + val.value + '"]').attr('checked', 'checked');
break;
default:
$el.val(val.value);
}
});
However, if the input field doesn't exist, I want to be able to copy the parent div and create a clone after the last div. The only time this would occur is if they dynamically created fields previously, so they would be in the format of something-example[0] and something-example[1]
My idea was if I had something-example[2], then search for the input field without the square brackets so trying to match up something-example with something-example, and then clone that div. I am using Bootstrap if you want to get an understanding of the design of the page.
This is an example of the form-group:
<div class="form-group itemize-last">
<label for="itemize-supplies-name[1]" class="col-sm-1">Item</label>
<div class="col-sm-5">
<input type="text" name="itemize-supplies-name[1]" class="form-control">
</div>
<label for="itemize-supplies-amount[1]" class="col-sm-1">Amount</label>
<div class="col-sm-3">
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="text" name="itemize-supplies-amount[1]" class="form-control itemize-supplies-amount money">
</div>
</div>
</div>
How would I go about taking care of this feature? Thanks!

IP Range From and IP Range To - Dynamic Text Box

I want to add two dynamic text box to enter "IP Range From" to "IP Range To" and one add more button to insert new IP Range plus validations to test those ranges.
Please suggest the code.
Waiting for your early response.
Thanks in Advance
Tanu
Asuming you use jQuery, if i were you, i would create a DIV with the "textbox-list" and just after the div, a button to add new textbox in the above div.
Here is the part of code :
<div id="iprange_list">
</div>
<img src="images/plus.png" alt="new ip range image"/>
Then just add a .click() event on the id new_iprange to dynamically add a line which contains 2 input with unique ID (static text + increment a var). I suggest you to define general span with a class for each line, such as "linecontainer", and then just add a "title" property to your span with the increment var used above.
After few clicks, your div would look like that :
<div id="iprange_list">
<span class="linecontainer" title="1"><input type="text" id="tbxfrom1" /><input type="text" id="tbxto1" /></span>
<span class="linecontainer" title="2"><input type="text" id="tbxfrom2" /><input type="text" id="tbxto2" /></span>
<span class="linecontainer" title="3"><input type="text" id="tbxfrom3" /><input type="text" id="tbxto3" /></span>
</div>
<img src="images/plus.png" alt="new ip range image"/>
Finally when you validate your form just use the jquery selecter to retrieve every line in your Div, and use a .each() to iterate between your lines :
$.each($( "#iprange_list .linecontainer" ), function(i, item) {
var currentID = $(item).attr("title");
alert( $( "#tbxfrom" + currentID ).val() );
alert( $( "#tbxto" + currentID ).val() );
});
That's just an idea, i let you do the rest ;) !
To validate the IpAddress you need a regular expression to do this.
See here sample regular expression to validate the IpAddress.
Then to check the range you need to compare the two textbox value
if(textbox1.value > textbox2.value){...
To add additional IpRange, you need to create new element using DOM.
var newField = document.createElement('input');
To summarize all this see a working sample here in jsfiddle
Note: This might not be the exact things you want, its your part to do the rest.
UPDATE CODE:
SCRIPT
var ipIndex = 1;
var validIp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
function addIpRange(){
var ipDiv = document.getElementById('ipRange');
var newDiv = document.createElement('div');
ipIndex++;
newDiv.innerHTML = ipIndex + '. From: <input type="text" name="ipfrom" /> To: <input type="text" name="ipto" /><input type="button" onClick="validate(\'ipRange' + ipIndex + '\');" value="Validate">'
newDiv.setAttribute('id', "ipRange" + ipIndex);
ipDiv.appendChild(newDiv);
}
function validate(id){
var divToCheck = document.getElementById(id);
var ipAdress = divToCheck.getElementsByTagName('input');
var ipFrom = document.getElementById(id).childNodes[1].value;
var ipTo = document.getElementById(id).childNodes[3].value;
if(validIp.test(ipFrom)){
if(validIp.test(ipTo)){
if(ipFrom > ipTo){
alert("Invalid Ip Range");
} else {
alert("Valid Ip Range");
}
} else {
alert("Invalid Ip Address [To]");
}
} else {
alert("Invalid Ip Address [From]");
}
}
HTML
<form name="ipAddress">
<div id="ipRange">
<div id="ipRange1">
1. From: <input type="text" name="ipfrom" /> To: <input type="text" name="ipto" /><input type="button" onClick="validate('ipRange1');" value="Validate">
</div>
</div>
<input type="button" value="Add" onClick="addIpRange();"/>
</form>

Radio button with an "other" text box not inputting value properly using javascript

I'm creating a form using html form controls and javascript to help streamline some processes at work. I've temporarily put the form online here.
In one section of the form, I have a text box associated with a radio button. The other radio buttons in the section display their values properly when the "Display" button is hit at the bottom of the page, but the radio button with the text box does not. It seems that I'm not correctly assigning the value of the text box to the value of the radio button. What am I doing wrong?
Here's the javascript:
<script LANGUAGE="JavaScript" type="text/javascript">
function display() {
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
var radio_paymenttype_val = document.form2.paymenttype[i].value;
}
}
for (var i=0; i < document.form2.contracts.length; i++)
{
if (document.form2.contracts[i].checked)
{
var radio_contracts_val = document.form2.contracts[i].value;
}
}
DispWin = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600')
message = "<h2>Royalty Advance Payment Letter</h2>";
message += "<hr />";
message += "<span STYLE=\'font-family: Garamond\'>";
message += "<p>" + document.form2.agentfirstname.value + " " + document.form2.agentlastname.value + "<br />";
message += document.form2.agencyname.value + "<br />";
message += document.form2.agentaddress1.value + "<br />";
message += document.form2.agentaddress2.value + "<br />";
message += document.form2.agentcity.value + ", " + document.form2.agentstate.value + " " + document.form2.agentzip.value + "<br />";
message += document.form2.agentcountry.value + "<br />";
message += "</p>";
message += "<p>Dear " + document.form2.agentfirstname.value + ",</p>";
message += "<p>Please find enclosed a check in the amount of $";
message += document.form2.paymentamount.value + " representing the amount due upon ";
message += radio_paymenttype_val + " ";
message += document.form2.authorfirstname.value + " ";
message += document.form2.authorlastname.value + "'s <em>";
message += document.form2.booktitle.value + "</em>.";
message += radio_contracts_val + "</p>";
message += "<p>Regards,<br /><br /><br /><br />My Name<br />Associate Editor</p>";
message += "</span>";
DispWin.document.write(message);
}
</script>
And here's the HTML for that section:
<div class="required">
<fieldset>
<legend>Payment Type:</legend>
<label for="payment_sig" class="labelRadio"><input type="radio" name="paymenttype" id="payment_sig" class="inputRadio" value="signature for" /> Signature</label>
<label for="payment_danda" class="labelRadio"><input type="radio" name="paymenttype" id="payment_danda" class="inputRadio" value="delivery and acceptance of" /> Delivery & Acceptance</label>
<label for="payment_pub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pub" class="inputRadio" value="publication of" /> Publication</label>
<label for="payment_pbpub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pbpub" class="inputRadio" value="paperback publication of" /> Paperback Publication</label>
<label for="payment_otherlabel" class="labelRadio"><input type="radio" name="paymenttype" id="payment_otherlabel" class="inputRadio" onclick="this.form.payment_other.focus()" onfocus="this.form.payment_other.focus()" value="" checked="checked" /> Other:</label>
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" />
<small>Remember, this text will be in the middle of a sentence. This text should always end in "of" or "for."</small>
</fieldset>
</div>
Your first for loop goes through and finds the value of the correct radio selected, but in the case of "other" you're not going to have a value assigned. You need to determine when other is selected, then assign radio_paymenttype_val the value of the text box instead. Something to the effect of:
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
// assuming "other" is the only case where this radio's value property would be empty.
var radio_paymenttype_val = (document.form2.paymenttype[i].value != ''
? document.form2.paymenttype[i].value
: document.form2.payment_other.value);
}
}
Update
So excuse the delay (took your form field and ran with it). This is (I believe) what you're looking for. Some things to note:
I don't do any form validation. This is something you probably want to tinker with, and can be pretty simple. In the .click() event, just check something like the following (or you can get more elaborate):
if($('#agentfirstname').val()==''){
alert('Missing First Name');
return;
}
Also, I use something fairly new to jQuery, templates. This makes it easier than var+='html html'+var+'html'; (as you can witness in the <script> tag with the ID 'FormTemplate`).
Finally, I tested this on FF4, Chrome4 and IE8 and it should work, but let me know if it doesn't on whatever environment you use.
Anyways, here's the code, hope this helps!
Place inside <head> element of your document
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<Script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script type="text/javascript">
$(function(){
// bind to the "display" button ('.' means this is a class name reference)
$('.inputSubmit').click(function(e){
// build up the template values
var tmplData = [{
agentFirstName: $('#agentfirstname').val(),
agentLastName: $('#agentlastname').val(),
agencyName: $('#agencyname').val(),
agentAddr1: $('#agentaddress1').val(),
agentAddr2: $('#agentaddress2').val(),
agentCity: $('#agentcity').val(),
agentState: $('#agentstate').val(),
agentZip: $('#agentzip').val(),
paymentAmount: '$'+$('#paymentamount').val(),
paymentType: $('input[name="paymenttype"]:checked').val() != '' ? $('input[name="paymenttype"]:checked').val() : $('#payment_other').val(),
authorFirstName: $('#authorfirstname').val(),
authorLastName: $('#authorlastname').val(),
bookTitle: $('#booktitle').val(),
contracts: $('input[name="contracts"]:checked').val()
}];
// create the template
var template = $('#FormTemplate').template('letter');
// Create a fake div we can push the template to and pass off to popup
var tmplDiv = document.createElement('div');
$(tmplDiv).attr('id','TemplateDiv').css('display','none');
// Write the template and push it off
$.tmpl('letter', tmplData).appendTo(tmplDiv);
// create the window and populate it with the template
var hWindow = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600');
hWindow.document.write(tmplDiv.innerHTML);
// stop any further action
e.preventDefault();
});
});
</script>
Place inside <body> element of your document:
<script id="FormTemplate" type="text/x-jquery-tmpl">
<html>
<head>
<title>Letter</title>
</head>
<body>
<h2>Royalty Advance Payment Letter</h2>
<hr />
<span type="font-family:Garamond;">
<p>
${agentFirstName} ${agentLastName}<br />
${agencyName}<br />
${agentAddr1}<br />
${agentAddr2}<br />
${agentCity}, ${agentState} ${agentZip}<br />
</p>
<p>
Dear ${agentFirstName},
</p>
<p>
Please find enclosed a check in the amount of ${paymentAmount} representing the amount due upon ${paymentType}
${authorFirstName} ${authorLastName}'s <em>${bookTitle}</em>.
${contracts}
</p>
<p>
Regards,<br />
<br />
<br />
<br />
Margaret Maloney<br />
Associate Editor
</p>
</span>
</body>
</html>
</script>
Could you simply set a onblur() for the payment_other to set the radio option's value?
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" onblur="document.getElementById('payment_otherlabel').value=this.value;" />
Then if it is ever set, it will automatically copy the value into the radio option. Then when your Display() function is called, I would think the value would be set.
(Realized I missed the semi-colon at the end of the onblur="" statement.)
Have you tried this yet?

Categories

Resources