JQuery-mobile validation! - javascript

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/

Related

Sum a calculated <td> value

I am creating a calculator that converts a different opioids medications to a standard opioid dosage. The calculator converts all medications fine but I cannot get the javaScript sum() function to add it all up when a button is clicked. Please help.
Of note, the "totalMED += total[i]).value;" code inside the for loop breaks the medication calculate function (no value is displayed). I don't know why.
P.S. I realize both calculate() functions are basically the same but I couldn't get the relevant values to loop through a single function. I seem to have problems with loops.
Updated code with comments:
<!DOCTYPE html>
<html>
<head>
<SCRIPT language="javascript" src="date.js"></SCRIPT>
<style type="text/css">
...
</style>
</head>
<body>
<form>
<table>
<tr>
<th>Medications</th>
<th>Daily Dose (mg)</th>
<th>MED</th>
<th>Medications</th>
<th>Daily Dose (mg)</th>
<th>MED</th>
</tr>
<tr>
// ---this input box is really just a label----
<td><input class="tg-yw41" type=”text” name=”Tramadol” value=Tramadol id="med”
disabled></td>
// ----This input box takes user entered dosage, calls calculate() function, and
// passes the conversion factor---
<td>'TEXT"</td><td><input class ="tg-yw41" type=”text” name=”dose” value=""
placeholder="0" Id="r18c2" onchange="calculate28('.1')"></td>
//---This input box receives the value from the calculate function via Id="MED-
// Tramadol". Also includes name="sum" for sum() function.
<td><input Id="MED-Tramadol" type=”text” name="sum" value="" disabled></td>
//----The next three rows are just duplicate of above
<td><input class="tg-yw41" type=”text” name=”Sufentanil” value="Sufentanil"
disabled></td>
<td><input class ="tg-yw41" type=”text” name=”dose” value="" placeholder="0"
Id="r18c5" onchange="calculate29('60')"></td>
<td><input Id="MED-Sufentanil-intra" type=”text” name="sum" value="" disabled></td>
</tr>
<tr>
//-----Label
<td><input value="Total Daily Morphine Equivalent Dose (MED) in Milligrams"
disabled></td>
//---Input box that should receive value from sum() function (via ID="r19c2")
<td><input class ="tg-yw41" type=”text” name=”dose” value="" placeholder="0"
Id="r19c2"></td>
</tr>
//A button that when clicked calls the sum() function
</table>
<button type="button" onclick="sum()">MED total</button>
JavaScript functions
<script type="text/javascript">
//Takes user input * passed conversion factor, assigns value to
document.getElementById('MED-Tramadol')
function calculate28(x)
{
var my1 = x;
var my2 = document.getElementById('r18c2').value;
//Note: value is parsed as a Float...don't know if it gets converted back to string
document.getElementById('MED-Tramadol').value = parseFloat(my1) * parseFloat(my2);
}
//same as above
function calculate29(x)
{
var my1 = x;
var my2 = document.getElementById('r18c5').value;
document.getElementById('MED-Sufentanil-intra').value = parseFloat(my1) * parseFloat(my2);
}
//Supposed to combine all values from calculate() function assigned to respective boxes
function sum() {
//should collect value from all <input> with name="sum"
var total = document.getElementsByName('sum').value;
var sum = 0;
for(var i=0; i<total.length; i++)
{
totalMED += paredFloat(total[i]).value);
}
document.getElementById('r19c2').value = totalMED;
When you pull the value of an input box, it's read as a string. Use parseInt() to get the number, otherwise you're concatenating strings.
Since you're taking in user input, you should also validate it. A simple way to make sure you don't get NaN is to pull the value into a temporary variable and test it before parsing.
var strTemp = total[i].value;
if (strTemp)
{
totalMED += parseInt(test);
}
EDIT: I ignored the paren, thinking it was just a typo in the question. I decided I shouldn't. You'll see small errors like the unmatched ) inside your call easily if you check your browser's JS console, as this would certainly halt the program and provide an error message.
I'm just going to post this answer out here, and if it doesn't help or it's close then we can edit as we see fit.
First of all, are you sure that you are receiving the correct values in each of the variables? For example, var total = document.getElementsByName('sum').value; should return as undefined.
Secondly, totalMED += total[i]).value; is not valid Javascript, and even if var total = document.getElementsByName('sum').value; were to give you an array of actual values.. then totalMED += total[i]).value; would just concatenate strings. For example, if you have 2 input elements on your page, and the first has a value of 20 and the second has a value of 25 then, your output would be 02025, because value is of type string.
I think this may help:
Javascript
function sum()
{
var total = document.getElementsByName('sum');
var totalMED = 0;
for(var i = 0; i < total.length; i++)
{
if(!isNaN(parseInt(total[i].value)))
{
console.log(total[i].value);
totalMED += parseInt(total[i].value);
}
}
console.log(totalMED);
}
Here is a JSFiddle to prove that it's working.
Let me know if this helps.

If-expression in JavaScript with HTML (optional) button in one function

