Submit button and input validation? - javascript

I would like to change this code to work also when Enter is pressed to be more clear i got an submit form and an text field following with the submit button that has to be clicked to submit but that doesn't help me out as i need the form to recognize when enter is pressed, what would be the change to sort it out?
submitButton.onclick = function() {
index = 0;
results = [];
username = usernameInput.value;
if ( username.length > 0 ) {
window.location.href = '//' + window.location.host + window.location.pathname + '#' + username;
usernameInput.disabled = true;
submitButton.disabled = true;
getExistence();
}
Also i got an issue with input validation, what change should i made to allow the form recognize and accept special characters?
usernameInput.onchange = function() {
this.value = this.value.replace(/[^a-z0-9]+/ig, '').slice(0, 40);
var urlUsername = window.location.href.match(/\#([0-9a-z]{1,40})$/i)
I would ask from you to be more specific as i am new to javascript coding, and my knowledge it's not enough to sort it easily.

First solution is to read this.
https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
You get info why "button type="submit" is better way than adding that into JS.
I think, solution for your problem can be something like that:
<form>
<label for="age">Age:</label>
<input type="number" min="0" max="120" name="age" id="age">
<button id="child">Child</button>
<button id="adult">Adult</button>
</form>
<script>
(function() {
var age = document.getElementById('age');
age.addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
if (age.value > 20) {
document.getElementById('adult').click();
} else {
document.getElementById('child').click();
}
}
});
}());
</script>
In short, commenting your code:
submitButton.onclick = function() { ... your code
This work as you describe, onclick. You can have similar function with :
submitButton.onkeypress = function() { ... same code with checking keyCode as example above
Validation: the simplest way to create any Regex is by doing some real test. I'am personally prefer this site: https://regex101.com/
What "special" character you mean? Because nobody can help right now. More info in this particular example. You just don't need any RegEx for JS. Accept any char and do everything on backend.

Related

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Append URL from user input and go

I'm trying to get a input box that a patron could type in a word and it would take that input and append a URL in the middle.
link example would be https://proxyaddress/login=?url=http://libraryaddress/database/SearchResults.jsp?result_start=0&result_items=48&result_layout=GRID&query1_modifier=AND&query1=USERSEARCHTERM&query1_field=CONTENT
where the part changed by input would be USERSEARCHTERM
I've found solutions online but they all just load the proxy address and stop there.
Any help would be greatly appreciated, thanks!
The proxy address will need to be corrected to a valid DNS (.com,IP) But this captures the user input, concats the input with the URL format and changes the window location.
You'll also want to prevent XSS on any user input on the backend.
<form id="my-form">
<input type="text" id="search">
<button type="submit">Search</button>
</form>
var form = document.getElementById('my-form');
var input = document.getElementById('search');
function processForm(e) {
if (e.preventDefault) e.preventDefault();
var inputVal = input.value;
var combinedUrl = "https://proxyaddress/login=?url=http://libraryaddress/database/SearchResults.jsp?result_start=0&result_items=48&result_layout=GRID&query1_modifier=AND&query1=" + inputVal + "&query1_field=CONTENT";
window.location.href = combinedUrl;
alert(combinedUrl);
return false;
}
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}

Generating search links using text input in javascript

Im trying to make a website which makes searches easy for me.
I want to be able to write any text in a text box, and make a java script generate the appropriate links.
Ive been trying this:
function prepare_link() {
var url_param = document.getElementById('url_param');
var target_link = document.getElementById('target_link');
if ( ! url_param.value ) {
return false;
}
target_link.href = target_link.href + escape(url_param.value);
}
<input type="text" name="url_param" id="url_param" onkeypress='prepare_link()' onKeyUp='prepare_link()' />
<input type="button" onclick="prepare_link();" value="Generate" /><br>
Google<br>
Bing
For some reason the search string is repeated, but i would like it to update links for each keypress and not just when i hit the generate button.
Moreover the second links isn't being updated :(
Any ideas? :)
Please have a look of the following code snippet, hope this will help to resolve your Issue.
In the following snippet you will not get the repeated values. Also, it will work with 'keyup' and 'click' event :
var google = "https://www.google.dk/search?q=";
function prepare_link() {
var target_link = document.getElementById('target_link');
target_link.href = google + escape(url_param.value);
alert(target_link.href);
}
void function () {
document.addEventListener("keyup", function(e) {
prepare_link();
e.preventDefault();
});
var click = document.getElementById("target_link");
click.addEventListener("click", function() {
document.dispatchEvent(keyEvent);
});
}();
<input type="text" name="url_param" id="url_param" value=""/>
<input type="button" value="Generate" onclick="prepare_link();" /><br>
Google<br>
Thanks :)

how do I know user info submited?

This is what i have http://jsfiddle.net/bd9wv/... what i am trying to do is have boxes users can input numbers in, and be able to comment back based on the numbers they gave..what i have works for one only...if someone would not mind telling me...what holds the input, i think it's var val? i think i should be able to add more boxes. exp... var al id="number1" type="text"/> ...and then in js..... msg = 'Thank you for the wonderful number: ' + (val+al); but that does not work for me. i would like maybe 10 boxes..but 2-3 is good for me to see how it is done. what i am not understanding is what holds the input and how to use it...explaning a little would be great, i think the submit might be getting me. but if you have an example i can look at it an figure it out,i will be very thankful!!
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Keeping much of your code in place you can make this work. I changed your ID's to classes, since there will be multiple similar elements. I modified a piece of your JS to the following:
var val = $(this).prev(".number").val();
var $outputDiv = $(this).next().next(".feedback");
Using this you can find the closest elements to the input the user was typing.
And your HTML:
Enter number: <input class="number" type="text"/>
<button class="btnNumber">Submit</button>
<br/>
Feedback: <div class="feedback"></div>
Demo: http://jsfiddle.net/bd9wv/1/
I could not understand clearly; but please try whether this work for you or no http://jsfiddle.net/bd9wv/2/
Example:
var val = $(this).parent().find('.number').val();
Here I have used class and have surround the html block with another div

javascript function inside function

I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...

Categories