Adding Arrays Index number to labels - javascript

var arr = [];
$('.inp').click(function(){
function arrcall() {
$.each(arr, function(key, value) {
alert('Array Key is: ' + key + ' \n Array Key value is: ' + value);
});
}
var id = $(this).attr('id');
var value = $(this).val();
if(value == 'empty') {
this.value = id + 'ON';
value = $(this).val();
arr.push(value);
arrcall();
$('.txt').val(arr.join(','));
return false;
}
if(value == id + 'ON') {
arr.splice(arr.indexOf(value), 1)
this.value = id + 'OFF';
value = $(this).val();
arr.push(value);
arrcall();
$('.txt').val(arr.join(','));
return false;
}
if(value == id + 'OFF') {
arr.splice(arr.indexOf(value), 1)
this.value = 'empty';
value = $(this).val();
arrcall();
$('.txt').val(arr.join(','));
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class='txt' type='input'>
<label>X</label>
<input class='inp' id='x' type='button' value='empty'>
<label>Y</label>
<input class='inp' id='y' type='button' value='empty'>
<label>Z</label>
<input class='inp' id='z' type='button' value='empty'>
</form>
I'm trying here to change the value of the input and add it to the .txt input, Now my problem is nubmering the lables by its array key
For example
If i clicked Z button then X button then Y button and turned them to ON or OFF i want them to have their index key number + 1 so the label would change to be
X-2[xON] Y-3[yON] Z-1[zON]
and if i turned one of them to empty again, the numbers get ordered correctly again by the index.
so if i made Z button OFF the buttons would be
X-1[xON] Y-2[yON] Z[empty]

After you've loaded the new array, you can loop through all inputs an search its position in the array, to modify the label. Try this...
var arr = [];
function arrcall() {
$.each(arr, function(key, value) {
alert('Array Key is: ' + key + ' \n Array Key value is: ' + value);
});
}
$('input.inp').click(function(e) {
e.preventDefault();
var id = $(this).attr('id');
var value = this.value;
var position = arr.indexOf(value);
if (value == 'empty') {
this.value = id+'ON';
arr.push(this.value);
}
else if (value == id+'ON') {
this.value = id+'OFF';
arr[position] = this.value;
}
else if (value == id+'OFF') {
this.value = 'empty';
arr.splice(position,1);
}
arrcall();
$('input.txt').val(arr.join(','));
// Loop through all your inputs, search its value and modify label.
$('input.inp').each(function() {
var pos = 0;
if ((pos = arr.indexOf($(this).val())) >= 0)
$(this).prev('label').text($(this).attr('id')+'-'+(pos+1));
else
$(this).prev('label').text($(this).attr('id'));
});
})
I hope it helps.

Related

Textbox Maxlength Issue for amount field

I have a situation having a textbox having 15 as a max length property. That field works as a amount field. it is working correctly in normal cases.
lets say if i enter 11234567890.99 this amount in textbox it displays it as 112,34,567,890.99 which is expected.
But, if i copy & paste 112,34,567,890.99 amount in textbox last two digits gets truncated because the length gets out of bound.
Is there any ways to change this without modifying the exact behavior? allowing to paste whole 112,34,567,890.99 amount.
$(document).on("focusout","#txtformate1",(function () {
if (this.value != null && this.value != "") {
$((this.parentElement).nextElementSibling).hide()
}
else{
$((this.parentElement).nextElementSibling).show()
}
}));
$(document).on('keyup', '.Amt', function () {
var val = $(this).val();
val = val.replace(/([~!#$%^&*()_+=`{}\[\]\|\\:;'<>,\/? ])+/g, '');
if(isNaN(val) && val!="-")
{
val="";
}
$(this).val(val);
/*if (isNaN(val)) {
val = val.replace(/(?!^)-/g, '');
if(val.indexOf("-")>-1)
{
val = val.replace(/[`*\/]/g, '');
}
else{val = val.replace(/[^0-9\.]/g, '');}
if (val.split('.').length > 2)
{
val = val.replace(/\.+$/, "");
}
else if(val==".")
{
val ="";
}
}*/
});
$(document).on('focusout', '.Amt', function () {
var val = $(this).val();
val = val.replace(/(?!^)-/g, '');
if(isNaN(val) && val.indexOf(',')>-1){
val=$(this).val();
}
if (val == "0.00"){
val="";
}
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control Amt" id="txtformate1" maxlength="15" />`

html Input type number with Thousand Separator

i want to add thousand separator on keyup event in input type number
but this work just in 6 character, if more than 6 character, value on input has reseted
this my short code
<input type="number" id="tanpa-rupiah" step="any">
var dengan_rupiah = document.getElementById('dengan-rupiah');
dengan_rupiah.addEventListener('keyup', function(e)
{
dengan_rupiah.value = formatRupiah(this.value, 'Rp. ');
});
function formatRupiah(bilangan, prefix)
{
var number_string = bilangan.replace(/[^,\d]/g, '').toString(),
split = number_string.split(','),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{1,3}/gi);
if (ribuan) {
separator = sisa ? '.' : '';
rupiah += separator + ribuan.join('.');
}
rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
this my fiddle https://jsfiddle.net/C2heg/4619/
This might suit you. On keydown prevent the default action if it is not a number key. On keyup, parse the value and update it. Use the data- attributes to store and get the original value.
var elem = document.getElementById("num");
elem.addEventListener("keydown",function(event){
var key = event.which;
if((key<48 || key>57) && key != 8) event.preventDefault();
});
elem.addEventListener("keyup",function(event){
var value = this.value.replace(/,/g,"");
this.dataset.currentValue=parseInt(value);
var caret = value.length-1;
while((caret-3)>-1)
{
caret -= 3;
value = value.split('');
value.splice(caret+1,0,",");
value = value.join('');
}
this.value = value;
});
function showValue()
{
console.log(document.getElementById("num").dataset.currentValue);
}
<input type="text" id="num" maxlength="30">
<button onclick="showValue()">Get Value</button>
Ok I have posted answer below. I have added limit of 20 numbers. You can change it as per your need.
You can use Number.toLocaleString() for this purpose.
Below is working example:
// When ready.
$(function() {
var extra = 0;
var $input = $("#amount");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = $(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="amount" name="amount" type="text" maxlength="20" />
change your the input type equal to "text" then its work
<input type="text" id="tanpa-rupiah" step="any">
checkout jsfiddle

JavaScript .click doesnt work in IE 11

I have been trying to get this code working for multi select option sets for dynamic crm. My problem here is that this code works effortlessly in Chrome, does exactly what I want it to but in IE the .click event returns false no matter what, if the check boxes are checked or unchecked.
All this code does is take a option set and converts it to a multi select list and sets value into the two fields "l1s_trainingmodulesvalues" holds the value of the option selected and "l1s_trainingmodules" holds the label of the option selected.
Can some one have a look at what I have been doing wrong.
<html><head>
<title></title>
<script src="../WebResources/new_jquery3.1.1.min.js" type="text/javascript"></script>
<script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
<script type="text/javascript">
// function will be called when web resource is loaded on Form.
$(document).ready(function ()
{
ConvertDropDownToCheckBoxList();
});
//Coverts option list to checkbox list.
function ConvertDropDownToCheckBoxList()
{
var dropdownOptions = parent.Xrm.Page.getAttribute("l1s_trainingmodulesoptionset").getOptions();
var selectedValue = parent.Xrm.Page.getAttribute("l1s_trainingmodulesvalues").getValue();
$(dropdownOptions).each(function (i, e)
{
var rText = $(this)[0].text;
var rvalue = $(this)[0].value;
var isChecked = false;
if (rText != '')
{
if (selectedValue != null && selectedValue.indexOf(rvalue) != -1)
isChecked = true;
var checkbox = "<label><input type=\"checkbox\" name =\"r\">" + rText + "<br></label>"
$(checkbox)
.attr("value", rvalue)
.attr("checked", isChecked)
.attr("id", "id" + rvalue)
.on('click',function ()
{
//To Set Picklist Select Values
var selectedOption = parent.Xrm.Page.getAttribute("l1s_trainingmodulesvalues").getValue();
alert($(this).is(':checked')); /*** This value always returns false in IE but in Chrome it works perfectly*/**
if ($(this).is(':checked'))
{
if (selectedOption == null)
selectedOption = rvalue+"";
else
selectedOption = selectedOption + "," + rvalue
}
else
{
var tempSelected = rvalue + ",";
if (selectedOption != null)
{
if (selectedOption.indexOf(tempSelected) != -1)
selectedOption = selectedOption.replace(tempSelected, "");
else
selectedOption = selectedOption.replace(rvalue, "")
}
}
//alert(rvalue);
parent.Xrm.Page.getAttribute("l1s_trainingmodulesvalues").setValue(selectedOption);
//To Set Picklist Select Text
var selectedYear = parent.Xrm.Page.getAttribute("l1s_trainingmodules").getValue();
if ($(this).is(':checked'))
{
if (selectedYear == null)
selectedYear = rText+"";
else
selectedYear = selectedYear + "," + rText
}
else
{
var tempSelectedtext = rText + ",";
if (selectedYear != null)
{
if (selectedYear.indexOf(tempSelectedtext) != -1)
selectedYear = selectedYear.replace(tempSelectedtext, "");
else
selectedYear = selectedYear.replace(rText, "");
}
}
//alert(selectedYear);
parent.Xrm.Page.getAttribute("l1s_trainingmodules").setValue(selectedYear);
})
.appendTo(checkboxList);
}
});
}
</script>
<meta charset="utf-8">
</head><body style="-ms-word-wrap: break-word;"><form><div id="checkboxList">
</div></form>
</body></html>
Your checkbox variable does not refer to a checkbox element. It's a label (var checkbox = "<label><input type=\"checkbox\" name =\"r\">" + rText + "<br></label>"), which does not have a checked state.
Inside your click handler, change
if ($(this).is(':checked'))
to
if ($(this).find('input').is(':checked'))

How to detect whether an html input object is a button or not?

I am working on trying to pull the inputs from a form, excluding buttons, but not radio buttons. I am getting my inputs via the .find() method of the form element. I have the inputs, but am unable to restrict them to just inputs other than the submit button or a similar button. I have tried the jquery .is(), .type(), both with no luck any suggestions/ references would be helpful as I have not found anything to help as of yet. Here is the code I am using to pull the forms.
var inputs = formList.find(":input");
if (inputs ? inputs.length > 0 : false)
{
for(j = 0;j < inputs.length; j++)
{
console.log("input: " + inputs[j]);
if (inputs[j].name != "")
{
webForms.push({"inputName": inputs[j].name});
}else if (inputs[j].id != "")
{
webForms.push({"inputName": inputs[j].id});
}
}
}
Like I said, I have tried the .is and .type with no luck. Here is an example of how I was using .is()
var formList = $("form");
var formName = $("form").attr("name");
if (formList != null ? formList.length > 0 : false)
{
if (formList.length < 2)
{
if (formList.attr("name") ? formList.attr("name") != "" : false)
{
//alert("form name is not null");
//alert("form name: " + formList.attr("name"));
var webForms = [];
//alert("formList name: " + formList[i]);
var inputs = formList.find(":input");
if (inputs ? inputs.length > 0 : false)
{
for(j = 0;j < inputs.length; j++)
{
console.log("input: " + inputs[j]);
if (inputs[j].name != "")
{
if(inputs[j].is(":button"))
{
console.log(inputs[j].name + " is a button");
}
webForms.push({"inputName": inputs[j].name});
}else if (inputs[j].id != "")
{
if(inputs[j].is(":button"))
{
console.log(inputs[j].name + " is a button");
}
webForms.push({"inputName": inputs[j].id});
}
}
}
//alert(JSON.stringify(webForms));
jsonForm.forms[jsonForm.forms.length - 1].name = formList.attr("name");
//alert("json form name: " + JSON.stringify(jsonForm));
jsonForm.forms[jsonForm.forms.length - 1].inputs = webForms;
//alert("name: " + jsonForm.forms[jsonForm.forms.length - 1].name);
}
}
Any help here is appreciated.
You can use the following code to get the input elements which aren't buttons or inputs with a type attribute of "submit".
var inputs = formList.find(':input:not(button, [type="submit"])');
Here is a live demonstration.
the problem is inputs[i] returns a dom element reference not a jQuery wrapper object so its does not have the is method you can use
inputs.eq(i).is(':button')
I would recommend to use .each() loop to iterate over the jQuery object than using a loop
var inputs = formList.find(":input");
inputs.each(function () {
var $input = $(this);
console.log("input: " + this);
if (this.name != "") {
if ($input.is(":button")) {
console.log(this.name + " is a button");
}
webForms.push({
"inputName": this.name
});
} else if (this.id != "") {
if ($input.is(":button")) {
console.log(this.name + " is a button");
}
webForms.push({
"inputName": this.id
});
}
})
This could even be simplified to
var inputs = formList.find(":input");
inputs.each(function () {
var $input = $(this);
console.log("input: " + this);
var name = this.name || this.id;
if (name != "") {
if ($input.is(":button")) {
console.log(name + " is a button");
}
webForms.push({
"inputName": name
});
}
})

Maximum allowed value for <input type="text"/>

I have this input field:
<input type="text"/>
How can I allow entering only a number that is not greater than some predefined value, like for example 10, so every attempt to enter a number greater than 10 won't be allowed?
Javascript
function createValidator(element) {
return function() {
var min = parseInt(element.getAttribute("min")) || 0;
var max = parseInt(element.getAttribute("max")) || 0;
var value = parseInt(element.value) || min;
element.value = value; // make sure we got an int
if (value < min) element.value = min;
if (value > max) element.value = max;
}
}
var elm = document.body.querySelector("input[type=number]");
elm.onkeyup = createValidator(elm);
HTML
<input type="number" min="0" max="10"></input>
I haven't tested it, but I think it should work.
Convert the value to a number immediately, then compare it to a maximum value:
window.onload = function () {
var textbox = document.getElementById("text1");
var maxVal = 10;
addEvent(textbox, "keyup", function () {
var thisVal = +this.value;
this.className = this.className.replace(" input-error ", "");
if (isNaN(thisVal) || thisVal > maxVal) {
this.className += " input-error ";
// Invalid input
}
});
};
function addEvent(element, event, callback) {
if (element.addEventListener) {
element.addEventListener(event, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + event, callback);
} else {
element["on" + event] = callback;
}
}
DEMO: http://jsfiddle.net/jBFHn/
As you type, if the value isn't a number or the value is greater than the maximum, the "input-error" class is added to the element. You can take out the whole class changing, and put in your own stuff.
This is how I used this property in my project.
<script>
function integerInRange(value, min, max, name) {
if(value < min || value > max)
{
document.getElementById(name).value = "100";
alert("Write here your message");
}
}
</script>
And my input like this
<input type="text" id="yyy" name="xxx" onkeyup="integerInRange(this.value, 0, 100, "yyy")" />
If you using bootstrap you can use alert window!
function integerInRange(value, min, max, name) {
if(value < min || value > max)
{
document.getElementById(name).value = "100";
$.pnotify({ title: 'UYARI', text: 'Girilen değer ' + min + ' ile ' + max + ' arasında olmalıdır.', type: 'error' });
$(".ui-pnotify-history-container").remove();
}
}

Categories

Resources