How to make an input format for coordinate? - javascript

I'm trying to make an input for coordinate.
I use this script to add comma. But, it is adding comma every two char. I want it only add comma before the last two char.
$('.isCoor').on('keyup', function(){
$(this).val(function(index, value) {
var val_koor = value.replace(/\D/g, "").replace(/\B(?=(\d{2})+(?!\d))/g, ",")
return val_koor;
});
});

You can add a simple logic instead of using regular expression like this:
$('.isCoor').on('keyup', function(){
$(this).val(function(index, value) {
var val_koor = value;
if(value.length > 2){
value = value.replace(/,/g,'');
val_koor = value.substr(0,value.length-2)+ ',' + value.substr(value.length-2, value.length);
}
return val_koor;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='isCoor' type='text' />

Related

javascript capture every value in a div

I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"

loop elements by data attribute and replace values

I'm trying to loop through all elements that contain a certain data attribute and then replace/remove certain characters.
//replace chars put in by money mask since model is double
$("input[data-input-mask='money']").each(function() {
alert(this.value); // shows: $ 1,000
alert('test$ ,'.replace('$ ', '').replace(',', '')); //shows: test
this.value = this.value.replace('$ ', '').replace(',', '');
alert(this.value); //shows: $ 1,000
});
this.value is still the original value. What might I be doing wrong here?
Use .localeString()
UPDATE
After rereading the OP, I realize the opposite is desired. That's still easy. Instead of using a mask, use localString(). Then it's a matter of not using localestring() when you processing the values.
SNIPPET
$("input[data-input-mask='money']").each(function() {
var cash = parseFloat(this.value);
var green = cash.toLocaleString('en-EN', { style: 'currency', currency: 'USD' });
alert(green);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-input-mask='money' value="623.23">
<input data-input-mask='money' value="20199">
<input data-input-mask='money' value="">
You can loop through each element and replace it like this.
<script>
$(document).ready(function(e) {
//Retrieve all text of amount di;
$.each( $('.amount'), function(){
var unique_id = $(this).text();
//check if any price is match to FREE THEN replace it with NOT FREE
if(unique_id=='FREE'){
$(this).text("NOT FREE");
}
});
});
</script>

Add/Remove value to input on click

i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/
I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/
I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example

fill the input type hidden from selected multiple option on jquery

I have a input that have type like this:
<input class="emailSend" name="emailSend" type="hidden">
Then I have a multiple select option like this
<div class="controls">
<select id="email" multiple data-rel="chosen" class="input-xlarge" name="email[]">
<?php
foreach ($atasan as $data) {
echo "<option value='" . $data['email'] . "'>" . $data['email'] . "</option>";
}
?>
</select>
</div>
My problem is, I want to fill that hidden input from the option that selected from multiple select option. So let say, the selected option is 'email1', 'email2', 'email3' then would be affected to hidden type like this 'email1, email2, email3'.
I have try this for 3 hour in jquery and I am stuck. My code is like this.
$("#email").change(function() {
var elements = $("#email option:selected").length;
var input = $(".emailSend");
$(".emailSend").html("");
$.each($("#email option:selected"), function(/*index, element*/) {
input.val(input.val() + $(this).html() + ", ");
if (index < elements - 1) {
//code to remove last comma
//any idea ?
}
});
});
So appreciated for the help...
EDIT Here is the fiddle :JSFIDDLE
Updated FIDDLE now that I see what you meant by looking at the fiddle you made.
this is actually all you need to do...
Updated to include spaces between the addresses!
$("#email").on('change', function() {
var thisval = $(this).val() + '';
var myarr = thisval.split(',');
var newval = '';
myarr.forEach(function(i,v) {
newval += i + ' , ';
});
newval = newval.slice(0, newval.length - 3);
$("#emailsend").val(newval);
});
Commented Version (for learning and stuff)
$("#email").on('change', function() {
//the extra space at the end is to typecast to string
var thisval = $(this).val() + '';
//takes string of comma separated values and puts them
//into an array
var myarr = thisval.split(',');
//Initialize a new string variable and loop through
//the array we just created with MDN's forEach()
var newval = '';
myarr.forEach(function(i,v) {
//add to the string through each iteration,
//including comma with spaces
newval += i + ' , ';
});
//use .slice() to trim three characters off the
//end of the final string. (strip final comma)
newval = newval.slice(0, newval.length - 3);
//and last but not least, assign our newly created
//and properly formatted string to our input element.
$("#emailsend").val(newval);
});

Get values from TEXTAREA

<textarea name="test" id="text">
text
area
one one
two
break above
last
</textarea>
<span id="getvalues">get values</span>
$("#getvalues").click(function(){
})
How can i get all values from this textarea from each line to javascript array?
This should:
ignore whitespace - trim
ignore white break
Next i would like make:
$.each(textareavalues, function(index, value) {
console.log('#' + value + '#');
});
This should show me:
#text#
#area#
#one one#
#two#
#break above#
#last#
LIVE EXAMPLE: http://jsfiddle.net/BW8Z2/1/
When you say "ignore white space - trim", you mean "ignore leading and trailing white space on a line, but keep internal white space"? And "ignore white break" means "ignore lines with just white space"?
Something like this:
$("#getvalues").click(function(){
var lines = $("#text").val()
.replace(/\n\s*\n/g,"\n")
.replace(/^\s+|\s+$/gm,"")
.split(/\n/);
$.each(lines, function(i, val) {
console.log("#" + val + "#");
});
})
$("#getvalues").click(function(){
var $textareavalues = $("#text").val();
var x = $textareavalues.split('\n');
$.each(x, function(index, value) {
var text = $.trim(value);
if(text !== "")
console.log('#' + text + '#');
});
});
This will get you started:
var textareavalues = $('textarea').val().split('\n');
you can find how to trim strings and how to exclude empty items in an array in JavaScript from other questions on StackOverflow.

Categories

Resources