How to get validation to work properly on my input fields
This question already has an answer here:
请试试这个答案:
function audience_details(){
var aud1, aud2, total;
if(document.getElementById("audience_1_field").value == "" || !onlyNos(document.getElementById("audience_1_field"))){
alert("Please enter valid number in audience 1");
}
else if(document.getElementById("audience_2_field").value == "" || !onlyNos(document.getElementById("audience_2_field"))){
alert("Please enter valid number in audience 2");
}
else if(document.getElementById("reach_field").value == "" || !onlyNos(document.getElementById("reach_field"))){
alert("Please enter valid number in reache field");
}
else{
var aud1 = parseInt(document.getElementById("audience_1_field").value);
var aud2 = parseInt(document.getElementById("audience_2_field").value);
var reach = parseInt(document.getElementById("reach_field").value);
var total = (aud1 + aud2 - reach ) / aud1 * 100 ;
total_field.value = parseFloat(total).toFixed(2) + '%';
}
}
function onlyNos(e) {
try {
if (e) {
var charCode = e.value;
if (charCode.charCodeAt() > 31 && (charCode.charCodeAt() < 48 || charCode.charCodeAt() > 57))
return false;
else { return true; }
}
else{return false;}
}
catch (err) {
alert(err.Description);
}
}
Here I am going to give the partial solution. Look at the javascript
validation and demo fiddle.
function audience_details()
{
var temp = document.getElementById("audience_1_field").value;
var temp1 = document.getElementById("audience_2_field").value;
var temp2 = document.getElementById("reach_field").value;
if(temp == "" || temp == null)
{
alert("please enter Audience 1 value");
}
else if(temp1 == "" || temp1 == null)
{
alert("please enter Audience 2 value");
}
else if(temp2 == "" || temp2 == null)
{
alert("please enter Total Reach value");
}
else
{
var aud1, aud2, total;
var aud1 = parseInt(document.getElementById("audience_1_field").value);
var aud2 = parseInt(document.getElementById("audience_2_field").value);
var reach = parseInt(document.getElementById("reach_field").value);
var total = (((aud1 + aud2) - reach ) / aud1) * 100 ;
total_field = parseFloat(total).toFixed(2) + '%';
estimate = parseFloat(total).toFixed(2) + '%';
document.getElementById("total_field").value = total_field;
}
}
SAMPLE DEMO
As I told above partial solution
, Because I didn't add the numeric value validation in my solution. At present it will check whether they enter the value or not. If not it will through alert message. You try yourself for the numeric value validation.
下一篇: 如何验证在我的输入字段上正常工作