Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have written the following JS, and it gets the job done, but I have been having a ton of trouble eliminating the repeating code. I keep breaking the functionality.
It's just field validation using a regex, and adding an error message below the appropriate field if the input doesn't match the regex. It's works, but but I really want to begin writing more succinct code.
If someone can help me do this, I can compare mine and yours and start understanding how to approach this type of task.
Thanks.
<form></form>
Here's my JSFiddle code: https://jsfiddle.net/robinburrage/cnL2d4w8/2/
You can reuse the same function for all the 2 validations. The only difference between the 3 functions is that you are trying to append to a different id.
Use this instead of referring to the element specifically, since the input is anyways bound to the element you are looking for.
phone.addEventListener('keyup', validatePhone);
phone2.addEventListener('keyup', validatePhone);
phone3.addEventListener('keyup', validatePhone);
function validatePhone(evt) {
var pattern = /^(\(\d{1,2}\)\s)?\(?\d{4}\-\)?[\s.-]?\d{4}$/; //set the regular expression
var str = this.value; //get the user's input
var phoneVal = document.getElementById("phoneVal");
if (phoneVal) { //if the error message div is already on the page
phoneVal.parentNode.removeChild(phoneVal); //remove it, to prevent a series of error message divs from accumulating
}
if (str === "") {//if there is no user input
phoneVal.parentNode.removeChild(phoneVal);//remove the error message
}
if (pattern.test(str) === false) { //if the string doesn't match the expression
var elem = document.createElement("div"); //create a DIV
elem.setAttribute("id", "phoneVal"); //give it an 1)id, 2)class and 3)message
elem.setAttribute("class", "form-error-msg");
if(window.location.href.indexOf("/en") > -1) {
elem.innerHTML = 'Please enter a valid telephone number.';
}else{
elem.innerHTML = 'Por favor introduce un número de teléfono válido.';
}
this.parentNode.appendChild(elem); //add the div with the current error message
}
} //end function
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to check through the elements of the website for my code, but I can't understand how to do it with puppeteer on Node.JS
Here's the code I tried:
if(page.content('input[data-kwimpalaid="1580983806648-1"]'))
found = true
if(found = true)
console.log("I found it")
if(found = false)
console.log("I didn't found it")
So what I need basically, I have a website with element ID's ending in 1 to 20, and it can be random, and consecutive. For example it may start at 1, then has 6 ids (1,2,3,4,5,6) or it can start at 5 (5,6,7,8,9,10). I want to check for every ID, and if it exists then change the value of ''found'' to true. If the page doesn't have id 1, try id 2, id 3, id 4, etc.. until it finds an input with that ID/CLASS that exists on that website.
Shortly, I need to check if the selector element I use exists on the website or not (content).
Hm, what about this? On top of my head!
let found = false;
const allInputs = page.content('input[data-kwimpalaid]'); // Assuming an Array of elements here
for (let i = 1; i < 6; i++) {
if (allInputs.find((input) => input.dataset.kwimpalaid.startsWith(i))) {
found = true;
break;
}
}
if (found) {
console.log("I found it");
} else {
console.log("I didn't found it")
}
So basically scan the document once for all elements with an ID.
Then look at each element individually.
The for-loop respects your preference.
If an element is found Array.prototype.find will return it. Otherwise, its return value is undefined.
I'm assuming here, that puppeteer behaves similar to DOM in browser. Someone else might correct me, if that isn't the case.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to validate that two characters and a number were correctly input.
var studentValid = /^[MTWTF][AL][1-9]$/i;
if (studentValid.test(studentTemp.value))
{
alert("true");
}
else
{
alert("false");
}
Yet everything I enter turns out false?
The problem is with your regexp (/^[MTWTF][AL][1-9]$/i). What this tells you is that you first want one of the characters M,T,W,T or F, and after that either A or L and finaly a number (and nothing before or after this).
So for example
ML4, WA5, FL9
will give you true
while
AM9, ML0, MMA5, MA99
will give you false.
Is this the pattern you are trying to match? There is nothing else wrong with your code and a valid value will give you true, for example:
var studentValid = /^[MTWTF][AL][1-9]$/i;
var value = 'MA9';
if (studentValid.test(value))
{
alert("true");
}
else
{
alert("false");
}
When working with regexp, it can be very usefull to use a tool to help you build it, check out https://regex101.com/r/A5FOIh/3 where you can try your different studentTemp.value to see if they match.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
JQuery selector with multiple conditions Email Validation
hi i have to validate Email address.
my following code works fine:
contact_email = $('#contact_email').val();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
//if Email address is empty it allowed but if it have any value then check whether proper email address or not
if(contact_email && !reg.test(contact_email)) {
err += 1;
$('#contact_email').addClass('boxerror');
}
it works but following code not work
contact_email = $('#contact_email').val().is(reg.test(this.val())).addClass('boxerror');
1.what mistake i had done?
2.JQuery with selector with multiple condition is possible
You are misunderstanding how .is(...) works. You have to pass a jquery selector in is() function, or you can also pass a function which will be called by jquery for all the function. And it will return a boolean value.
To accomplish your task you will be needed to use filter(...).
Here is the code to help you :
$("#contact_email").filter(function(index, element) {
return !reg.test(element.value);
}).addClass("boxerror");
Full documentation for filter() is here
Hence :
Mistake: you were using is() in wrong situation.
selector with multiple condition is possible if implemented jquery nicely.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Hello I really want to learn how to do something like this. If you go to a page for example it says http://example.net/search.html?catagory=food&includelevelone=true. I do not have access to php so it can only be HTML and Javascript/jQuery. Thanks in advance!
The part of the URL that is from the questionmark onwards is called a query string.
Here is a pure JavaScript function to parse the query string to obtain particular values:
function querystring(key)
{
var filter;
var value;
key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
filter = new RegExp('[\\?&]' + key + '=([^&#]*)');
value = filter.exec(window.location.search);
if(value == null)
{
return '';
}
else
{
return decodeURIComponent(value[1].replace(/\+/g, ' '));
}
}
You just pass in the query string key name you're interested in (as a string) and you get the value back (also as a string.) An example of how you could use the function:
alert('Category = ' + querystring('catagory'));
Everything behind the questionmark is a url parameter. every word left of an equal sign is the name of the parameter, everything right of an equal sign is the corresponding value. The name-value-pairs are divided by &-signs
Here are two pages i quickly googled that are about getting these parameters in JavaScript (wich is really not that hard):
http://code-tricks.com/get-url-parameters-using-javascript
http://ziemecki.net/content/javascript-parsing-url-parameters
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm currently learning HTML 5 + javascript, and one of the examples I'm looking at is written in JQuery. I realise that JQuery would be simpler to some people, but as I am just coming to terms with Javascript and no nothing of JQuery, I'm looking to get some lines of code translated from one to the other.
I know what these lines of code does, I'm just looking for it in JavaScript.
var showForm = function() {
if(editMode) {
var transaction = transactions[editMode];
amountField.value = transaction.amount;
if(transaction.type) $('[value='+transaction.type+']').attr('checked', 'true');
if(transaction.cleared) $('#cleared').attr('checked', 'true');
noteField.value = transaction.note;
dateField.value = transaction.date;
$('#time').val(transaction.time);
postcodeField.value = transaction.postcode;
searchField.value = ''
} else {
clearUI();
}
$('#formDiv').show();
$('#toolbar').hide();
$('#tableDiv').hide();
$('#map_div').hide();
$('#sum').hide();
Replace the lines where ever you select the element by ID with the corresponding ID
$('#cleared') ---> document.getElementById('cleared')
you can also use querySelector metod to access the element directly.
var cleared = document.querySelector('#cleared');
To show or hide a element you would need to set the style.display property
// To hide
cleared .style.display = "";
// To show
cleared .style.display = "block";
To get the element based on the attribute would be a bit of javascript..
$('[value='+transaction.type+']')
Where in you would need to iterate over each element and get the attribute of that element and then compare with the value.