I'm creating a HTML table with fields, that have to be filled, but I want to make one of the fields optional. My code is something like this:
name.html
...
<table>
<tr>
<td>A number:</td>
<td><input id="numb1" type="text"/></td>
</tr>
<tr>
<td>Anoder number (optional)</td>
<td><input id="numb2" type="text"></td>
</tr>
</table>
<input type="button" value="Click" onclick="forfun()"/>
<pre id="result">
Result
</pre>
...
In my jaava.js I want to use an if-else expression, defining, that if the optional field is not empty, then the variable should take the value of the number, written in the field.
function forfun() {
var numberOne=document.getElementById("numb1").value;
numberOne =parseFloat(numberOne); // numberOne is now really a number
var numberTwo=document.getElementById("numb2").value;
numberTwo=parseFloat(numberTwo);
...
if(numberTwo==NaN) { //Here comes the problem, I tried also with
//undefined and ==0, but after pressing the button, I become the results
//of my functions in this loop with result NaN
numberTwo=2;
//and so on
...
}
}else {
//After I fill the second field, everything here is ok
}
What should I write between the brackets after if? Would you give me some ideas?
Comparison with NaN always returns false, so even NaN == NaN will return false. Instead use the built-in isNaN() function:
if (isNaN(numberTwo)) {

Pass the value of html input text to Javascript Function and get the result

This is my very first time I'm using Javascript.
I have this Script:
<script type="text/javascript">
function baunilha()
{
var qb=document.getElementById("quantbaunilha").innerHTML;
var prbau=5.58;
var totbau=qtd*prbau;
}
document.getElementById("valorlinhab").innerHTML=baunilha();
</script>
And, this is how the Function is called:
<tr>
<td><img src="/imagens/DOB_Baunilha.PNG" style="vertical-align: middle" alt="Ima_Bau"> </td>
<td>Caixa de 42 Unidoses de Detergente Ultra-Concentrado aroma Baunilha</td>
<td><input id="quantbaunilha" name="quantbaunilha" value="0" maxlength="2" type="text" size="2" onchange="baunilha()"></td>
<td><input id="valorunib" name="valorunib" size="6" value="5.58">€</td>
<td><input id="valorlinhab" name="valorlinhab" size="8" value="0.00">€</td>
</tr>
So, I want that the result of the Function apears in text-box id="valorlinhab".
I tried the examples of w3schools, but they didn't work, as others examples in the web.
Is there someone who could help me? Any help is wellcome.
Thank you, in advance.
You need to be using value instead of innerHTML. Additionally, you are using "qtb" instead of "qb" in your calculation. You should also set the value inside the baunilha function. Finally, you must tie an event listener to the input so that it will call the javascript function.
I also added a line which would check if the input is actually a number.
function baunilha()
{
var qb=document.getElementById("quantbaunilha").value;
//check that quantbaunilha is a number
if(isNaN(parseFloat(qb)))
{
alert('Enter a number');
return;
}
var prbau=5.58;
document.getElementById("valorlinhab").value=qb*prbau;
}
document.getElementById("quantbaunilha").addEventListener('change', baunilha);
Here is a fiddle: http://jsfiddle.net/uLfcG/3/
You use innerHTML to put the results in to an element's inner HTML for a tag with both an opening and closing tag (like <p>).
Also, since you are using it for your onchange event, you should move the value setting in to the function as well.
For <input>, you set the value attribute instead:
<script type="text/javascript">
function baunilha() {
var qb=document.getElementById("quantbaunilha").value;
var prbau=5.58;
var totbau=qb*prbau;
document.getElementById("valorlinhab").value=totbau;
}
</script>
That should do the trick.
Here is a JSFiddle with a working example: http://jsfiddle.net/U7ZZh/
Also, you had a small typo on the line that is var totbau=qtb*prbau should be var totbau=qb*prbau

Trying to add variable value from an html form into javascript

I've got a form set up below which has two inputs Keywords and min price
<form name="Data" method="GET" action="#">
<table cellpadding="2" border="0">
<tr>
<th>Keywords</th>
<th>Min Price</th>
</tr>
<tr>
<td><input type="text" name="keywords" id="keywords"/></td>
<td><input type="text" name="MinPrice" id="MinPrice"/></td>
</tr>
<tr>
<td colspan="2" align="center"><INPUT type="submit" name="submit" value="Search">
</td>
</tr>
</table>
</form>
Then the results obtained need to go into a javascript that then should return result based on the variable. The JS works without the variable i.e. just putting them in in the code, but i can t figure out how to reference the above form then submit the code as a whole
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
var filterarray = [
{"name":"MaxPrice",
"value":"1000",
"name":"MinPrice",
"value":Variable here!!,
"paramName":"Currency",
"paramValue":"GBP"},
Above is part of the script where one of the values would go
Any help apreciated p.s. complete novice so take it very slowly
Your list of options is not correct, several properties have the same name.
Here is a different way to present it:
var maxPrice = document.getElementById('MaxPrice').value;
var minPrice = document.getElementById('MinPrice').value;
var filterOptions = {
"MaxPrice": maxPrice,
"MinPrice": minPrice,
"paramName":"Currency",
"paramValue":"GBP"
};
You can then use them in your code. For example the min price will be filterOptions.MinPrice.
To retrieve the content from the MinPrice input text just do the following:
var minPrice = document.getElementById('MinPrice').value;
or more simply with jquery:
var minPrice = $('#MinPrice').val();
As for the way you are buiding up your array taht does not make much sense to me:
var filterarray = [
{"name":"MaxPrice",
"value":"1000",
"name":"MinPrice",
"value":Variable here!!,
"paramName":"Currency",
"paramValue":"GBP"},
...
Here you are building an array of objects containg the same fields multiple times (name and value). That does not make much sense to me. You should maybe reconsider the structure of the literal objects you are trying to populate the array with.

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

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.

Categories

Resources