How to convert this code in to jQuery - javascript

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

Related

How will i prevent duplication of value and empty value

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

Store default values and use in comparison in click event

The code is not complete atm but demonstrates what i'm trying to do. In my script i have a jQuery function that is storing the default values from all textareas when the pages is first loaded in an array "defaultValues". When the "click function is executed and the idea is to use the array "defaultValues" in the "CheckTextChange" function and check if anny item dosn't match "currentVal". If currentVal has another value a text change has been made and CheckTextChange will return true. I'm wondering, how can i access "defaultValues[]" inside CheckTextChange and how can i use defaultValues[] in the if-statement to check weather anny item dosn't match currentVal?
HTML:
<h3>Text1...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
Script:
$('#btnClick').on("click", function () {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
var defaultValues = [];
$(document).ready(function(){
$('.txt').each(function () {
var defValue = $(this).get(0).defaultValue;
defaultValues.push(defValue);
var v = defaultValues[0];
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != previousVal) {
isChanged = true;
}
});
return isChanged;
}
you can save the default values as a data attrib...
$(document).ready(function() {
$(".txt").each(function() {
$(this).attr("data-deftxt", $(this).val());
});
});
$('#btnClick').on("click", function() {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function() {
var currentVal = $(this).val();
if ($(this).val() !== $(this).data("deftxt")) {
isChanged = true;
}
});
return isChanged;
}
Use an associative mapping:
var defaultValues = {};
$(document).ready(function(){
$('.txt').each(function () {
defaultValues[$(this).attr('id')] = $(this).val();
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultValues[$(this).attr('id')]) {
isChanged = true;
}
});
return isChanged;
}
And set an ID to your fields:
<h3>Text1...</h3>
<textarea class="txt" id="field1">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt" id="field2">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt" id="field3">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
You have to break the loop as follow
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function (index) {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultVaules[index]) {
isChanged = true;
return;
}
});
return isChanged;
}

hide second modal if condition is false

I have 2 modal and I check validation of form of first modal and if entries of textboxes were empty .second modal should not be shown.I cannot do this. user is id of my first modal and permission is id of my second modal.
java script code:
function valid() {
var bool = true;
var pt = /^[\w.]+#[a-z0-9-]+\.[a-z]{2,6}/i;
var email = document.getElementById('email').value;
if (!pt.test(email)) {
bool = false;
}
var name = document.getElementById('name').value;
if (name.length < 1) {
bool = false;
}
return bool;
}
$("#btn1").click(function() {
var bool = valid();
if (bool == false) {
$('#permission').modal('hide');
} else {
$('#user').modal('hide');
$('#permission').modal('show');
}
});
my html code:
<form onsubmit="return valid()">
<button role="button" class="btn btn-default" data-toggle="modal" data-target="#permission" id="btn1">set permission</button>
What about trying this in the valid() function?
function valid() {
var pt = /^[\w.]+#[a-z0-9-]+\.[a-z]{2,6}/i;
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
return pt.test(email) && name.length>1;
}

jQuery multiple validation

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>

Javascript function not being called from onclick

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>

Categories