how do I know user info submited? - javascript

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

Related

Submit button and input validation?

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.

How to print random string from a selection of user form inputs javascript/jquery

var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?

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...

Regular expression on textarea

I'm having a bit of trouble validating a form I have, I can check for only letters, numbers and a full stop ("period") in a single text input, but I can't for the life of me get it to work at all on a textarea field.
in my validation I have this:
var usernamecheck = /^[A-Za-z0-9.]{5,1000}$/;
the validation I've tried that doesn't work on the textarea ($ITSWUsers) is:
if(!document.all.ITSWUsers.value.match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
however, the following on a 'input type="text"' works just fine on the same form
if(!document.all.SFUsersName1.value.match(usernamecheck))
{
alert("Usernames can only contain letters, numbers and full stops (no spaces).");
return false;
}
I need it to validate usernames, 1 name per line
e.g.
John.smith
Peter.jones1
these are both OK but the following wouldn't be:
John Smith
David.O'Leary
3rd.username
any help/pointers with this would be greatly appreciated
(I only know basic html/php/javascript)
To validate line by line, I'd use the split function to turn each line into an array. Then, loop through the array and run your RegEx on each line. That way, you can report exactly what line is invalid. Something like this:
<textarea id="ITSWUsers"></textarea>
<button onclick="Validate()">Validate</button>
<script>
var usernamecheck = /^[A-Za-z0-9]{5,1000}\.[A-Za-z0-9]{5,1000}$/;
function Validate()
{
var val = document.getElementById('ITSWUsers').value;
var lines = val.split('\n');
for(var i = 0; i < lines.length; i++)
{
if(!lines[i].match(usernamecheck))
{
alert ('Invalid input: ' + lines[i] + '. Please write the usernames in the correct format (with a full stop between first and last name).');
return false;
}
}
window.alert('Everything looks good!');
}
</script>
I'd trim the input from the textarea using JQuery (or a JS function), and then use this regex:
/^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/
Like so:
function testFunc()
{
var usernamecheck = /^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/;
if(!$.trim(document.all.ITSWUsers.value).match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
}
<textarea id="ITSWUsers" cols="50" rows="10">
John.smith
Peter.jones1
</textarea>
<button onclick="testFunc()">Click Me</button>
See it working here:
http://jsfiddle.net/DkLPB/

Best way to add/show additional form fields

I am hoping for some insight on the best way to accomplish the following. I want to create a form that will allow for more fields to be added when a + or add button is clicked. So for example the user would fill out a text field lets call it "Description" and then next to it another field called "Unit number". I want to allow for multiple "Description" and "Unit number" fields without submitting the form after each entry, but for the sake of keeping the site looking "Clean" I don't want there to be several duplicate fields if the user only needs to enter information into one of them. I was thinking about using JavaScript to hide the additional fields by just setting display:none. Is this a good/efficient solution? Is there a better solution? I am new to programming so take it easy if you feel this is a dumb question.
The best way to do this is to make your fields and put them in a div and then hide it. Use jQuery to .clone your first row and then update the field names any time the user clicks an add link.
You can use a templating library like mustache or handlebars. You can also do this using jQuery. My approach would be to generate new elements on the fly. I won't hide it so that the user can see if he is already inputting duplicate. But if you want to make your markup cleaner, you can also hide the field once the user has already inputted something. So when the user clicks on the add button, you will need to check if the user has actually inputted something, if there is an input, then hide it and then generate a new input again.
If you need a code sample, feel free to ask.
Here's some javascript I wrote on my own site awhile ago:
var SITE = SITE || {};
SITE.fileInputs = function() {
var $this = $(this),
$val = $this.val(),
valArray = $val.split('\\'),
newVal = valArray[valArray.length-1],
$button = $this.siblings('.button'),
$fakeFile = $this.siblings('.file-holder');
if(newVal !== '') {
$button.text('File Chosen');
if($fakeFile.length === 0) {
$button.after('<span class="file-holder">' + newVal + '</span>');
} else {
$fakeFile.text(newVal);
}
}
};
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span class=\"file-wrapper\"><input type=\"file\" name=\"screenshot[]\" id=\"screenshot\" /><span class=\"button\">Choose a screenshot</span></span>";
document.getElementById(divName).appendChild(newdiv);
counter++;
$('.file-wrapper input[type=file]').bind('change focus click', SITE.fileInputs);
}
}
$(document).ready(function(){
$("#addss").click(function(){
addInput("screenshots");
});
});
Then you can just use the array for the name in the php or whatever else you're using to handle the data.
HTML:
<div id="screenshots">
<span class="file-wrapper">
<input type="file" name="screenshot[]" class="screenshot" />
<span class="button">Choose a screenshot</span>
</span>
</div>
<input type="button" id="addss" value="+Screenshot" class="btn" />

Categories