HTML5 local storage, validating required text box issue - javascript

I have a survey. On button click need it to validate certain fields required/store locally/ go to confirmation page(to prevent user from resubmitting). Only 'FirstName''Hostipal' required atm.
Problem is when all required fields are filled, it fails to go to confirmation.html. If i leave 1 required field open, It doesnt validate and goes to confirmation. If all 'required' syntax is taken out, It doesnt go to confirmation
<label>First Name*:</label> <input required title="Name is required" id="FirstName" name="MainName" type="text"/>
In all cases, It still stores to local storage however. Any input on validating required fields would be appreciated. Hopefully can put it in my clicked() function.
<button type="submit" value="Save" id="Save" >Submit Form</button>
function
$( document ).ready(function() {
$('#Save').click(function (e) {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
}
});
});
If the above doesn't show my problem, here is the whole: http://jsfiddle.net/smZHe/1/

each helper method in jquery executes the function we pass to it once for each item in the initial array. You are trying to execute below statement multiple times (once for each input, select, textarea).
window.location.href = "Confirmation.html";
You can use a variable instead as flag to mark validation failure. In the end, you can check variable and navigate conditionally.

Related

How to call variables from different events together?

I am trying to learn how to call variables from different events.
I have 2 inputs, without a submit button. So, the way I get the value is by using the keyup event.
My Code:
function myPhone() {
$("#phone").keyup(function() {
var phone = $(this).val();
});
return phone;
}
function myEmail() {
$("#email").keyup(function() {
var email = $(this).val();
});
return email;
}
function myValidation() {
var myPhone2 = myPhone();
var myEmail2 = myEmail();
alert(myPhone2 + " - " + myEmail2);
}
myValidation();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="phone" id="phone" placeholder="phone">
<input type="text" name="email" id="email" placeholder="email">
Explanation Behind My Code:
First, I create a function called myPhone() where it saves the value of what has been inserted by the user based on keyup. I do the same for email and create a function myEmail().
Now, I created another function named myValidation and tried to call the values I get in myPhone() and myEmail() and then I try to display the values in an alert box.
But, this is not working for me. I can see that it will alert upon page load, and show undefined, which makes sense for me.
But why is it not tracking the keyup event? And why is the 2 variables not getting called in? Have i done it wrongly? Can someone please guide me on this with explanation?
You're trying to alert both values even if the event isn't yet triggered. You should
Create a global access to the email and phone variables, could also be an object
Attach the event first
Run myValidation() after both events are triggered, adding a flag to do so;
Alert the values from the global scope
Following your code, you can:
//Create global variables
var phone, email;
//Create function to attach events
function setEvents(){
//switched to change event
$( "#phone" ).change(function() {
phone = $(this).val();
myValidation(); //call after
});
$( "#email" ).change(function() {
email = $(this).val();
myValidation(); //call after
});
}
//Prepare myValidation() function to call after both events are triggered
function myValidation() {
//Check if phone and email exists before alerting from the global scope
if(phone && email) alert(phone + " - " + email);
}
setEvents(); //initiate function to attach events to element
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="phone" id="phone" placeholder="phone">
<input type="text" name="email" id="email" placeholder="email">
But like others said, you can just directly get $(element).val() without any variables at play; but we are following from your logic which I think is much better for a direct answer to the problem.

Not able to reset input field in laravel

I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
JS for reset button:
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
Reset Button:
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
Use type="reset" for your button:
<button type="reset">Cancel</button>
try using reset():
document.getElementById("app_number").reset();
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.
$('#app_number').on('change', function () {
// enter code here
});
Please try to use in js like:
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
So answering my own question, any feedback would be appreciated but this is working.
It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.
So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.
I added onkeyup event ion to the input field
<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
and JS to store and retrieve input
document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input
function saveValue(e) {
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return ""; // You can change this to your defualt value.
}
return localStorage.getItem(v);
}
and then reset the form as usual
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
Your reset button :
<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
In js:
function myFunction(){
document.getElementById("app_number").value = "";
}

Simulated chatbot that switches input methods?

