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>
Related
I'm trying to add another input field as the user clicks on the "add another field" button.
Although it works perfectly, there's this minor issue as the name in the input field supposed to add +1 to the earlier name value in the additional field, which returns as a string instead of int.
Upon clicking on "Add Additional field" a new input appears with name value as name="asin1" and further on goes as name="asin11" & name="asin111". How can I add it up as a count?
And on the other hand, how can I know on the backend page how many fields were actually user added using PHP.
Any help is greatly appreciated.
$('.extra-fields-customer').click(function() {
$('.customer_records').clone().appendTo('.customer_records_dynamic');
$('.customer_records_dynamic .customer_records').addClass('single remove');
$('.single .extra-fields-customer').remove();
$('.single').append('Remove Fields');
$('.customer_records_dynamic > .single').attr("class", "remove");
$('.customer_records_dynamic input').each(function() {
var count = 1;
var fieldname = $(this).attr("name");
$(this).attr('name', fieldname + count);
count++;
});
});
$(document).on('click', '.remove-field', function(e) {
$(this).parent('.remove').remove();
e.preventDefault();
});
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<div class="customer_records">
<input type="text" class="input" id="fname" name="asin" required placeholder="ASIN/FSIN or Wesite Link of the product">
<a class="extra-fields-customer button" href="#">Add Another Field</a>
</div>
<br>
<div class="customer_records_dynamic"></div>
First solution:
defined count & fieldname out of function .each
$('.extra-fields-customer').click(function() {
$('.customer_records').clone().appendTo('.customer_records_dynamic');
$('.customer_records_dynamic .customer_records').addClass('single remove');
$('.single .extra-fields-customer').remove();
$('.single').append('Remove Fields');
$('.customer_records_dynamic > .single').attr("class", "remove");
var count = 1;
var fieldname='asin';
$('.customer_records_dynamic input').each(function() {
$(this).attr('name', fieldname + count);
count++;
});
});
$(document).on('click', '.remove-field', function(e) {
$(this).parent('.remove').remove();
e.preventDefault();
});
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<div class="customer_records">
<input type="text" class="input" id="fname" name="asin" required placeholder="ASIN/FSIN or Wesite Link of the product">
<a class="extra-fields-customer button" href="#">Add Another Field</a>
</div>
<br>
<div class="customer_records_dynamic"></div>
Another solution:
edit input field Like:
<input type="text" class="input" id="fname" name="asin[]" required placeholder="ASIN/FSIN or Wesite Link of the product">
now you don't need to count your inputs and use this.
$('.customer_records_dynamic input').each(function() {
$(this).attr('name', fieldname + count);
count++;
});
just edit your back-end and receive input data asin as Array
Since you are using PHP on the backend, you really do not need to keep track of the names like you would for a set static number of fields.
Have a look at this:
<input type="text" name="asin[]" />
<input type="text" name="asin[]" />
<input type="text" name="asin[]" />
// php will convert it to an array in the backend as $_POST['asin']
In your PHP you'll want something like:
<?php
foreach ($_POST['asin'] as $asinInputValue) {
// iterate over each input's value
echo $asinInputValue . "<br>";
}
In my app I have multiple divs which look like (The divs are created dynamically):
<div class="form-group clearfix">
<div class="form-group first-name">
<input type="text" id="firstName0" class="signup-input firstName required" name="first[0]" placeholder="">
</div>
<div class="form-group last-name">
<input type="text" id="lastName0" class="signup-input lastName" name="last[0]" placeholder="optional">
</div>
<div class="form-group email">
<input type="text" data-index="0" id="inputMail0" class="signup-input mail" name="email[0]" placeholder="e.g. example#url.com" aria-invalid="true">
<span class="common-sprite sign-up-cross first"></span>
</div>
</div>
The names are dynamically generated according to the index (For example the are email[1], email[2].....).
I have a button which should be disabled in case the field of the first name is not empty and the field of the email is empty and the span hasn't a class of disNone.
How should I disable the button according to above condition?
If I understand you correctly, you want to disable the button if all of the following conditions are met:-
First name field is NOT empty - $('#firstName0').val() != ''
Email field IS empty - $('#inputMail0').val() == ''
Span does NOT have class of disNone - !$('span').hasClass('disNone')
So I would check that condition this way by wrapping it in a listener on the keyup event upon the form:
$('.form-group').on('keyup', function () {
console.log('keyup');
if ($('#firstName0').val() !== '' && $('#inputMail0').val() === '' && !$('.email span').hasClass('disNone')) {
//Now do whatever with your button.
$('.mybutton').prop('disabled', true);
} else {
$('.mybutton').prop('disabled', false);
}
});
Demo: http://jsfiddle.net/ajj87Lg3/
Hope this condition works out for you.
Store the jQuery objects in variables and use that variables instead, which is a much better way to do it.
$(function(){
var firstName = $('#firstName0').val();
var inputMail = $('#inputMail0').val();
var checkClass = $('span').hasClass('disNone');
if( firstName!=='' && inputMail==='' && !checkClass ) {
$('button').attr('disabled','disabled'); //in the fiddle you would see an alert, you just have to replace that code with this one
}
});
EDIT: If your DIVS are being generated dynamically you can use the each() jquery function to loop through them.
$(function(){
$('#mainDiv').children('div').each(function(index,element){
var nameDiv = $(element).find(":nth-child(1)");
var firstName = $(nameDiv).find('input').val();
var emailDiv = $(element).find(":nth-child(3)");
var inputMail = $(emailDiv).find('input').val();
var spanElem = $(emailDiv).find("span");
var checkClass = $(spanElem).hasClass('disNone');
if(firstName!=='' && inputMail==='' && !checkClass){
$('button').attr('disabled','disabled');
//in the fiddle you would see a console.log('hi'), you just have to replace that code with this one for whatever button you want to disable
}
});
});
Checkout the FIDDLE LINK
In the fiddle I have left out one SPAN tag with class disNone and other SPAN tag without class disNone. So only once the condition executes
I have a forms which allows multiple steps to be submitted. When a user clicks "add step" another textarea appears. I am using CKeditor. It works great of the first iteration, but on all subsequent ones, it shows a standard text area. Here is my code:
<form method="post" action="process_project.php">
<b>Steps for your project:</b>
<div> </div>
Step 1
<div id="divWho">
<textarea name="projSteps[]" class="steps" id="1" rows="10" cols="60"></textarea>
</div>
<div> </div>
<input type="button" value="Add project step" onClick="addTextArea();">
<input type="submit" name="submit" value="submit" />
</form>
<script type="text/javascript">
var counter = 1;
var limit = 11;
function addTextArea() {
if (counter == limit-1) {
alert("You have reached the limit of adding " + counter + " project steps");
return false;
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Step " + (counter + 1) + " <br><textarea name='projSteps[]' id=counter rows='10' cols='60'>";
document.getElementById('divWho').appendChild(newdiv);
counter++
return true;
}
}
</script>
<script> CKEDITOR.replace('1');</script>
How can I make each new dynamically created text areas also use CKeditor? I have been working on this for hours and I am stumped.
I think you need to move CKEDITOR.replace('1'); inside the addTextArea() method enclosed in the else block before the return statement.
And also if you hard code the replace parameter to '1', it will only convert the first instance of textarea with id 1 to CKEditor and ignore others. Generate an Id dynamically and pass it to repalce method. Something like below,
var step = 'step'+counter;
div = <textarea name='projSteps[]' id=step rows='10' cols='60'>;
CKEDITOR.replace(step);
I haven't written the second step completely, I guess you can modify it as you need.
I'm working on a similar functionality and this approach works for me.
use like this.
<textarea class="ckeditor" name="abc1"</textarea>
and in JS add this
CKEDITOR.replaceAll( 'ckeditor' );
I hope it will work for all the textareas.
Right now my code is very "hard-coded" and repetitive. I'd like to know if there is a cleaner way to do the following. Ideally, I want to iterate through my forms fields with a loop and calculate the results with one statement, but I'm struggling to figure out how best to do so.
Summary: I have ten form fields, each with a distinct decimal value that a user may or may not supply. When the user hits submit, it should add the value in the input field with a value being displayed on the current HTML page, then insert into the DB.
First, I grab that value from the form input field and convert it into a number with two decimal places. I then grab the current total from the HTML and add the two numbers together. After that I inject that total back into the form input field so that it can be stored in $_POST and inserted into a database.
How can I make my code more DRY (ie, Don't Repeat Yourself)? Below are just two examples but they are exactly the same except for the element calls:
var subtotal = Number($("#housing").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-housing').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#housing').val(total);
var subtotal = Number($("#utilities").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-utilities').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#utilities').val(total);
I would like to iterate through my input fields like so, but I'm trying to figure out how I could display the logic inside:
var input = $('.form-expenses :input');
input.each(function() {
// Insert switch statement here?? Some other construct??
});
HTML: (Uses Bootstrap 3 classes)
FORM:
<form class="form-expenses form-horizontal" role="form" method="post" action="/profile/update">
<div class="form-group">
<label for="housing" class="control-label col-sm-3">Housing</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="housing" id="housing" />
</div>
</div>
<div class="form-group">
<label for="utilities" class="control-label col-sm-3">Utilities</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="utilities" id="utilities" />
</div>
</div>
...
<button class="btn btn-lg btn-primary btn-block" id="update-expenses" type="submit"> Update</button>
</form>
OUTPUT:
<tr>
<td>Housing</td>
<td id="output-housing">$<?php echo $total['housing']?></td>
</tr>
<tr>
<td>Utilities</td>
<td id="output-utilities">$<?php echo $total['utilities']?></td>
</tr>
Something like this should work. Assumes the same prefixing relationship of output/input ID's
$(function() {
$('form.form-expenses').submit(function() {
updateValues();
return false/* prevent submit for demo only*/
})
})
function updateValues(){
$('.form-expenses :input').not('#update-expenses').each(function(){
var $input=$(this), inputId=this.id;
var curr=$('#output-'+inputId).text().replace("$", "");
$input.val(function(i,val){
return (1*(val ||0) + 1*curr).toFixed(2);
})
});
}
DEMO
From a UI perspective, this seems very counter intuitive to change values that user just input.
To create ajax data object instead of updating the display values:
function getAjaxData(){
var ajaxData={}
$('.form-expenses :input').not('#update-expenses').each(function(){
var $input=$(this), inputId=this.id;
var curr=$('#output-'+inputId).text().replace("$", "");
ajaxData[this.name] =(1*(val ||0) + 1*curr).toFixed(2);
});
return ajaxData
}
/* in submit handler*/
$.post('path/to/server', getAjaxData(), function(response){/*do something with reponse*/})
"if I allow a user to add/remove fields, then this could get a bit sticky"
In that case, give your fields a class name. As long as that exists on added fields, they will all be calculated.
<input type="text" class="form-control calculate-me" name="housing" id="housing" />
And iterate though all, using their ids as a reference
$(".calculate-me").each(function(){
var ref=this.id;
var subtotal = Number($("#" + ref).val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-' + ref).html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#' + ref).val(total);
});
I have a form with a bunch of inputs. Sometimes the form will have 1 input and sometimes up to 10 inputs. When someone fills out each input I want a tag field at the bottom to be populated also. Right now I have it working but only with a set number of inputs. (3 at the moment).
Im trying to figure out how to make it work regardless of how many inputs there are on the page.
HTML
Input1 <input id="input1" name="input1" type="text" value="" />
<br/>
Input2 <input id="input2" name="input2" type="text" value="" />
<br/>
Input3 <input id="input3" name="input3" type="text" value="" />
<br/>
<p>List of inputed text</p>
<span id="allInputs"></span>
Jquery
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#allInputs").text(inputArray.join(' '));
});
A nice to have also would be putting them into another input instead of a span and adding a comma after each one except for the last one.
I know Im probably missing something very simple here.
In your example you are only allowing for 3 inputs as you have 3 input boxes, when any of those input boxes change your tags are then being transferred to the span.
Now it sounds like you wish to allow for multiple entries regardless of how many inputs. You could try something simple such as the below fiddle.
http://jsfiddle.net/K2g4z/
Html:
<div>
<strong>Enter your tag and click add</strong>
<br/>
<input type="text" id="tagEntry" />
<button id="tagAdd">Add</button>
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
Javascript:
var tags = [];
$(function() {
$('#tagAdd').click(function(){
//get the tag value and trim the spaces
var tVal = $('#tagEntry').val().trim();
if(tVal == '')
return;
//reset the entry box
$('#tagEntry').val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
UPDATE:
The JSFiddle link http://jsfiddle.net/K2g4z/1/ now supports using multiple inputs of as many as you need. To achieve this instead of selecting on element ID we bind to a class name. Given the following Html.
<div>
<strong>Enter your tag and click add</strong>
<br/>
<strong>Tag 1</strong>
<input type="text" id="tagEntry" class="tagEntry" />
<br/>
<strong>Tag 2</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 3</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 4</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 5</strong>
<input type="text" class="tagEntry" />
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
All the tag input boxes have a class of tagEntry now this class will become our selector. With the following JS we can bind the blur event to every tag that has a class of tagEntry. This will now update the tags box every time any of the inputs changed.
var tags = [];
$(function() {
$('.tagEntry').blur(function(){
//get the tag value and trim the spaces
var tVal = $(this).val().trim();
if(tVal == '')
return;
//reset the entry box
$(this).val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
As you can see our handler binds to all the inputs, as any of the inputs receives the blur event the method of extracting the tags is executed.
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#masterinput").val(inputArray.join(' '));
});
You probably want to narrow the selector so it isn't selecting all text inputs on the page.
var inputs$ = $("input:text").change(function () {
var inputArray = [];
$.each(inputs$, function(i, v) {
inputArray.push($(v).val());
}
$("#allInputs").text(inputArray.join(' '));
});
Here you go:
var str = "";
$("input[type=text]").change(function () {
$("input[type=text]").each(function(){
str += $(this).val()+",";
};
});
$("#allInputs").html(str);