jquery saving form input into an array of objects then displaying them, getting uncaught typeError - javascript

I am currently working on a bootstrap-styled form that allows a person to enter a handler and a comment.It has a button that, when clicked, will call a jquery event handler that saves the handler,comment, and Date.now() in an object that will be pushed in the array users.
However, I keep getting
"Uncaught TypeError: Cannot read property 'handler' of undefined at HTMLButtonElement.,at HTMLButtonElement.dispatch,at HTMLButtonElement.v.handle."
The error is from the .js file line : $("#display").val......
Form and display area code
<form>
<div class="form-group">
<label for="exampleFormControlInput1">handle</label>
<input type="text" class="form-control" id="handle" placeholder="#joe">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Comment</label>
<textarea class="form-control" id="comm" rows="3" placeholder="Bad match last night, Joe sucked"></textarea>
</div>
<button id="button1" type="submit" class="btn btn-primary">Post</button>
</form>
<h1 id="display"></h1>
jquery .js file
$(document).ready(
function(){
var users = [];
$("#button1").click(function(){
var person={
handler:$("#handle").val(),
comment:$("#comm").val(),
postDate:Date.now()
};
users.push(person);
$("#display").val(users[0].person.handler+"<br>"+users[0].person.comment);
});
});
I am new to jquery and thus I am not sure how to fix this error.