I have a chatbot I created that asks for a user's username, then stores it as a variable. However, in one of my dialog trees, I have to ask the user for them to type another answer, I have it working so that user's can navigate via button clicks.
On username capture, the "input bar" is removed from controls and I append buttons with each message function. I tried to do the inverse of this (remove buttons and add an input) which does work, however I can't get my input to do anything. It won't submit on enter, it won't save a variable and in my trial and error, I found that if I try to set a var off that msg value, it updates the username's.
Here is my function to retrieve name
function get_username() {
send_msg("Hello I'm Mumbles, the Help Bot", function(){
send_msg("Who am I speaking with today?")
});
}
function ai(msg) {
if (username.length < 3) {
username = msg;
send_msg("Nice to meet you"+username+". What are you working on today?" , function() {
$("#controls").append(
'<button class="options one" value="my_certifications" type="button">My Certifications</button>' +
'<button class="options one" value="videos"type="button">Videos</butto/>' +
'<button class="options one" value="login"type="button">Login</butto/>' +
'<button class="options one" value="other"type="button">Other</butto/>'
);
});
}
// Remove text bar
$("#controls").empty();
};
Here is my function to try and capture email
} else if (b_val == "my_practicum") {
send_msg("What is the email address you submitted your practicum with? By having this we can give you a status update!" , function() {
$("#controls").append(
'<textarea id="message" class="practicum-bar" placeholder="Type Your Name - Then Hit Enter"></textarea><button style="display:none;" id="sendMsg">Send</button>' );
email = msg;
console.log(email);
});
}
}
If you want to see this in action, here my JSFiddle. You can see it by going through this user path
Enter name > Certifications > My Practicum > Enter email
Any help on this is appreciated! Thanks!
It looks like you remove controls by doing $("#controls").empty(); and you want to add an event to a dynamically created element so you have to add the context to the second parameter of the .on. look now you can see the console.log in the fiddle the second time you clicked enter because jquery can detect the item now.
$("#controls").on("keypress", "#message", function(event){
if (event.which == 13) {
console.log("my test");
if ($("#slideThree").prop("checked")) {
$("#sendMsg").click();
event.preventDefault();
//*edit you can now change variables outside of scope*
}
}
});
now you can do your event handling.

Linking form and button to javascript command

I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO

Always returns a undefined value

I am using jQuery to send Ajax request to the server to save the values being input in the form. Below the section where I am stuck. The HTML is as
<span class="no-margin multiple Date_Off" style="margin-left: 104px;">
<input type="text" value="" /><input type="text" />
<input type="text" value="-" /><input type="text" />
<input type="text" /><input type="text" value="-" />
<input type="text" /><input type="text" /><input type="text" />
<input type="text" />
</span>
I have tried using jQuery to send the request. What I want to do is something like this
I want to save the values from the form, to the same Column_Name that the input fields have. In the multiple input fields I am not using input names. Instead I am using a classname which is identical to the Column_Name in the database.
For that, I am using $(this).parent().attr('class');. If I use this in an alert, it gives me the result without error. But if I use it in the code, it gives me undefined.
I want to append each input's value to the string to save it as a single string.
Here is what I tried so far
var input = $('input');
input.change(function () {
// Input click function...
if ($(this).parent().attr('class')
.replace(' multiple ', '')
.replace('no-margins', '') == 'Date_Off') {
// Date Time for the office work!
var value = '';
value = $(this).parent().find('input').each(function (index, ele) {
value += ele.val();
});
send_request('Date_Off', value);
// Below is the else condition, to execute only when the input is single
// Like a single string input and not like the one in image
// That's why I am using attr('name') for that.
} else {
send_request($(this).attr('name'), $(this).val());
}
});
But what it returns is always a undefined in the Query structure. Here is the function for that
function send_request(input_name, value) {
$.ajax({
url: '/ajax_requests/save_form',
data: 'input_name=' + input_name + '&form_id=' +
$('input[type=hidden]').val() + '&value=' + value,
error: function () {
$('.main-content').append(
'There was an error in request.
Please contact your website Developer to fix it.'
);
},
success: function () {
}
});
}
Image for the code execution
The input in focus was 1. Date. And the console shows the Internal Server Error. Because jQuery sent the request with input_name=undefined which is not a Column_Name.
I have created a (Mini) fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/EHWqB/
Any help here?
For the fiddle that you posted, there were two errors. The first was you were calling ele.val(), but ele in this context is not a jQuery object - so you need to get the value property off of it. The second is that the jQuery each function operates on an array of objects and it's return value is that array of objects. You don't want your value, which should be a string, to be accepting that return value. Here is an updated, working fiddle
input.change(function () {
// Input click function...
var value = '';
$(this).parent().find('input').each(function (index, ele) {
value += ele.value;
});
send_request('Date_Off', value);
});
In this line you're trying to get the name of the input
send_request($(this).attr('name'), $(this).val());
I don't see a "name" attribute anywhere in your code, I think what you want is to get the class of the parent instead?
send_request($(this).parent().attr('class'), $(this).val());

Categories

Resources