Using parse.com and javascript/jquery.
The below code should capture the input from the user in the "friendsearch" input box.
Once the submit button is clicked, it should query the parse.com backend and find out if the user exists. At the moment I keep getting "undefined" returned in "friendName" which I cannot spot why or what is causing the error?
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" required/>
<button type="submit" class="btn btn-login">Find</button>
</form>
var friendName;
$('#friendsearch').on('keyup', function(e) {
friendName = $(this).val();
});
var friendFinder = Parse.Object.extend("_User");
var query = new Parse.Query(Parse.User);
query.equalTo("username", friendName); // find users that match
query.find({
success: function(friend) {
alert(friendName);
},
error: function (error) {
//Show if no user was found to match
alert("Error: " + error.code + " " + error.message);
}
});
Ok, I revised your code so that the friendName variable actually contains the contents of the input box on your form. The problem was that your original code was trying to get access to the contents of your input box before it was even loaded into the DOM.
Try this for your HTML:
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" />
<button id="find_button" type="submit" class="btn btn-login">Find</button>
</form>
And this for your javascript:
var friendName;
function findFriend(){
friendName = $('#friendsearch').val();
alert(friendName);
var friendFinder = Parse.Object.extend("_User");
var query = new Parse.Query(Parse.User);
query.equalTo("username", friendName); // find users that match
query.find({
success: function(friend) {
alert(friendName);
},
error: function (error) {
//Show if no user was found to match
alert("Error: " + error.code + " " + error.message);
}
});
}
$('#find_button').click(function(e){
findFriend();
});
I updated the live jsFiddle example here: http://jsfiddle.net/LWA48/2/
In the jsFiddle example, the Parse object prints {"error": "Please use POST request"} when you click the button, but at least your friendName variable contains the name you typed in the box! Hopefully, this can take you the rest of the way.
I believe the problem is where you're assigning friendName = $(this).val();
Try using e.target to get a reference to the value currently in the text input box. I'm not sure if it's e.target off the top of my head but I'm fairly certain that you want a property contained inside the e argument.
Try $(e.target).val() or $(e.currentTarget).val() something like that instead of $(this).val();
What I also like to do when I'm trying to figure out why something isn't being set properly is to set a breakpoint in the chrome debugger. In this case, you can put 'debugger' in your code where you want the browser to break on. So in your example, you could write this:
$('#friendsearch').on('keyup', function(e) {
debugger
friendName = $(this).val();
});
And in your Chrome Dev Tools you can inspect the value of e and determine what properties and values are available.
Related
Am trying out NFC reading in phonegap. I have managed to read the NFC but now am stack on how I can show results on the input text. I got help on How to show QRC scan results on Input text but the problem is the implementation of "$('#v')=val.(vv);" breaks or deactivates NFC reading. Is there another way in which I can get these values...
Js for Reading
onDeviceReady: function() {
app.receivedEvent('deviceready');
// Read NDEF formatted NFC Tags
nfc.addTagDiscoveredListener (
function (nfcEvent) {
var tag = nfcEvent.tag,
ndefMessage = tag.ndefMessage;
alert(JSON.stringify(ndefMessage));
alert(nfc.bytesToString(ndefMessage[0].payload).substring(3));
//Getting values on Input
var vv = (nfc.bytesToString(ndefMessage[0].payload).substring(3));
$('#v')=val.(vv); -----this breaks the reading.
},
function () { // success callback
alert("Waiting for NDEF tag");
},
function (error) { // error callback
alert("Error adding NDEF listener " + JSON.stringify(error));
}
);
}
Input Form as follows:
<form id="Insert" method="POST">
<input type="text" name="v" id="v" value=""/> ---------Values of NFC should show here after the alert
</form>
it breaks the reading because that's not the right code to change the input value, try this:
$('#v').val(vv);
If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-
So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>
I am trying to retrieve two strings from my Parse Customers class. I want to compare these strings (usernameAdmin, and passwordAdmin respectively) with the input field entered by the user, and if they matched it will take them to a specific page.
I am taking this approach for a particular reason, and would appreciate feedback.
$scope.logIn = function(form) {
var Customer = Parse.Object.extend("Customers");
parseAdminUsername = Customer.get('usernameAdmin');
parseAdminPassword = Customer.get('passwordAdmin');
if (form.lusername == parseAdminUsername && form.lpassword == parseAdminPassword) {
window.location = 'adminSelect.php'
} else {
alert('error');
}
};
The html code looks as follow:
<form role="form" ng-show="scenario == 'Sign up'">
<h4 id="wrongCredentials"></h4>
<input id="signupformItem" ng-model="user.lusername" type="email" name="email" placeholder="Email Address"> <br>
<input id="signupformItem" ng-model="user.lpassword" type="password" name="password" placeholder=" Password"> <br>
<br>
<button id="signupbuttonFinal" ng-click="logIn(user)" class="btn btn-danger"> Sign In</button>
</form>
I receive the following error on console:
undefined is not a function
at Object.$scope.logIn
below is the line
parseAdminUsername = Customer.get('usernameAdmin');
You are better off using Parse in built users instead of creating a separate object and then you would use Parse.User.logIn.
If you were to use your table instead. Customer.get('usernameAdmin') is used to return a field after you have performed a query to return records/s. You are best to perform a find query to check the username and password like so:
var Customer = Parse.Object.extend("Customers");
var query = new Parse.Query(Customer);
query.equalTo("usernameAdmin", form.lusername);
query.equalTo("passwordAdmin", form.lpassword);
query.find({
success: function(results) {
if (results.length > 0) {
window.location = 'adminSelect.php';
}
},
error: function(error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
I'd recommend not to use window and instead $window so that you can unit test your code. Better yet use angular routing and create a Single page app.
I'm using the Data module from Parse. I'm using HTML to create an email form. I use Javascript to get the form data (email), and then generate a username from the email address. This information is then saved to the Parse database.
Here's the HTML form code:
<form method="post" class="center">
<input id="email" name="email" type="email" placeholder="Type your email to create a Mail Link" />
<button id="submit" onclick="formSubmit();">Create</button>
</form>
Here's the Javascript:
function formSubmit() {
var emailValue = document.getElementById("email").value;
var userValue = emailValue.substr(0, emailValue.indexOf('#'));
Parse.initialize("---KEY---", "---KEY---");
var Users = Parse.Object.extend("Users");
var users = new Users();
users.save({username: userValue}).then(function(object) {
alert("Saved user");
});
users.save({email: emailValue}).then(function(object) {
alert("Saved email");
});
}
The problem is that the console is showing that the values are saved, however the data isn't saved into Parse.
Any ideas would be greatly appreciated!
In can make button a simple button, no need to change the button to a button as mention in the link you've mentioned, your code'll work fine.
You've written .then() method after saving the user data, but actually it's called to run the callbacks when the promise is fulfilled.
But here you're using simple Parse.Object, so either you've to use Parse.Promise, or if you want to use only simple Parse.Object when something like:-
users.save({
username: "Jake Cutter"
}, {
success: function(userObject) {
alert('The save was successful');
},
error: function(userObject, error) {
// The save failed. Error is an instance of Parse.Error.
// Do something if you want to do on error
}
});
For details you can check:-
https://www.parse.com/docs/js/symbols/Parse.Object.html#save
https://www.parse.com/docs/js/symbols/Parse.Promise.html#then
Okay, I awarded Indra the bounty, but here's the full answer for more context. This is an annoying problem, but you can solve it.
First, the form should use onsubmit.
<form method="post" onsubmit="formSubmit();">
Second, your function should use Indra's method to save data. But, you need event.preventDefault(); before it.
event.preventDefault();
userList.save({
username: "Peter Adams"
}, {
success: function(userList) {
alert('Success');
},
error: function(userList, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
You can use jquery to store the form values and create a sub class of your parse class and also a new parse object to store the values in parse.
Example:
<form id="contact-form" >
First name:<br>
<input type="text" name="firstname" id="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname">
email:<br>
<input type="text" name="email" id="email">
<input type="submit" value="Get Access" />
</form>
Javascript code:
Parse.initialize("--KEY--", "--KEY--");
var Subscribers = Parse.Object.extend('Subscribers'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val()
};
//create new Parse object
subscribers = new Subscribers();
//match the key values from the form, to your parse class, then save it
subscribers.save(data, {
//if successful
success: function(parseObj) {
alert(subscribers.get('firstname') + " " + subscribers.get('lastname') + " " + subscribers.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
});
});