users[0].person.handler should be users[0].handler. The variable is named person, but the array itself doesn't care about that. Same thing for users[0].person.comment.
Edit: Also, you might need an preventDefault() call to stop the page from refreshing (unless that's what you want.
$("#button1").click(function(e){
e.preventDefault();
var person = {
handler:$("#handle").val(),
comment:$("#comm").val(),
postDate:Date.now()
};
users.push(person);
// i changed this to .html() because val() felt wrong
$("#display").html(users[0].handler+"<br>"+users[0].comment);
});

Use users[0].handler instead of users[0].person.handler. Although the variable is named person, what is actually pushed into the users Array is just a reference to the person Object.
Also, use the .html() method to set the innerHTML of the #display h1 as a h1 does not have a value attribute.
$(document).ready(
function(){
var users = [];
$("#button1").click(function(e){
var person={
handler:$("#handle").val(),
comment:$("#comm").val(),
postDate:Date.now()
};
users.push(person);
e.preventDefault();
$("#display").html(users[0].handler+"<br>"+users[0].comment);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="exampleFormControlInput1">handle</label>
<input type="text" class="form-control" id="handle" placeholder="#joe">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Comment</label>
<textarea class="form-control" id="comm" rows="3" placeholder="Bad match last night, Joe sucked"></textarea>
</div>
<button id="button1" type="submit" class="btn btn-primary">Post</button>
</form>
<h1 id="display"></h1>

Related

Create HTML text in an HTML form and open up the text in a Javascript alert box

I'm new to coding and need to create HTML text in an HTML form on a page and open up the text in a Javascript alert box. I've tried various code to no success. Here is what I've come up with so far which does not create a pop up alert box:
Here is the HTML and the JS:
Function myfunction1()
{
Let myfun1 = document.getElementById('sec1-input').value;
Alert(myfun1);
}
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
I'm not sure what do you want, but I'll show you how to make an alert window exactly as you're asking.
First of all you must consider several mistakes that you are making. JavaScript does not recognize the word Function because it is capitalized. The function keyword must be lowercase.
Here I leave you a referring link with JavaScript reserved words: https://www.w3schools.com/js/js_reserved.asp
On the other hand, I see that you are not using the form tag, which leads to two problems: technical and semantic. Here I leave you another link with reference to forms: https://www.w3schools.com/html/html_forms.asp
Finally, to achieve what you want you need to work with events, especially with the click event. Here I will leave you a reference link and the solution you want:
let button = document.querySelector('#sec1-btn1');
button.addEventListener('click', function(e) {
let val = document.querySelector('#sec1-input').value;
alert(val);
});
<form>
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input" />
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">
Alert Me!
</button>
</form>
You have not called the function anywhere. For it to work you need to use a listener.
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button onclick="myfunction1()" id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
<script>
function myfunction1() {
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1)
}
</script>
I added the onClick listener to button and now it works.
javaScript is case sensitive
function myfunction1()
{
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1);
}
<div class="form-group">
<label for="sec1-label"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" onClick="myfunction1()" class="btn btn-primary">Alert Me!</button>
also IDs of elements should not be the same , to assign same selector , use class and you also need to give your function to your element's event listener
You should not start javascript functions like alert with capital letters.
Put this piece of code instead of your button:
<button id="sec1-btn1" type="button" class="btn btn-primary" onclick="myfunction1()">Alert Me!</button>

jQuery data() not working to write to HTML element? [duplicate]

This question already has answers here:
Data attribute value updated by jquery is not visible in DOM
(2 answers)
Closed 4 years ago.
HTML:
<div class="modal">
<div class="search">
<input class="search-input" type="text" name="search" placeholder="Start typing to search">
</div>
</div>
<p class="add-new-item" data-catid="1">Add New Item</p>
jQuery:
$(".add-new-item").click(function() {
var catid = $(this).data("catid");
$(".modal").show();
$(".search-input").data("catid", catid);
});
The catid is being retrieved properly, but is not added to the input element. How come, and how do I solve this?
You need to use .attr() if you want the data to be visible in DOM.
Note: catid is not a "allowed" attribute. You should write data-catid read more about it here
$(".add-new-item").click(function() {
var catid = $(this).data("catid");
$(".modal").show();
$(".search-input").attr("data-catid", catid); // see changes in this line
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal">
<div class="search">
<input class="search-input" type="text" name="search" placeholder="Start typing to search">
</div>
</div>
<p class="add-new-item" data-catid="1">Add New Item</p>
UPDATE .data() does work! But as the docs say: the value is just set to the element doesn't means it's visible in DOM.
$(".add-new-item").click(function() {
var catid = $(this).data("catid");
$(".modal").show();
$(".search-input").data("catid", catid);
// now "catid" is set to .search-input
// it's just not visible in DOM
console.log('catId: ' + $(".search-input").data("catid"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal">
<div class="search">
<input class="search-input" type="text" name="search" placeholder="Start typing to search">
</div>
</div>
<p class="add-new-item" data-catid="1">Add New Item</p>
is not added to the input element
Correct, that's not how .data() works. When use .data() to add data, it's stored internally within jquery, so you read it again via jquery, not by looking at the html or using vanilla javascript to read it.
The initial value will be read from any matching data- attributes, but after that it uses the internal value.
Example:
$(".add-new-item").click(function() {
var catid = $(this).data("catid");
$(".search-input").data("catid", catid);
});
$(".readdata").click(function() {
console.log($(".search-input").data())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class="readdata">Read Data</button>
<button type='button' class="add-new-item" data-catid="1">Add Data</button>
<input class="search-input" type="text" name="search" placeholder="Start typing to search">
<button type='button' class="readdata">Read Data</button>
There's also a difference in that .data() will attempt to infer the data type for you (so you could get a number out) while .attr() will always be a string.

How to clear a form within an angular app that appears on click?

I have seen several tutorials on how to clear angular (version 1.4.0) forms, however.. none of them seem to work in my case. I am puzzled. The following form is display: none; to begin with, but comes into existence when the 'Add' button is clicked.
<div id="..." class="displayNone ...">
<form class="..." name="addFooForm">
<div class="...">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<br>
<div class="form-group">
<label>Foos</label>
<input type="text" class="..." id="..." ng-model="foo.value">
</div>
</div>
</div>
</div>
<div class="...">
...
<input type="button" value="Cancel" class="..." ng-click="resetAddFooForm()">
</div>
</form>
</div>
And in my controller, I have the following.
$scope.resetAddFooForm = function () {
// XXX:
console.log('about to reset the form');
$scope.foo = {};
// $scope.addFooForm.$setValidity();
// $scope.addFooForm.$setPristine();
// $scope.addFooForm.$setUntouched();
};
But, although the console.log message is being displayed. The form field is not being cleared. I have have even tried doing it directly as follows.
$scope.resetAddFooForm = function () {
// XXX:
console.log('about to reset the form');
$scope.fooVal = '';
// $scope.addFooForm.$setValidity();
// $scope.addFooForm.$setPristine();
// $scope.addFooForm.$setUntouched();
};
.. with the above html modified as follows.
<div class="form-group">
<label>Foos</label>
<input type="text" class="..." id="foo" ng-model="fooVal">
</div>
But nothing seems to be working. Is it perhaps because the $scope is different due to the form being dynamically inserted? But then how do I tackle that?
I just want to be able to clear the fields (and also clear the angular properties like dirty/pristine, etc) of this dynamically generated form.
Update:
I was able to send this from the html back to the controller, and then use it do what I wanted. So it appears that the problem may actually be to do with differing scopes.
<div class="...">
...
<input type="button" value="Cancel" class="..." ng-click="resetAddFooForm(this)">
</div>
And then have this retrieved the controller.
$scope.resetAddFooForm = function (elem) {
elem.foo = {};
elem.$setValidity();
elem.$setPristine();
elem.$setUntouched();
};
Any hints? Why do I need to send this, when I should really be able to simply use $scope. Why doesn't that work?
Initially declare empty object on your controller
$scope.foo = {}
then try empty it on reset
You can manually reset fields value.

Uncaught ReferenceError: reg is not defined

Im trying to build a login and registration form using jquery, ajax and php. But im getting this error when im pressing the button for registration.
<!-- Formular for signing up -->
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" name="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" name="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" name="newclub">
</div>
<button type="button" onClick='reg' class="btn btn-success">Sign up!</button>
</form>
And here is my script code
$(document).ready(function () {
// Function for registrate of new users
function reg(newusername, newpassword, newclub) {
$.post('class/callingClass.php', {
newusername: 'newusername',
newpassword: 'newpassword',
newclub: 'newclub'
});
};
});
Functions called from onXYZ attribute event handlers must be globals (it's one of the several reasons not to use them). Your reg function isn't a global, it's nicely contained within your ready callback (which is a Good Thing™, the global namespace is already really crowded and prone to conflicts).
Separately, onClick='reg' wouldn't work, it would have to be onClick='reg()'.
Instead, hook reg up dynamically via on:
<button type="button" id="btn-reg" class="btn btn-success">Sign up!</button>
<!-- Removed onClick, added id -->
and
$(document).ready(function () {
$("#btn-reg").on("click", reg); // <== Added
// Function for registrate of new users
function reg(newusername, newpassword, newclub) {
$.post('class/callingClass.php', {
newusername: 'newusername',
newpassword: 'newpassword',
newclub: 'newclub'
});
};
});
I've used an id above, but it doesn't have to be an id, that's just one way to look up the element. Any CSS selector that would find it would be fine.
Use onClick='reg()'. You need to do the function call here, which is the proper syntax.
Update : You also need to move your function outside of the $(document).ready(function(){}).

AJAX function not being called with button onclick function

I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.

Categories