On keypress event, how do I change a ',' to a '~' - javascript

I have to prevent Coldfusion's default list delimiter ',' from being entered into a form input array. I am new to using javascript for validation purposes, and have never tried to switch out the values someone is typing in. How can I snag a comma, and replace it with a tilda?
Javascript i've tried so far:
$(document).ready(function(event){
var regExComma = /,/;
$("[name='name[]']").live("keypress",function(event){
// i know i could check the numerical value, i feel this requirement can get more added to it and I would like to just change the regEx accordingly.
if(regExComma.test(String.fromCharCode(event.which)){
//it was a ',' switch it to '~'
event.which = 126;
}
});
// added to show that the 'name' input form array is the only input that cares about the ','
var regExDig = /[\d]/
$("[name=min[]],[name=max[]]").live(keypress, function(event){
if(!regExDig .test(String.fromCharCode(event.which)){
event.preventDefault();
$("#cfocFormMessages").trigger("updateMessages", {"url":"components.cfc/CFOC.cfc", "data":{"more":"stuff"}});
}
});
});
cfml / html involved:
<form action="components/CatagoryService.cfc?method=saveVersion">
<input id="version" name="version" type="text">
<!--- .. more inputs ..--->
<table id="table">
<thead><tr><th>name col</th>
<th>min col</th>
<th>max col</th>
<th>edit</th>
</tr></thead>
<tfoot></tfoot>
<cfoutput query="variables.query">
<tr><td><input name="name[]" type="text" value="#variables.query.name#"></td>
<td><input name="min[]" type="text" value="#variables.query.min#"></td>
<td><input name="max[]" type="text" value="#variables.query.max#"></td>
<td><input name="id[]" type="hidden" value="#variables.query.id#">
edit</td>
</tr>
</cfoutput>
<tr><td></td><td></td><td>add</td></td></tr>
</table>
<input type="Submit"/>
</form>
if I alter CatagoryService.cfc?method=saveVersion to <cfreturn arguments> in a JSON string, a typical response from Coldfusion looks like:
{VERSION:"",name:"name1,name2",min:"1,3", max:"2,4",id:"1,2"}

I put your HTML on jsfiddle (you can test it there) and added this JavaScript, using a selector that matches all and elements:
$(document).ready(function(event){
$(document).delegate("input, textarea", "keyup", function(event){
if(event.which === 188) {
var cleanedValue = $(this).val().replace(",","~");
$(this).val(cleanedValue);
}
});
});
All commas in the value string are replaced by a tilde if a comma (code 188) was entered.
Remember that JavaScript validation is nothing you want to rely on. The commas can easily be send to the server or never get replaced, e.g. in a user agent with JavaScript disabled.

I replaced the name[] .live() event.which = 126; to event.originalEvent.keyCode=126;
var regExComma = /,/;
$("[name='name[]']").live("keypress",function(event){
if(regExComma.test(String.fromCharCode(event.which)){
//this line works as expected. and will swap out the value on keypress.
if(event.originalEvent.keyCode){
event.originalEvent.keyCode=126;
}else if(event.originalEvent.charCode){
event.originalEvent.charCode=126;
}
}
});
wolfram I upped your keyUp solution as well.

Imho, there's no need to check those keyCodes:
$(document).ready(function(event){
$('#fieldName').keyup(function(event) {
var cleanedValue = $(this).val().replace(",","~");
$(this).val(cleanedValue);
});
});
Check it on jsFiddle.

Related

Check value from a string after a special character if it's not empty

im working in little projet, and i have a little issue
So first im working in a form with differents inputs
the first input called by ID is #name
I try to write a code to check if my user fill the input correctly with this tructure
fisrtname_lastname
what i try to do on my sence, is to check first if the user type ( _ ) in the input, and check if he continue to add more infos after the special character.
and the others steps is when he fill in the right way the submit button is actif
$('#submit').removeAttr('disabled');
if its not its gona be inactif
$('#submit').attr('disabled', 'disabled');
** input code**
<input type="text" class="form-control text" name="p_Nom" id="name" maxlength="24" placeholder="firstname_Prenom" />
** Jquery part **
$('#name').keyup(function() {
$('#submit').attr('disabled');
let val = $(this).val();
if( (val.includes('_')) && (val.substr(val.indexOf('_') + 1) == null) ){
$('#submit').removeAttr('disabled');
} else{
$('#submit').attr('disabled', 'disabled');
}
});
You might consider using a regex instead: use the pattern [A-Za-z]+_[A-Za-z]+ for the input. No jQuery necessary:
<form>
<input pattern="[A-Za-z]+_[A-Za-z]+">
<button>Submit</button>
</form>
Or, to permit other non-alphabetical characters, use a negative character set instead:
<form>
<input pattern="[^_]+_[^_]+">
<button>Submit</button>
</form>
If you also need to run Javascript when invalid, add an invalid event listener:
$('input').on('invalid', () => {
console.log('invalid');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input pattern="[^_]+_[^_]+">
<button>Submit</button>
</form>

Using the current variable when tracking multiple variables with jQuery event

Below you'll find a simplified example of the code I am using and what I am trying to accomplish.
I'm tracking multiple variables with jQuery that need to call a function on a certain event. The problem is that I don't manage to use only that variable that just changed.
In the HTML body section I have a couple of input fields where people can fill in a number. That number should be formatted with commas as a thousand seperator. Thanks to Elias Zamaria I found an good solution for this (https://stackoverflow.com/a/2901298/7327579). Now I want this implemented with jQuery so I can track all of my variables that will get number inputs at once.
<html>
<title></title>
<head>
In the head of the html I insert my script to track my variables:
<script language="javascript">
var Currency = function() {
this.currencyType = $("#businessAuthorisation, #businessIncome, #entityIncome, #entityAuthorisation);
The function that formats the numbers and should only get the current number from the current variable that is being changed:
this.formatCurrency = function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
};
};
Tracking starts and on the keyUp event my function is called. Only the current variable should be a parameter of the called function.
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
currency.formatCurrency(this);
});
});
</script>
</head>
Here below are the concerning input fields in my form:
<body>
<form>
<table>
<tr>
<td><input type="number" name="entityAuthorisation" id="entityAuthorisation" value="<%=entityAuthorisation%>></td>
</tr>
<tr>
<td><input type="number" name="businessAuthorisation" id="businessAuthorisation" value="<%=businessAuthorisation%>"></td>
</tr>
<tr>
<td><input type="number" name="entityIncome" id="entityIncome" value="<%=entityIncome%>"></td>
</tr>
<tr>
<td><input type="number" name="businessIncome" id="businessIncome" value="<%=businessIncome%>"></td>
</tr>
</table>
</form>
</body>
</html>
How can I make sure that that the function only applies to the current element that caused the event?
In a jQuery event handler, this refers to the element that the event was triggered on. And you need to use .value to get the value of an input. So you should write:
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
this.value = currency.formatCurrency(this.value);
});
});

