Autocomplete values from other fields on form - jquery-autocomplete

I'd like to pass values from other input fields on the form to an input with jquery autocomplete feature. I try several ways but none of them work. Here is an example of what I have so far:
html:
<input type="text" class="fieldname"/>
<input type="text" class="fieldname"/>
<input type="text" class="fieldname"/>
<input type="text" class="fieldname"/>
<input type="text" class="autofieldnames"/>
<input type="text" class="autofieldnames"/>
jquery:
$(".fieldname").each(function() {
$(this).blur(function() {
var fieldnames = $(".fieldname").map(function(){ return this.value; }).get();
});
$(".autofieldnames").each(function() {
$(this).autocomplete({ source: fieldnames });
});
If I manually set the fieldnames array (i.e. fieldnames = ["aaa", "abc"];) autocomplete works but can't pass the values of from other fields into an array for some reason.

When you use the var keyword to declare a variable, it becomes a local variable. That means that fieldnames is only visible for the function that defined it - and not to the one that tries to read it so drop the var keyword.
However, since fieldnames is a very generic name, you shouldn't make it a global variable(you should try to avoid with making global variables with non-generic names as well, but it's even more dangerous with generically named variables). Therefore you should declare it as a local variable - but in a scope that's visible to all the functions that need it.
Something like this:
$(function(){
var fieldnames;
$(".fieldname").each(function() {
$(this).blur(function() {
fieldnames = $(".fieldname").map(function(){ return this.value; }).get();
});
});
$(".autofieldnames").each(function() {
$(this).autocomplete({ source: fieldnames });
});
});

It's solved. FYI, this is what I come up with:
html:
<input type="text" class="fieldname"/>
<input type="text" class="fieldname"/>
<input type="text" class="fieldname"/>
<input type="text" class="fieldname"/>
<input type="text" onfocus="getfieldnames"/>
<input type="text" onfocus="getfieldnames"/>
jquery:
function getfieldnames(obj) {
var fieldnames = $(".fieldname").map(function(){ return this.value; }).get();
$(obj).autocomplete({ source: fieldnames });
}

Related

How to get structured object using POST endpoint in SvelteKit?

when I'm using the POST endpoint from Sveltekit, I get a "flat" object as output. How can I get a "structured" Object instead ?
Let's assume the following code:
index.svelte
<div class="container">
<form method="post">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" />
<label for="lastname">Lastname</label>
<input type="text" name="lastname" />
<label for="dog">Dog 1</label>
<input type="text" name="dog" />
<label for="dog">Dog 2</label>
<input type="text" name="dog" />
<!-- ... -->
<button>Save</button>
</form>
</div>
index.js
export async function post({request}){
const data = Object.fromEntries(await request.formData());
console.log(data);
return{}
}
Ouput (what I'm calling "flat" object)
{ firstname: 'foo', lastname: 'bar', dog: 'teckel', dog: 'labrador' }
Instead of that output, how should I proceed to get the following one in my index.js
Expected output:
{
firstname: 'foo',
lastname: 'bar',
dogs: [ { dog: 'teckel' }, { dog: 'labrador' } ]
}
There are libraries that can perform a transform like this more or less automated. Some use conventions in the field names to parse the data into arrays and nested structures, others additionally use schemas to do type conversions or validation. E.g. to achieve an array of objects like this, one might set the names like this:
<label for="dog">Dog 1</label>
<input type="text" name="dogs[][dog]" />
<label for="dog">Dog 2</label>
<input type="text" name="dogs[][dog]" />
The [] Indicates that the field is part of an array, [dog] indicates that a property called dog is set on the element (.dog would also be reasonable).
So instead of calling Object.fromEntries you have to either parse the data yourself or find a library that does it for you. (Note that StackOverflow is not a place for library recommendations.)
Personally, I would avoid the synchronous form post and send JSON asynchronously instead, that way you can send in a fixed structure and receive that exact structure. Of course this requires binding/reading the form values yourself.

How to make a function of arrays in node js, handlebars

I was new to node.js and trying to render a list of fruits using hbs or handlebars in the client that came from the server
I wonder how to make a functions or event in every fruits
This is how i render the fruits
app.js
app.post('/getList', function(request, response) {
if (request.session.loggedin) {
//here i am sending the arrays to the client in the homepage
response.render('home',{fruits:fruits()});
} else {
response.send('Please login to view this page!');
}
This is my home.bhs
<form action="getList" method="POST">
<input type="text" name="username" placeholder="Username" >
<input type="password" name="password" placeholder="Password" >
<input type="submit" value="Insert">
<ul>{{#each fruits}}</ul>
<li>{{this}}</li>//Here are the list of frutis and i want to make them clickable
{{/each}}
</form>
});
This is my arrays
let fruits=()=>{
let list = ["apple","asdas","bbb","ccc","dddd"];
return list;
};

Getting a classname or attribute of a DOM element using post in Node and Express

I have a form that I am submitting using post. I can retrieve input values, however I also want to retrieve the class name or attribute of a div within a form.
html:
<form method='post' action='/formResult'>
<input type='text' name='someInput' />
<div class="stateAlpha" customAttr="alpha"></div> <!-- want 'alpha' -->
<button type="submit" class="btn btn-default">Submit</button>
</form>
node/express:
router.post('/formResult', function(req, res, next){
res.render('formResult', { someInput: req.body.someInput, someState: req.body.??? });
});
You'll need to intercept the submit event of the form, and put the class info into a hidden field. In pure JavaScript:
<form method='post' class='myForm' action='/formResult'>
<input type='text' name='someInput'>
<input type='hidden' name='state'>
<div class="stateAlpha" customAttr="alpha"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
document.querySelector('.myForm').addEventListener('submit', function(evt) {
var alpha = evt.target.querySelector('[customAttr="alpha"]');
var hiddenState = evt.target.querySelector('[name="state"]');
hiddenState.value = alpha.classList.join(' ');
});
</script>
Note that I added a class to the form, and used that to select the form; that's because you may have more than one form on the page, and you want to select the right one. Also note that inside the submit listener, I don't use document as the base of my selection, but evt.target; that's because you might have elements with customAttr='alpha' elsewhere in your document.
Once I have the div with the class you want to identify, I get the hidden input element, and set it's value property to the div's class list (remember any element can have more than one class, so classList is an array, which I just join using spaces).
If you're using jQuery, it gets a little shorter:
<form method='post' class='myForm' action='/formResult'>
<input type='text' name='someInput'>
<input type='hidden' name='state'>
<div class="stateAlpha" customAttr="alpha"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
$(document).ready(function() {
$('.myForm').on('submit', function() {
var $alpha = $(this).find('[customAttr="alpha"]');
$(this).find('[name="state"]')
.val($alpha.get(0).classList.join(' '));
});
});
</script>
The DOM is client-side and when you post the form only the values of the fields are posted, nothing else. To achieve what you are trying to do you can create a hidden field that stores the value of your class like this.
<input type="hidden" value="stateAlpha" name="myFieldName" />
This will then get sent in the form post.

Form: Keep posted parameters with Sails JS

I have file views/user/index.ejs
<form action="" method="POST>
<label>Username: </label>
<input type="text" class="form-control" value="<%= req.param('username') %>" name="username">
<input type="Submit" value="Submit">
</form>
Content of api/controllers/UserController.js
module.exports = {
index: function (req, res) {
sails.log(req.param('username'));
// Result: invest
}
}
Although the log print "invest", but the content of input is "undefined". I think that the array of requested parameters had not been kept.
Can anyone help me solve it? I will donate 2 eggs ;)
You can use this to pass variables to your view:
module.exports = {
index: function (req, res) {
return res.view("user/index", {username: req.param('username')});
}
}
In your view:
<input type="text" class="form-control" value="<%= username %>" name="username">

Can't update user model in express?

I'm trying to do a put request to update a user model but instead my router just sends another get request.
Here's my router
router.get('/update', isLoggedIn, function(req, res) {
res.render('update.ejs', {
user : req.user // get the user out of session and pass to template
});
});
router.put('/update', function(req, res) {
var username = req.body.username;
var profile_type = req.body.prof_type;
var pic = req.body.profile_pic;
var aboutme = req.body.whoami;
console.log(req.body.whoami);
User.findById(req.params.id,function(err, userup){
if (!userup)
return next(new Error("Couldn't load user"));
else {
userup.username = username;
userup.prof_type = profile_type;
userup.profile_pic = pic;
userup.whoami = aboutme;
userup.save(function(err) {
if (err)
console.log('error on update');
else
console.log('successful update');
});
}
});
res.redirect('/profile');
});
Here's my html input form
<form action="/update" method="put">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username">
</div>
<div class="form-group">
<h2> Pick a type of profile</h2>
<input type="radio" class="form-control" name="prof_type" value="true">Tutor<br>
<input type="radio" class="form-control" name="prof_type" value="false">Student
</div>
<div class="form-group">
<label>Link to profile picture</label>
<input type="text" class="form-control" name="profilepic">
</div>
<div class="form-group">
<label>About me</label>
<textarea name="whoami" class="form-control">Enter text here </textarea>
</div>
<button type="submit" class="btn btn-warning btn-lg">Update</button>
</form>
I've also tried changing them to be /update/:username, however, after I click the update button with the fields, I GET this address
http://localhost:3000/update?username=bob&prof_type=false&profilepic=bob&whoami=bob
Not sure why I'm not updating the model or even why it's not putting. Any help is much appreciated, thanks!
HTML only supports GET and POST requests. See the specification for details:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET
method. The keyword post, mapping to the state POST, indicating the
HTTP POST method. The invalid value default for these attributes is
the GET state. The missing value default for the method attribute is
also the GET state. (There is no missing value default for the
formmethod attribute.)
You can use the PUT method only with an ajax request. For example in jQuery:
$.ajax({
url: '/update',
type: 'PUT',
success: function(result) {
// Do something with the result
}
});

Resources