Using join() to create a HTML id? - javascript

I have 6 Hidden fields which are to hold a latitude and longitude for 3 different postcodes:
<input type="hidden" id="geo_lat1" name="geo_lat1">
<input type="hidden" id="geo_lon1" name="geo_lon1">
<input type="hidden" id="geo_lat2" name="geo_lat2">
<input type="hidden" id="geo_lon2" name="geo_lon2">
<input type="hidden" id="geo_lat3" name="geo_lat3">
<input type="hidden" id="geo_lon3" name="geo_lon3">
I also have the three input fields for the postcodes:
<input type="text" name="search_postcode1" id="search_postcode1">
<input type="text" name="search_postcode2" id="search_postcode2">
<input type="text" name="search_postcode3" id="search_postcode3">
The geocoding function I have works fine, but only for the first set of lat/longs. If I want to produce the lat/longs for the other two postcodes, I would have to copy and paste the geocoding function for each postcode, just changing the number at the end of the input name in the following line:
var sAddress1 =document.getElementById("search_postcode1").value ;
Instead of copying/pasting I want to use the same code but in a loop, which means changing the reference from search_postcode1 to search_postcode2 and search_postcode3
I know I can use join() to join data in an array and assign it to another variable like so:
var a = new Array("search_postcode","1");
var pcname = a.join(""); // pcname would be assigned "search_postcode1"
My question is how do I assign it so that it would appear in the line of code above rather than a value in a variable?
EDIT
I also need to assign it to the hidden fields using:
geo_lat1.value = loc[0];
geo_lon1.value = loc[1];
How do I change the '1's in this to a '2' and a '3' in a loop? It must be a different way to the getElementById("search_postcode" + "1") way?

You could do something like this:
for (var i = 1; i <= 3; i++) {
var address = document.getElementById('search_postcode' + i);
// Do something with address. Each time through the loop, it will
// reference the "i" search_postcode input, 1-3. Maybe something like:
var loc = geoCodePostCode(address.value);
document.getElementById('geo_lat' + i).value = loc[0];
document.getElementById('geo_long' + i).value = loc[1];
}

Related

replace String to number in loop