How to reference "this" in a function

I want to validate several input fields. The code below works fine, except for the focus method. I expect that it can not interpret the "input" variable which relates to the input location on the form. Question: How do I reference the location of the specific input, bearing in mind that there are 20+ inputs ? tks !
function validateInput(quantity,input)
{
if (quantity.value !== " ") {
if(isNaN(quantity)) {
$(".myerror_alert").append('<div class="alert alert-danger"><strong>Warning!</strong> You have entered an non valid character, go back and enter a real number </div>');
input.focus(); // THIS DOES NOT WORK
return false;
}
}
return true;
}
$(".product_table").on('change', '.edit_quantity',function (){
var quantity = $(this).parents(':eq(1)').find('input').filter(".edit_quantity").val();
var input = $(this).parents(':eq(1)').find('quantity').filter(".edit_quantity");
validateInput(quantity, input);
// MORE CODE GOES HERE //
});
HTML:
<tr class='delete_row'>
<td><input class="product_id form-control" readonly="readonly" name="product_id[0]" type="text" value="123"></td>
<td><input class="edit_product_id form-control" readonly="readonly" name="product_id[0]" type="text" value="Euroshake Blackstone"></td>
<td><input class="edit_quantity" name="product_id[0]" type="text" value="120"></td>
<td id="price"><input class="unit_price form-control" readonly="readonly" style="text-align:right;" name="price" type="text" value="120.00"></td>
<td><input class="line_cost form-control" readonly="readonly" style="text-align:right;" name="cost" type="text" value="14400.00"></td>
<td>
<span style="padding-left:12px;"><input name="delete" type="checkbox" value="123"></span>
</td>
</tr>
What I did was supose that in this part .find('quantity') you was probably meaning .find('input') as its previous statement, then I figure out that you were working with the same element there. So being the same element, you don't need to hold it's reference(in input var) and it's value(quantity var) to pass into validateInput. As this is a function, why not work with less code and make the function handles it, right? So I've changed it to pass only the element reference and inside the function with this condition if ($input.val().length > 0 && isNaN($input.val())) I could check if element ins't empty and also if it isn't a number:
function validateInput(input)
{
var $input = $(input);
if ($input.val().length > 0 && isNaN($input.val())) {
$(".myerror_alert").append('<div class="alert alert-danger"><strong>Warning!</strong> You have entered an non valid character, go back and enter a real number </div>');
input.focus();
return false;
}
return true;
}
$(".product_table").on('change', '.edit_quantity',function (){
validateInput(this);
});
Demo
One important mistake you've done that you've workaround it - probably - without noticing it, is that you navigate through the element tree to find the input, but when you do $(".product_table").on('change', '.edit_quantity' you're in fact binding an event in all elements with class edit_quantity inside the element with class product_table, so inside the event, your this already is the input, you don't need to go after it, as I did:
validateInput(this);
I hope this helps.

how to use split() function in classic ASP for mass inputs textbox?

I am trying to use the split function in classic ASP using JavaScript. I need to have a big text box where I can keep group of bar-code numbers of products. Once submit button is clicked These bar-code numbers needed to be split by each and every character term for all bar-code numbers (in a loop). For instance, if i have 5 bar-code numbers, I have to split first bar-code number by each and every character/number, keep into array and continue same process to all 5 bar-code numbers. I wanted to display the result of split-ted numbers into a paragraph for myself just to check if its working. Below is the code I was working on. It doesn't show me anything when i click the button. I am not being able to figure out my logical error or what am I missing. How do I fix it? I didn't find any helpful solution when i was doing research.
<p id="demo"></p>
<form name="submitticket" action="<%=Request("script_name")%>" method="post">
<input type="hidden" name="action" value="sendform">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td align="center" colspan="2">
<br /><textarea name="noskews" id="skewsip" rows="50" cols="100" wrap="soft" maxlength="5000"><%=Request("noskews")%></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="padding-top:20px;">
<input type="submit" name="clearNoskew" value="Submit" class="a-t-button-mini">
</td>
</tr>
</table>
</form>
<script>
$("form").on("click", ".a-t-button-mini", function(event){
//var clickedId = $(this).attr('value')+','; // give me first numbers,
var locationBtn = $('#skewsip'); // Select the input
var locationBtnValue = $('#skewsip').val(); // Take the select value
var ids = locationBtnValue.split(',');
document.getElementById("demo").innerHTML = ids; //want to display in a paragraph for myself
});
</script>
I was able to split one barcode (out of total 5 barcodes entered inside textarea) by every characters and display it into div. for example: I entered 5465 8989 7586 5236 5486 (These barcodes are entered using "enter or new line" after every 4 numbers; space in above example means the next barcode is in next line). I get split output of (5,4,6,5) which I need but it didn't give me for rest of my barcodes. In other words, I couldn't do same for all 5 total bar codes entered into the textarea/textbox. I know its only "for loop" When I kept for loop in my code, it executes for first barcode out of 5 barcodes.
<script>
$("#form").on("click",".a-t-button-mini", function(event){
var locationBtnValue = $('#skewsip').val();
var skews_array = locationBtnValue.split("",12);
// for (i = 0; i < locationBtnValue.length; i++) {
// text += skews_array[i] + "<br>";
document.getElementById("test").innerHTML = skews_array;
// }
});
</script>
I think you're saying each barcode on a new line of the textarea. If so, this should work for you (\n is the newline character), at least to capture and re-output to the demo element:
<script>
$("form").on("click", ".a-t-button-mini", function(event){
var ids = $("#noskews").val().split('\n');
$.each( ids, function( index, value ) {
$("#demo").append(index + ' - ' + value + '<br/>');
});
});
</script>
Added working code to codepen:
http://codepen.io/anon/pen/NxENYW

JQuery-mobile validation!

I am using JQuery-mobile under eclipse. I have a form with 2 text fields, I want my 1st text field in the form to be able accept only numbers, so if the input is a char, or text or even empty, i want an error to appear. as for validation goes, I am using jquery validVal. I have included my codes `
<form id="ccform" method = "post">
<table>
<tr>
<td><label for="cc">Card Number</label></td>
<td><input name = "ccc" class="required" type = "text" id = "cc" maxlength="23" " ></td>
</tr>
<tr>
<td>Card Holder Name</td>
<td><input class="required" type = "text"></td>
</tr>
</table>
</form>
and also:
<script>
$("#ccform").validVal({
customValidaton:{
"cc": function ($field){
var myexpr =/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/
if(myexpr.test($field.val())) {return true;}
else{return false;}
}
}
});
</script>
`
but I dont get any result, nothing... so any help would be appreciated.
You have a syntax error. Your regular expression should start and end with a /.
/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/
you can look at http://validval.frebsite.nl/examples.php.
See example 1, there is validVal validation available for number.
Why bother writing your own validation?? Use an existing plugin such as this one
You can do like this.
first change the file as below. Note the Required number attribute.
<input name = "ccc" class="required number" type = "text" id = "cc" maxlength="23">
Then a simple $("#ccform").validate(); can do the magic.
full working example is here http://jsfiddle.net/mayooresan/A3rvK/3/

Categories

Resources