This has me pulling my hair out. Button on site has onclick=method() and it's not calling the method. The method is supposed to grab all the checkboxes, check their checked state and fill the chk[] array with true/false. The WebMethod then takes that array, breaks it down into three smaller arrays and runs checks on the combinations. So far as I can tell, the button never calls the method to begin with.
aspx page:
<fieldset id="Fieldset">
<button onclick="SendForm();">Send</button>
<button onclick="CancelForm();">Cancel</button>
</fieldset>
</form>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
var chk = new [42];
for (i = 0; i < elLength; i++) {
var count = 0;
var type = form1.elements[i].type;
if (type == "checkbox") {
if (form1.elements[i].checked) {
chk[count] = true;
}
else {
chk[count] = false;
}
count++;
}
else {
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
codebehind method it's calling:
[WebMethod]
public static void SendForm(string email, bool[] chk)
{
bool[] desc = new bool[14];
bool[] loc = new bool[14];
bool[] other = new bool[14];
for (int i = 0; i < 14; i++)
{
int count = i * 3;
desc[i] = chk[count];
loc[i] = chk[count + 1];
other[i] = chk[count + 2];
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
for (int i = 0; i < 14; i++)
{
if (desc[i])
{
if ((loc[i]) && (other[i]))
{
throw new Exception("Invalid, two parameters selected");
}
else if (loc[i])
{
// do stuff
}
else if (other[i])
{
// do stuff
}
else
{
throw new Exception("Invalid, every exemption must have at least one reason selected");
}
}
else
{
throw new Exception("No exemptions have been selected");
}
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
EDIT!!:
Running the page with the following script instead of the previous script works like a charm. No clue why the previous didn't work.
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
for (i=0;i< elLength;i++) {
var type = form1.elements[i].type;
if (type == "checkbox" && form1.elements[i].checked) {
alert("true!");
}
else {
alert("false!");
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
Instead of calling your function like
<button onclick="SendForm();">Send</button>
try calling it like this
<button onclick="javascript:return SendForm();">Send</button>
Running the page with the following script instead of the previous script works like a charm. No clue why the previous didn't work.
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
for (i=0;i< elLength;i++) {
var type = form1.elements[i].type;
if (type == "checkbox" && form1.elements[i].checked) {
alert("true!");
}
else {
alert("false!");
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
Related
I'm doing this for a class assignment and I know there has to be a better way of writing it. Maybe some kind of loop that gets the inputs and labels? I'm repeating a lot here and it seems better to minify this if possible.
function checkEmptyFields() {
if(formName.value === "") {
formLabels[0].classList.add("has-errors");
formLabels[0].innerHTML = "Name is required *";
formName.style.borderBottomColor = "red";
} else {
formLabels[0].classList.remove("has-errors");
formLabels[0].innerHTML = "Name";
formName.style.borderBottomColor = "green";
}
if(formEmail.value === "") {
formLabels[1].classList.add("has-errors");
formLabels[1].innerHTML = "Email is required *";
formEmail.style.borderBottomColor = "red";
} else {
formLabels[1].classList.remove("has-errors");
formLabels[1].innerHTML = "Email";
formEmail.style.borderBottomColor = "green";
}
if(formNumber.value === "") {
formLabels[2].classList.add("has-errors");
formLabels[2].innerHTML = "Phone is required *";
formNumber.style.borderBottomColor = "red";
} else {
formLabels[2].classList.remove("has-errors");
formLabels[2].innerHTML = "Phone";
formNumber.style.borderBottomColor = "green";
}
if(formMessage.value === "") {
formLabels[3].classList.add("has-errors");
formLabels[3].innerHTML = "message is required *";
formMessage.style.borderBottomColor = "red";
} else {
formLabels[3].classList.remove("has-errors");
formLabels[3].innerHTML = "Email";
formMessage.style.borderBottomColor = "green";
}
}
You can try like this:
fields = [{
'name': formName,
'index': 0,
'css-error': "has-errors",
'innerHtml': "Name",
'innerHtml-error': "Name is required *",
'borderBottomColor ': "green", //Or you can hardcode it in the loop itself.
'borderBottomColor-error': "red"
},
....
]
for(var i=0; i < fields.length; i++) {
var field = fields[i];
if(field.name.value == "") {
formLabels[field.index].classList.add(field.css);
formLabels[field.index].innerHTML = field.innerHtml-error;
field.name.style.borderBottomColor = field.borderBottomColor-error ;
} else {
formLabels[field.index].classList.remove(field.css);
formLabels[field.index].innerHTML = field.innerHtml;
field.name.style.borderBottomColor = field.borderBottomColor ;
}
}
You can create arrays for both the controls and the control names, and process them together with the formLabels array that you already have, in a for-loop that goes from 0 to length (not inclusive), like this:
function checkEmptyFields() {
var controls = [formName, formEmail, formNumber, formMessage];
var controlNames = ["Name", "Email", "Phone", "Message"];
for (var i = 0; i < controls.length; i++) {
if(controls[i].value === "") {
formLabels[i].classList.add("has-errors");
formLabels[i].innerHTML = controlNames[i] + " is required *";
controls[i].style.borderBottomColor = "red";
} else {
formLabels[i].classList.remove("has-errors");
formLabels[i].innerHTML = controlNames[i];
controls[i].style.borderBottomColor = "green";
}
}
}
You can write an additional function to check one field:
function checkEmptyField(field, ind, msg, errmsg) {
if(field.value === "") {
formLabels[ind].classList.add("has-errors");
formLabels[ind].innerHTML = errmsg;
field.style.borderBottomColor = "red";
} else {
formLabels[ind].classList.remove("has-errors");
formLabels[ind].innerHTML = msg;
field.style.borderBottomColor = "green";
}
}
Then you can call it
function checkEmptyFields() {
checkEmptyField(formName,0,"Name","Name is required *");
...
If you know about and understand for loops you can simply loop over 2 arrays of data like this:
function checkEmptyFields() {
formArray = [formName, formEmail, formNumber, formMessage];
labelArray = ["Name", "Email", "Phone", "Message"];
for (let i = 0; i < formArray.length; i++) {
if(formArray[i].value === "") {
formLabels[i].classList.add("has-errors");
formLabels[i].innerHTML = labelArray[i] + " is required *";
formArray[i].style.borderBottomColor = "red";
} else {
formLabels[i].classList.remove("has-errors");
formLabels[i].innerHTML = labelArray[i];
formArray[i].style.borderBottomColor = "green";
}
}
}
if not then you can read about them here:
https://www.w3schools.com/js/js_loop_for.asp
Anytime you have roughly the same code in more than one place, you should stop and rethink your approach as you are doing here.
If you give each of the HTML elements that need to be validated a common class, you can then create a node list (collection/array) that contains them. Then you can loop over that collection and perform the same test (written only once) on each item and act accordingly.
Also, I'm not quite sure what you are doing with .innerHTML, but don't use that when the text you are working with doesn't have any HTML in it. .innerHTML has security and performance implications. Instead, use .textContent when there is no HTML.
// Get all the form fields that need validation into an Array
let fields = Array.prototype.slice.call(document.querySelectorAll(".validationNeeded"));
// Set up form submit event handler
document.querySelector("form").addEventListener("submit", checkEmptyFields);
function checkEmptyFields(event) {
let validCount = fields.length; // Holds the number of valid fields
// Loop over the array
fields.forEach(function(field){
if(field.value === ""){
field.previousElementSibling.classList.add("has-errors-label"); // style the label
field.classList.add("has-errors-field"); // style the field
field.classList.remove("valid-field"); // style the field
validCount--; // Decrease the count of valid fields
} else {
field.previousElementSibling.classList.remove("has-errors-label"); // style the label
field.classList.remove("has-errors-field"); // style the field
field.classList.add("valid-field"); // style the field
}
});
// Check to see if the form should be submitted
if(validCount !== fields.length){
event.preventDefault(); // Cancel the form's submission
}
}
.row {margin-bottom:5px; }
.has-errors-label { color:red; }
.has-errors-field { outline:1px solid red; }
.valid-field { outline:1px solid green; }
<form action="#" method="get">
<div class="row">
<label for="userName">Name: </label>
<input class="validationNeeded" name="userName" id="userName">
</div>
<div class="row">
<label for="email">Email: </label>
<input class="validationNeeded" name="email" id="email">
</div>
<div class="row">
<label for="phone">Phone: </label>
<input class="validationNeeded" name="phone" id="phone">
</div>
<button>Submit</button>
</form>
So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";
I created this small game while ago and now i'm trying it find a way to make it script short and simpler i was wondering if there is any another way . I have four pics of animals and blow the pic i have four names . what the game suppose to do is when the users click on right image and right name both the image and the name has to disappear. Any help really appreciate it
function image_select() {
var pic1 = document.getElementById("cow").value;
var text1 = document.getElementById("cow_t").value;
if (document.getElementById("cow").checked) {
if (pic1 == text1) {
var x = document.getElementById("cow_s");
x.play();
} else {
alert("wrong selection");
}
} else {
alert("no");
}
}
function image_select2() {
var pic2 = document.getElementById("dog").value;
var text2 = document.getElementById("dog_t").value;
if (document.getElementById("dog").checked) {
if (pic2 == text2) {
var x = document.getElementById("dog_s");
x.play();
} else {
alert("wrong selection");
}
} else {
alert("no");
}
}
function image_select3() {
var pic3 = document.getElementById("horse").value;
var text3 = document.getElementById("horse_t").value;
if (document.getElementById("horse").checked) {
if (pic3 == text3) {
var x = document.getElementById("horse_s");
x.play();
} else {
alert("wrong selection");
}
} else {
alert("no");
}
}
function image_select4() {
var pic4 = document.getElementById("pig").value;
var text4 = document.getElementById("pig_t").value;
if (document.getElementById("pig").checked) {
if (pic4 == text4) {
var x = document.getElementById("pig_s");
x.play();
} else {
alert("wrong selection");
}
} else {
alert("no");
}
}
<div style="margin-left:230px;">
<br>
<br>
<img onmousedown="dog.play()" height="142" width="142" src="image/cow.jpg" alt="Cow" data-value="cow" onclick="selectImage(event)" />
<img height="142" width="142" src="image/dog.jpg" alt="" data-value="dog" onclick="selectImage(event)"/>
<img height="142" width="142" src="image/horse.jpg" alt="" data-value="horse" onclick="selectImage(event)"/>
<img height="142" width="142" src="image/pig.jpg" data-value="pig" onclick="selectImage(event)"/>
</div>
<br>
<br>
<br>
<div style="margin-left:400px;">
<button type="button" onclick="selectName(event)" value="pig" id="pig_t">Cochon</button>
<button type="button" onclick="selectName(event)" value="cow" id="cow_t">Vache</button>
<button type="button" onclick="selectName(event)" value="horse" id="horse_t">Cheval</button>
<button type="button" onclick="selectName(event)" value="dog" id="dog_t">chien</button>
</div>
Just put the name of the animal to the function (in fact, you seem to already does so, since you pass the event to selectName, but I don't see this function in your code) :
function image_select_animal(prefix) {
var pic = document.getElementById(prefix).value;
var text = document.getElementById(prefix + "_t").value;
if (document.getElementById(prefix).checked) {
if (pic == text) {
var x = document.getElementById(prefix + "_s");
x.play();
} else {
alert("wrong selection");
}
} else {
alert("no");
}
}
and in onclick, call image_select_animal("pig") or equivalent for the other animals.
function image_select(name) {
var el = document.getElementById(name); // create this variable, as you use this element twice. Less DOM lookups.
var pic = el.value; // get the value of the `el` variable
var text = document.getElementById(name + '_t').value;
if (!el.checked) { // if not check
alert('no');
return; // return ends the function immediately, meaning the following lines are not read
}
if (pic != text) {
alert('wrong selection');
return; // return ends the function immediately, meaning the following lines are not read
}
document.getElementById(name + '_s').play(); // no need to store this in variable x, as you only use this element once.
}
I have this email validation function in plain JavaScript:
function isEmail() {
var slides = document.getElementsByClassName("email");
for (var i = 0; i < slides.length; i++) {
emailValue = slides.item(i).value;
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var res = regex.test(emailValue);
if (res == false) {
alert("Enter valid email");
return false;
} else {
return true;
}
}
}
I want to convert this in to jQuery in this format:
$(document).ready(function() {
$("#form").submit(function() {
$(".email").each(function() {
});
});
});
Is that what you need??
$(document).ready(function() {
$(".button").click(function() {
$("li.email").each(function() {
emailValue = $(this).text();
console.log(emailValue);
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var res = regex.test(emailValue);
if (res == false) {
alert(emailValue+" email invalid");
} else {
alert(emailValue+" email valid");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="email">email_valid#gmail.com</li>
<li class="email">email_valid2#gmail.com</li>
<li class="email">email_invalid#gmailcom</li>
<li class="email">email_valid3#gmail.com</li>
<li class="">not email</li>
</ul>
<input type="button" class="button" value="validate emails"/>
It seams like the code above it trying to validate multiple emails fields on the page. So I'm going to make some dummy data on my js fiddle for you. I also optimized your code so that the variables are cached outside of the loop. If they were cached inside of the $.each loop, then it would create a new variable each time.
function isEmail() {
var slides = $('.email');
var emailValue = null;
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
var res = null;
console.log(slides);
$(slides).each(function(){
emailValue = $(this).val();
res = regex.test(emailValue);
if (res==false){
alert("Enter valid email");
return false;
}
alert("Success!")
return true;
})
}
Here is the JSFiddle
I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>