I'm supposed to press enter to submit the form
my code doesnt work on this FIDDLE but it works on this one FIDDLE2.
I'm not really sure why and would like to see if anyone knows why. The code is exactly the same
var i = 0;
var allowed = /^[a-zA-Z0-9]+$/;
$('#form').submit(function(e) {
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if (!allowed.test(input)) {
alert("Name can have only letters and numbers.\n\n Names Already Submitted: " + ar.join(" , "));
return false;
} else {
ar[i] = input;
alert("Your name was successfully submitted\n\n Names Already Submitted: " + ar.join(" , "));
i = i + 1;
return false;
}
})
You have not included jQuery in the first fiddle, and that is why $ can not be resolved or defined error is there.
Second fiddle does includes jQuery and it is working as expected.
It is showing $ is not defined. It is means you are not including jQuery in your project.
add jQuery in your code. working fiddle here
Add
$('#form').submit(function(e){
e.preventDefault(); // Saves from Reloading of page
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if(!allowed.test(input)){
alert("Name can have only letters and numbers.\n\n Names Already Submitted: "+ ar.join(" , "));
return false;
}else{
ar[i]= input;
alert("Your name was successfully submitted\n\n Names Already Submitted: "+ ar.join(" , ") );
i = i+1;
return false;
}
});
try the below code
When the input is not matching your regex, then validation will occurs and page will get not submit.
use preventDefault in if (!allowed.test(input)) {
$('#form').submit(function (e) {
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if (!allowed.test(input)) {
alert("Name can have only letters and numbers.\n\n Names Already Submitted: " + ar.join(" , "));
e.preventDefault();
return false;
} else {
ar[i] = input;
alert("Your name was successfully submitted\n\n Names Already Submitted: " + ar.join(" , "));
i = i + 1;
return false;
}
})
Related
i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/
I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/
I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example
I'm trying to have a button and text box displayed. Have the user enter a number. That a random number will be generated and the user has 10 attempts to answer the question correctly. The script should check whether the users number is either equal to, less than, or greater than the random number. I am having trouble getting the number inputted from the text-box.
HTML:
<form name="myForm">
<div id='myForm'></div>
</form>
JAVASCRIPT:
function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
var check = document.getElementById('textbox').value
button.onclick = calc(guessCount, random, check);
}
function calc(guessCount, random, check){
while(guessCount > 0) {
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;
}
}
Your code is assigning callback function result to onclick event instead of function itself. Besides, you are also trying to run a while loop which will consume guessCount on first click event.
I edited code, following should work:
function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
button.onclick = function(){
var check = textbox.value*1;
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;
}
}
You are accessing the value by using id, whereas you didn't give any id to your input.
Try this:
textbox.id = 'textbox';
You forgot the set the id of your textbox element. Try adding the id after creating it. Then you can get the element by its id, which in your case is textbox
var myEl = document.getElementById('a');
myEl.addEventListener('click', function() {
alert(document.getElementById('text').value);
}, false);
<input type="text" id="text"/>
<button id="a">Alert text</button>
Jquery has a wonderful option available for you,
$('#unique-id').val();
The unique ID will be whatever value that specific textarea. So in this case:
<textarea id="unique-id"></textarea>
I just wanted to add this to what all the other answers say. You probably want a semicolon after this line:
var check = document.getElementById('textbox').value
I'm using $.trim to check if the inputs are empty, if so, nothing should happen. If they're not empty then the form should be submitted.
This is the variable where the condition is located:
var save = $("<input type='button' value='Save' />").on('click',function() {
if(!$.trim(name)==''||!$.trim(degree)==''||!$.trim(dateFrom)==''||!$.trim(dateTo)=='') {
$("#list").append("<li>Name: "+$('#elem1').val()+
"<br>Degree: "+$('#elem2').val()+
"<br>Date From: "+$('#elem3').val()+
"<br>Date To: "+$('#elem4').val()+
"</li>");
cancel.click();
} else {}
});
Please take a look to the code on jsFiddle here: http://jsfiddle.net/vrpWu/
Click on "Add another"
Note that it works without the if condition, why is this happening? I've readed everywhere but looks like my code is not wrong.
First, you have to get the values when you actually click the save button, not before, as then the values will always be empty strings
var save = $("<input type='submit' value='Save' />").on('click', function () {
var name = $("#elem1").val();
var degree = $("#elem2").val();
var dateFrom = $("#elem3").val();
var dateTo = $("#elem4").val();
if (!($.trim(name) == '' || $.trim(degree) == '' || $.trim(dateFrom) == '' || $.trim(dateTo) == '')) {
console.log('test')
$("#list").append("<li>Name1: " + $('#elem1').val() +
"<br>Name2: " + $('#elem2').val() +
"<br>Name3: " + $('#elem3').val() +
"<br>Name4: " + $('#elem4').val() +
"</li>");
cancel.click();
} else {
console.log('no')
}
});
then you should note that things work a little differently when you negate the variables and use OR
You can either negate the whole thing at once
if (! ($.trim(name)==''||$.trim(degree)==''||$.trim(dateFrom)==''||$.trim(dateTo)=='')) {
or use AND instead
if (!$.trim(name)=='' && !$.trim(degree)=='' && !$.trim(dateFrom)=='' ... etc
FIDDLE
Ive got some javascript im using to validate a form which works fine but I now need to add a checkbox which needs to be checked before the form submits. The name of the checkbox is terms in the html and ive managed to get it to not submit the form using the code below.
$(document).ready(function(){
$("#sendmail").click(function(){
var valid = '';
var isr = ' is required.';
var name = $("#name").val();
var mail = $("#mail").val();
var subject = $("#subject").val();
var country = $("#country").val();
if( !$("#terms").is(":checked") ){
valid += '<br />Please accept the terms and conditions.';
}
if (name.length<1) {
valid += '<br />Name'+isr;
}
if (!mail.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<br />A valid Email'+isr;
}
if (subject.length<1) {
valid += '<br />Website Link'+isr;
}
if (country.length<1) {
valid += '<br />Country'+isr;
}
if (valid!='') {
$("#response").fadeIn("slow");
$("#response").html("Error:"+valid);
setTimeout('$("#response").fadeOut("slow")',4000);
}
else {
var datastr ='name=' + name + '&mail=' + mail + '&subject=' + subject + '&country=' + country;
$("#response").css("display", "block");
$("#response").html("<img src='http://infashionation.com/female/images/response.jpg'>");
$("#response").fadeIn("slow");
setTimeout("send('"+datastr+"')",2000);
}
return false;
});
The problem is it now doesnt submit regardless of whether box is checked or not.
Ive been searched for some information to help me with this for a while but no luck so thought I would ask here to see if anyone can help me.
There appears to be an extra exclamation point after the valid variable. I suggest also using a javascript debugger.
if (valid!='') {
You're missing a closing curly brace for your .ready function.
It doesn't look like you've closed the $(document).ready() function. You close the sendmail click function, but not the main function. I think the tail end of your code should look like this:
}
return false;
}); // close sendmail function
}); // close document.ready
If that happened because of copying it to SO, then disregard this, but if this is in your code, your browser will probably not do a thing and appear not to react to the JavaScript.
Please excuse my lack of javascript seasoning. I currently have two parts to my validation:
1. functions that apply css decoration to the input fields and makes the div that contains the error message visible
2. a function that aggregates the above functions and is called in the form ie, onSubmit="(return validate();)"
I wish to fix two things:
1. Refactor code so as to make it smaller
2. FIXED with code update. Apply selector text decoration to all empty fields. Currently, the decoration is applied to the first empty field then once a text value is entered, it hits the next field. Every empty field should be validated and show proper decoration.
/** VALIDATION DECORATION **/
function validateAccountNameRequired(textInputId, textInputLabelName) {
var valid = true;
if (!$('input#accountName').val()) {
$('input#accountName').addClass('inputError');
$('ul#accountNameList').find('div.error').attr('style', '');
valid = false;
} else if ($('input#accountName').val()) {
$('input#accountName').removeClass('inputError');
$('ul#accountNameList').find('div.error').hide();
}
return valid;
}
function validateAccountBusOrgIDRequired(textInputId, textInputLabelName) {
var valid = true;
if (!$('input#accountBusOrgID').val()) {
$('input#accountBusOrgID').addClass('inputError');
$('ul#busOrgList').find('div.error').attr('style', '');
valid = false;
} else if ($('input#accountBusOrgID').val()) {
$('input#accountBusOrgID').removeClass('inputError');
$('ul#busOrgList').find('div.error').hide();
}
return valid;
} /** VALIDATORS **/
function validate() {
valid = validateAccountNameRequired('accountName', 'Account Name');
valid1 = validateAccountBusOrgIDRequired('accountBusOrgID', 'Account Bus Org ID');
return valid && valid1;
}
I resolved my own issue. Hopefully someone else can benefit:
Validates all fields at once
Refactored for better cohesion, just load values in function validate() and reuse one function validateTextRequired():
function validateTextRequired( textInputId, errorListId)
{
var valid = true;
if( !$('input' + '#' + textInputId).val())
{
$('ul' + '#' + errorListId).find('label').addClass('error');
$('input' + '#' + textInputId).addClass('inputError');
$('ul' + '#' + errorListId).find('div.error').attr('style','');
valid = false;
} else if ($('input#' + textInputId).val()) {
$('ul' + '#' + errorListId).find('label').removeClass('error');
$('input' + '#' + textInputId).removeClass('inputError');
$('u' + 'l#' + errorListId).find('div.error').hide();
}
return valid;
}
function validate()
{
valid = validateTextRequired( 'accountName', 'accountNameList');
valid1 = validateTextRequired( 'accountBusOrgID', 'busOrgList');
valid2 = validateTextRequired( 'acctMgr', 'accountMgrList');
}