I want to create a fill in the blank quizz web site.
My problem is putting a different name="" value of all inputs.
So I create a function Who change a string giving into input.
But the problem is they have all the same name (inpName1).
What I want to do is giving them a diffrent names (inpName1,inpName2,inpName3...) so I can recuperate them later into DB
var i=0;
function MyFunction() {
var str = document.getElementById("myTextArea").value;
var res = str.replace(/#champ/g, "<input type='text' name='inpName"+ i++ +"'>");
document.getElementById("finalText").innerHTML = res;
}
Instead of inpName1, inpName2 etc use [] notation in name attribute:
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
In this case your values will be available on server via $_POST['inpName'] array.

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

javascript how to calculate values in dynamically added fields with multiple rows

I had one row with three fields: received, issue, balance
<input type="text" name="rcv" class="rcv"/>
<input type="text" name="issue" class="issue"/>
<input type="text" name="blnc" class="balance"/>
I calculated the balance for each row easily, but how do I calculate more than one row?
Each row has receive, issue and balance fields.
How do I calculate each row's balance field?
I tried like this for multiple row but it's not working:
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = $('.t_rcv').val();
var totalRtn = $('.t_rtn').val();
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
you need to parse The value of textbox as it returns string not int
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = parseInt($('.t_rcv').val()) || 0;
var totalRtn = parseInt($('.t_rtn').val()) || 0;
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
If your code is being run on document.ready it will only be applied to elements which exist at that point.
You'd be better with :
$(document).on('blur','.t_rtn, .t_rcv',function(){
var val = $(this).val();
...
});
try this..
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
In addition to parsing the string values into integers you also need to use the correct selectors for those input elements. t_rtn is not the right class name, for example. And if doing this in rows you will want to grab the correct element from the current row (you already did this correctly for the consume field)
Fixed html (Example.. I chose to use div with class name = row):
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
Fixed code:
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
I took the liberty of fixing some inconsistencies with the class names used. I tried to match them up to the variables for totalRcv and totalRtn so that now the balance shows as receipt minus return. If the user enters non-numeric data, it defaults the value to 0 before calculating.
Example fiddle here: http://jsfiddle.net/cp81g4nf/1/
I think problem is because you are subtracting 2 Strings. .val returns an String.
Convert them in number before subtracting like bellow
$('t_rtn').next('.consume').val((+totalRcv)-(+totalRtn));

getting wrong output on the second function

I have a code in which I have two functions:
In first function hardcode value is going
In second function value is going dynamically.
Here is my HTML
<input type="text" name="txt1" id="txt1">
<input type="text" name="txt2" id="txt2">
<input type="text" name="txt3" id="txt3">
<input type="submit" value= "ADD Value" onclick="Addhardcode(1,2,3)">
<input type="submit" value="Add" onclick ="Add()">
Script:
<script type="text/javascript">
<!--
function Addhardcode(a,b,c)
{
a+b+c;
alert(a+b+c);
}
function Add()
{
var x= document.getElementById("txt1")
var y= document.getElementById("txt2")
var z= document.getElementById("txt3")
var a=x.value;
var b=y.value;
var c=z.value;
Addhardcode(a,b,c);
}
//-->
</script>
While Clicking on button ADD Value I get right answer but, on clicking on button Add I am not getting right answer. If I pass 4 ,5& 6 in the textbox then the output come as 456 in place of 15. What am I doing wrong. If i have to make an validation on the text boxes that it take only numbers or it cannot be empty . then what can i do for that
The reason you are getting the concatenated answer is because JavaScript will see the passed arguments as strings. They are being passed as strings because they are pulled from the textbox's value property, which is a string.
This would be the equivalent of doing this:
alert('4'+'5'+'6'); // Gives '456'
To actually add the numbers, you need to convert them to integers first.
var a = parseInt(x.value);
var b = parseInt(y.value);
var c = parseInt(z.value);
When you currently call x.value it returns as a string, so the + operator will just be concatenating the values.
Use parseInt() to parse the values into integers.
var a = parseInt(x.value);
var b = parseInt(y.value);
var c = parseInt(z.value);
in your code a,b,c are considered as strings and so + is just appending them.
you have to convert them into integer like
var a= parseInt(x.value,10);
var b= parseInt(y.value,10);
var c= parseInt(z.value,10);
before passing on to function Addhardcode

Javascript function not returning a value

I have a javascript function that check for a value from a text box and the if the text box is not blank it outputs a statement. The text box take a numeric value, i want to include that numeric value that is output to html.
here is the html
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
and the Javascript
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").innerHTML; <---i want to pass the value of this box
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = mnthchk; <----passed to here
i cant get the value passed, it only shows blank, i can hardcode a value and will output fine, which is how the jsfiddle is currently http://jsfiddle.net/rn5HH/4/
thanks in advance
Input elements don't have child nodes, therefore innerHTML is blank. If you want to read their value, use the value property.
Your line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
Should be:
var mnthchk = document.getElementById("mdamountBox");
Then you can get the value of the text input like this:
var newmnthchk = mnthchk.value;
Working JS Fiddle here: http://jsfiddle.net/rn5HH/10/
use document.getElementById("mdamountBox").value
The problem here is you are trying to get the innerHtml, where you want the value. From your fiddle, just change this line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
...to this:
var mnthchk = document.getElementById("mdamountBox").value;
check below code :
HTML Code
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
Javascript Code
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").value;
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newmnthchk = '5';
newmnthchk = mnthchk;
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = newmnthchk;
}
}
This is working code perfectly checked on Fiddle
,you need to get DOM value using
var mnthchk = document.getElementById("mdamountBox").value;

Categories

Resources